diff --git a/website/astro.config.mjs b/website/astro.config.mjs index 7075377..25f9312 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -10,7 +10,7 @@ export default defineConfig({ integrations: [ starlight({ title: 'Claude Kit', - description: 'The open-source AI dev toolkit for Claude Code. Ship faster with 27+ commands, 7 modes, and 34+ skills. Free forever.', + description: 'The open-source AI dev toolkit for Claude Code. 43 skills, 20 agents, 7 modes — structure that makes Claude Code production-ready. Free forever.', social: [ { icon: 'github', label: 'GitHub', href: 'https://github.com/duthaho/claudekit' } ], @@ -37,148 +37,31 @@ export default defineConfig({ items: [ { label: 'Introduction', slug: 'getting-started/introduction' }, { label: 'Installation', slug: 'getting-started/installation' }, - { label: 'Quick Start', slug: 'getting-started/quick-start' }, { label: 'Configuration', slug: 'getting-started/configuration' }, ], }, { - label: 'Commands', - collapsed: false, + label: 'Workflows', items: [ - { label: 'Overview', slug: 'commands/overview' }, - { - label: 'Development', - collapsed: true, - items: [ - { label: '/feature', slug: 'commands/feature' }, - { label: '/fix', slug: 'commands/fix' }, - { label: '/review', slug: 'commands/review' }, - { label: '/test', slug: 'commands/test' }, - { label: '/refactor', slug: 'commands/refactor' }, - { label: '/debug', slug: 'commands/debug' }, - { label: '/tdd', slug: 'commands/tdd' }, - ], - }, - { - label: 'Planning', - collapsed: true, - items: [ - { label: '/plan', slug: 'commands/plan' }, - { label: '/brainstorm', slug: 'commands/brainstorm' }, - { label: '/execute-plan', slug: 'commands/execute-plan' }, - { label: '/research', slug: 'commands/research' }, - ], - }, - { - label: 'Git & Deployment', - collapsed: true, - items: [ - { label: '/ship', slug: 'commands/ship' }, - { label: '/commit', slug: 'commands/commit' }, - { label: '/pr', slug: 'commands/pr' }, - { label: '/deploy', slug: 'commands/deploy' }, - { label: '/changelog', slug: 'commands/changelog' }, - ], - }, - { - label: 'Documentation', - collapsed: true, - items: [ - { label: '/doc', slug: 'commands/doc' }, - { label: '/api-gen', slug: 'commands/api-gen' }, - ], - }, - { - label: 'Utilities', - collapsed: true, - items: [ - { label: '/mode', slug: 'commands/mode' }, - { label: '/index', slug: 'commands/index-cmd' }, - { label: '/load', slug: 'commands/load' }, - { label: '/checkpoint', slug: 'commands/checkpoint' }, - { label: '/spawn', slug: 'commands/spawn' }, - { label: '/status', slug: 'commands/status' }, - { label: '/help', slug: 'commands/help' }, - { label: '/optimize', slug: 'commands/optimize' }, - { label: '/security-scan', slug: 'commands/security-scan' }, - ], - }, + { label: 'Planning & Building', slug: 'workflows/planning-and-building' }, + { label: 'Testing & Debugging', slug: 'workflows/testing-and-debugging' }, + { label: 'Reviewing & Shipping', slug: 'workflows/reviewing-and-shipping' }, ], }, { - label: 'MCP Integrations', - collapsed: false, + label: 'Reference', items: [ - { label: 'Overview', slug: 'mcp/overview' }, - { label: 'Context7', slug: 'mcp/context7' }, - { label: 'Sequential Thinking', slug: 'mcp/sequential' }, - { label: 'Playwright', slug: 'mcp/playwright' }, - { label: 'Memory', slug: 'mcp/memory' }, - { label: 'Filesystem', slug: 'mcp/filesystem' }, - { label: 'Command Integration', slug: 'mcp/integration' }, - ], - }, - { - label: 'Modes', - collapsed: false, - items: [ - { label: 'Overview', slug: 'modes/overview' }, - { label: 'Default', slug: 'modes/default' }, - { label: 'Brainstorm', slug: 'modes/brainstorm' }, - { label: 'Token-Efficient', slug: 'modes/token-efficient' }, - { label: 'Deep Research', slug: 'modes/deep-research' }, - { label: 'Implementation', slug: 'modes/implementation' }, - { label: 'Review', slug: 'modes/review' }, - { label: 'Orchestration', slug: 'modes/orchestration' }, - ], - }, - { - label: 'Skills', - collapsed: true, - items: [ - { label: 'Overview', slug: 'skills/overview' }, - { - label: 'Methodology', - collapsed: true, - items: [ - { label: 'Brainstorming', slug: 'skills/methodology/brainstorming' }, - { label: 'Writing Plans', slug: 'skills/methodology/writing-plans' }, - { label: 'Executing Plans', slug: 'skills/methodology/executing-plans' }, - { label: 'TDD', slug: 'skills/methodology/tdd' }, - { label: 'Systematic Debugging', slug: 'skills/methodology/systematic-debugging' }, - { label: 'Code Review', slug: 'skills/methodology/code-review' }, - ], - }, - { - label: 'Languages', - collapsed: true, - items: [ - { label: 'Python', slug: 'skills/languages/python' }, - { label: 'TypeScript', slug: 'skills/languages/typescript' }, - { label: 'JavaScript', slug: 'skills/languages/javascript' }, - ], - }, - { - label: 'Frameworks', - collapsed: true, - items: [ - { label: 'React', slug: 'skills/frameworks/react' }, - { label: 'Next.js', slug: 'skills/frameworks/nextjs' }, - { label: 'FastAPI', slug: 'skills/frameworks/fastapi' }, - { label: 'Django', slug: 'skills/frameworks/django' }, - ], - }, + { label: 'Skills', slug: 'reference/skills' }, + { label: 'Agents', slug: 'reference/agents' }, + { label: 'Modes', slug: 'reference/modes' }, + { label: 'MCP Servers', slug: 'reference/mcp-servers' }, ], }, { label: 'Customization', - collapsed: true, items: [ - { label: 'Overview', slug: 'customization/overview' }, - { label: 'Creating Commands', slug: 'customization/creating-commands' }, - { label: 'Creating Modes', slug: 'customization/creating-modes' }, { label: 'Creating Skills', slug: 'customization/creating-skills' }, - { label: 'CLAUDE.md Reference', slug: 'customization/claude-md' }, + { label: 'Creating Agents & Modes', slug: 'customization/creating-agents-and-modes' }, ], }, ], diff --git a/website/src/content/docs/commands/api-gen.md b/website/src/content/docs/commands/api-gen.md deleted file mode 100644 index 7008da1..0000000 --- a/website/src/content/docs/commands/api-gen.md +++ /dev/null @@ -1,422 +0,0 @@ ---- -title: /api-gen -description: Generate API endpoints, documentation, or client code from specifications ---- - -# /api-gen - -## Purpose - -Generate API endpoints, documentation, or client code from specifications. Accelerates API development by creating boilerplate code, OpenAPI specs, and client SDKs. - -## Usage - -```bash -/api-gen [resource-name-or-spec] -``` - -## Arguments - -- **resource-name-or-spec**: - - Resource name: `User`, `Order`, `Product` - Generate CRUD API - - OpenAPI spec path: `openapi.yaml` - Generate from specification - - Description: `"User management API"` - Generate from description - -## Workflow - -### Step 1: Define Resource - -1. **Identify resource properties** - - Field names and types - - Required vs optional - - Validation rules - -2. **Define relationships** - - One-to-many - - Many-to-many - - Foreign keys - -3. **Determine operations** - - CRUD operations needed - - Custom endpoints - - Business logic - -### Step 2: Generate Code - -1. **Create model/schema** - - Database model - - Validation schema - - Type definitions - -2. **Create routes/endpoints** - - HTTP methods - - Path parameters - - Request/response handling - -3. **Add validation** - - Input validation - - Type checking - - Error handling - -4. **Generate tests** - - Endpoint tests - - Validation tests - - Error case tests - -### Step 3: Document - -1. **Create OpenAPI spec** - - Endpoint descriptions - - Request/response schemas - - Authentication - -2. **Add examples** - - Request examples - - Response examples - - cURL commands - -3. **Document errors** - - Error codes - - Error messages - - Resolution steps - -## Examples - -### Generate CRUD API for Resource - -```bash -/api-gen User -``` - -Creates: -- `src/models/user.ts` - Data model -- `src/routes/user.ts` - API routes -- `src/controllers/user.ts` - Business logic -- `tests/user.test.ts` - Test suite -- `docs/api/user.md` - API documentation - -### Generate from OpenAPI Spec - -```bash -/api-gen openapi.yaml -``` - -Generates code matching the specification. - -### Generate with Description - -```bash -/api-gen "Product catalog API with categories and tags" -``` - -Creates API based on natural language description. - -## Output - -```markdown -## API Generated: User Management - -### Endpoints Created - -| Method | Path | Description | -|--------|------|-------------| -| GET | /api/users | List all users | -| POST | /api/users | Create new user | -| GET | /api/users/:id | Get user by ID | -| PUT | /api/users/:id | Update user | -| DELETE | /api/users/:id | Delete user | -| GET | /api/users/:id/posts | Get user's posts | - -### Files Created - -#### Model -- `src/models/user.ts` - ```typescript - export interface User { - id: string; - email: string; - name: string; - createdAt: Date; - updatedAt: Date; - } - - export const UserSchema = z.object({ - email: z.string().email(), - name: z.string().min(1).max(100), - }); - ``` - -#### Routes -- `src/routes/user.ts` - ```typescript - router.get('/users', listUsers); - router.post('/users', validateBody(UserSchema), createUser); - router.get('/users/:id', getUser); - router.put('/users/:id', validateBody(UserSchema), updateUser); - router.delete('/users/:id', deleteUser); - ``` - -#### Controller -- `src/controllers/user.ts` - ```typescript - export async function createUser(req, res) { - const user = await db.user.create({ - data: req.body, - }); - res.status(201).json(user); - } - // ... other handlers - ``` - -#### Tests -- `tests/user.test.ts` - ```typescript - describe('User API', () => { - it('should create user', async () => { - const res = await request(app) - .post('/api/users') - .send({ email: 'test@example.com', name: 'Test' }); - expect(res.status).toBe(201); - expect(res.body).toHaveProperty('id'); - }); - }); - ``` - -#### Documentation -- `docs/api/user.md` - Full API documentation - -### OpenAPI Specification - -Generated `openapi.yaml`: -```yaml -openapi: 3.0.0 -info: - title: User API - version: 1.0.0 -paths: - /api/users: - get: - summary: List all users - responses: - '200': - description: Success - content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/User' - post: - summary: Create new user - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateUser' - responses: - '201': - description: Created -``` - -### Next Steps - -1. ✅ API endpoints generated -2. 🔧 Add authentication middleware -3. 🔧 Implement business validation -4. 🔧 Add pagination to list endpoint -5. 📝 Review and customize as needed -``` - -## Generation Modes - -### CRUD Generation -```bash -/api-gen Product -``` -Full Create, Read, Update, Delete operations - -### Spec-Based Generation -```bash -/api-gen swagger.json -``` -Generate from existing OpenAPI/Swagger spec - -### Client Generation -```bash -/api-gen --client openapi.yaml -``` -Generate TypeScript/Python client SDK - -### Documentation Only -```bash -/api-gen --docs-only api/ -``` -Generate documentation for existing endpoints - -## Flags - -| Flag | Description | -|------|-------------| -| `--framework=[express\|fastapi\|nestjs]` | Target framework | -| `--db=[postgres\|mongodb\|prisma]` | Database/ORM | -| `--auth` | Include authentication | -| `--client` | Generate client SDK | -| `--docs-only` | Documentation only | -| `--test-framework=[jest\|vitest\|pytest]` | Testing framework | - -## Advanced Examples - -### Express + PostgreSQL + Auth - -```bash -/api-gen Order \ - --framework=express \ - --db=postgres \ - --auth -``` - -### FastAPI + MongoDB - -```bash -/api-gen Product \ - --framework=fastapi \ - --db=mongodb -``` - -### Generate Client SDK - -```bash -/api-gen --client openapi.yaml -``` - -Creates TypeScript client: -```typescript -import { UserAPI } from './generated/client'; - -const api = new UserAPI({ baseUrl: 'http://localhost:3000' }); -const users = await api.getUsers(); -const user = await api.createUser({ - email: 'test@example.com', - name: 'Test User' -}); -``` - -## Resource Definition - -When generating from resource name, you'll be asked: - -```markdown -### Define Resource: User - -**Fields:** -1. email (string, required, unique) -2. name (string, required) -3. role (enum: user|admin, optional, default: user) -4. createdAt (datetime, auto) - -**Relationships:** -- Has many: Post -- Belongs to: Organization (optional) - -**Custom Endpoints:** -- POST /users/:id/verify-email -- POST /users/:id/reset-password - -**Validation:** -- Email must be valid format -- Name: 1-100 characters -- Password: min 8 characters - -Proceed with generation? (y/n) -``` - -## OpenAPI Templates - -### Complete Endpoint - -```yaml -/api/orders: - post: - summary: Create new order - tags: - - Orders - security: - - bearerAuth: [] - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateOrder' - examples: - basic: - value: - items: - - productId: "123" - quantity: 2 - shippingAddress: - street: "123 Main St" - city: "New York" - responses: - '201': - description: Order created - content: - application/json: - schema: - $ref: '#/components/schemas/Order' - '400': - description: Invalid input - '401': - description: Unauthorized -``` - -## Best Practices - -1. **Start with Design**: Define API before generating -2. **Review Generated Code**: Don't blindly accept all generated code -3. **Customize**: Generated code is a starting point -4. **Add Business Logic**: Implement domain-specific validation -5. **Security**: Add authentication and authorization -6. **Testing**: Extend generated tests with edge cases - -## Use Cases - -### Rapid Prototyping - -```bash -# Quickly scaffold multiple resources -/api-gen User -/api-gen Post -/api-gen Comment -``` - -### API-First Development - -```bash -# Design spec, then generate -# 1. Create openapi.yaml -# 2. Generate code -/api-gen openapi.yaml -``` - -### Client SDK Distribution - -```bash -# Generate client for API consumers -/api-gen --client openapi.yaml -``` - -### Documentation Generation - -```bash -# Document existing API -/api-gen --docs-only src/api/ -``` - -## Related Commands - -- [/doc](/claudekit/commands/doc) - Generate documentation -- [/feature](/claudekit/core-commands/feature) - Full feature development -- [/test](/claudekit/core-commands/test) - Generate tests -- [/review](/claudekit/core-commands/review) - Review generated code diff --git a/website/src/content/docs/commands/brainstorm.md b/website/src/content/docs/commands/brainstorm.md deleted file mode 100644 index 5920a95..0000000 --- a/website/src/content/docs/commands/brainstorm.md +++ /dev/null @@ -1,303 +0,0 @@ ---- -title: /brainstorm -description: Interactive design session using one-question-at-a-time methodology ---- - -# /brainstorm - -Start an interactive brainstorming session to refine rough ideas into fully-formed designs through collaborative dialogue. - -## Purpose - -The `/brainstorm` command uses a proven one-question-at-a-time methodology to help you design features, architectures, and solutions. It guides you through thoughtful decision-making via sequential questions and validates designs incrementally. - -## Usage - -```bash -/brainstorm [topic or feature to design] -``` - -## Arguments - -- **topic**: The topic, feature, or problem you want to brainstorm about - -## How It Works - -The brainstorming process follows three phases: - -### Phase 1: Understanding - -**Goal:** Clarify requirements through sequential questioning - -The assistant asks **one question at a time** and waits for your response before proceeding. Questions are typically multiple-choice to reduce cognitive load. - -**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)" - -You: "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 - -The assistant presents 2-3 approaches with their pros and cons, leading with the recommended option: - -```markdown -## Approach 1: JWT-based (Recommended) -- Stateless, highly scalable -- Works well with microservices -- Cons: Can't revoke instantly - -## Approach 2: Session-based -- Easy revocation control -- Simpler mental model -- Cons: Requires session store (Redis/DB) - -Which approach aligns better with your goals? -``` - -### Phase 3: Design Presentation - -**Goal:** Present validated design incrementally - -The design is presented in digestible 200-300 word sections: -1. Architecture overview -2. Component breakdown -3. Data flow -4. Error handling -5. Testing considerations - -You validate each section before moving to the next. - -## Core Principles - -### YAGNI Ruthlessly - -Features are aggressively pruned: -- Questions every "nice to have" -- Starts with minimal viable design -- "We might need this later" means remove it - -### One Question at a Time - -Sequential questioning produces better results: -- Gives you time to think deeply -- Prevents overwhelming with choices -- Creates natural conversation flow - -### Multiple-Choice Preference - -Structured options when possible: -- Reduces cognitive load -- Surfaces the assistant's understanding -- Makes decisions concrete - -## Output - -After the design is validated, a design document is created: - -```markdown -# Design: [Feature Name] -Date: [YYYY-MM-DD] - -## Summary -[2-3 sentence overview] - -## Architecture -[Architecture decisions made] - -## Components -[Component breakdown with responsibilities] - -## Data Flow -[How data moves through the system] - -## Error Handling -[Error scenarios and handling strategies] - -## Testing Strategy -[How the feature will be tested] - -## Open Questions -[Any remaining unknowns] -``` - -## 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` | - -### 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 | - -## Examples - -### Quick Feature Design - -```bash -/brainstorm --quick "simple file upload feature" -``` - -Runs a short session (2-3 questions) to design a straightforward file upload. - -### Comprehensive Architecture Design - -```bash -/brainstorm --comprehensive "authentication system design" -``` - -Runs an extensive session (10+ questions) exploring architecture thoroughly. - -### Design with Custom Depth - -```bash -/brainstorm --depth=4 "microservices architecture" -``` - -Runs a comprehensive session with 8-10 questions exploring the microservices approach. - -### Save Design to File - -```bash -/brainstorm --save=docs/payment-design.md "payment integration" -``` - -Creates a design document and saves it to the specified file. - -### Deep Research Mode - -```bash -/brainstorm --mode=deep-research "distributed caching strategy" -``` - -Uses deep-research mode for thorough analysis with citations. - -## Workflow Integration - -### Brainstorm → Plan → Execute - -1. **Design the feature:** - ```bash - /brainstorm "OAuth authentication" - ``` - -2. **Create detailed implementation plan:** - ```bash - /plan --detailed "implement OAuth from design doc" - ``` - -3. **Execute with automation:** - ```bash - /execute-plan path/to/plan.md - ``` - -### Research → Brainstorm → Plan - -1. **Research options:** - ```bash - /research --compare "state management libraries" - ``` - -2. **Design the solution:** - ```bash - /brainstorm "state management architecture" - ``` - -3. **Plan implementation:** - ```bash - /plan "implement state management" - ``` - -## When to Use - -**Good use cases:** -- Designing new features with unclear requirements -- Exploring architectural decisions -- Evaluating multiple approaches -- Refining vague ideas into concrete designs -- Making technology choices - -**When NOT to use:** -- Clear "mechanical" processes with known implementation -- Simple bug fixes with obvious solutions -- Tasks with explicit requirements already defined - -For these cases, use direct implementation instead. - -## Best Practices - -### Prepare Context -Before brainstorming, have ready: -- Current architecture understanding -- Constraints (performance, budget, timeline) -- Related features or systems -- Team capabilities - -### Engage Actively -- Take time to think through each question -- Ask for clarification when needed -- Push back if suggestions don't fit -- Validate each section before moving on - -### Document Decisions -- Save designs to version control -- Include rationale for decisions -- Note rejected alternatives -- Track open questions - -### Follow Through -After brainstorming: -1. Commit design document to repo -2. Share with team for feedback -3. Use `/plan --detailed` for implementation planning -4. Reference design during development - -## Tips for Better Sessions - -1. **Be specific** about constraints and requirements -2. **Mention existing systems** that need integration -3. **State preferences** if you have strong opinions -4. **Ask "why"** to understand recommendations -5. **Take breaks** for complex designs (use `--checkpoint`) - -## Related Commands - -- [/plan](/claudekit/commands/plan) - Create implementation plans from designs -- [/execute-plan](/claudekit/commands/execute-plan) - Execute plans with automation -- [/research](/claudekit/commands/research) - Research technologies before designing -- [/review](/claudekit/commands/review) - Review existing designs - -## Customization - -Brainstorming behavior can be customized via `CLAUDE.md`: -- Question style (sequential vs all-at-once) -- Default depth level -- Required design sections -- Output format preferences - -See the [Configuration Guide](/claudekit/configuration) for details. diff --git a/website/src/content/docs/commands/changelog.md b/website/src/content/docs/commands/changelog.md deleted file mode 100644 index c5190b1..0000000 --- a/website/src/content/docs/commands/changelog.md +++ /dev/null @@ -1,427 +0,0 @@ ---- -title: /changelog -description: Auto-generate changelog entries from git commits with proper categorization ---- - -# /changelog - -Automatically generate beautiful, user-friendly changelogs from your git commit history. - -## Purpose - -Creates changelog entries by: -- Analyzing git commit messages -- Categorizing changes by type -- Generating user-friendly descriptions -- Linking to PRs and issues -- Following [Keep a Changelog](https://keepachangelog.com/) format - -Perfect for release notes, version documentation, and keeping users informed. - -## Usage - -```bash -/changelog [version or range] -``` - -**Generate for latest changes:** -```bash -/changelog -``` - -**Generate for specific version:** -```bash -/changelog v1.2.0 -``` - -**Generate since last tag:** -```bash -/changelog since:v1.1.0 -``` - -## Arguments - -| Argument | Description | Example | -|----------|-------------|---------| -| `[version]` | Version number for release | `v1.2.0`, `2.0.0` | -| `since:[tag]` | Changes since specific tag | `since:v1.1.0` | -| `[date]` | Changes since date | `since:2024-01-01` | -| (none) | Changes since last tag | `/changelog` | - -## Workflow - -### Step 1: Analyze Commits - -Retrieves commits in the specified range: - -```bash -# Since last tag -git describe --tags --abbrev=0 -git log [last-tag]..HEAD --oneline - -# Or custom range -git log v1.1.0..HEAD --oneline -``` - -### Step 2: Categorize Changes - -Groups commits by type: - -| Category | Commit Types | Description | -|----------|-------------|-------------| -| **Added** | `feat` | New features | -| **Changed** | `refactor`, `perf` | Improvements, changes | -| **Fixed** | `fix` | Bug fixes | -| **Removed** | `remove` | Removed features | -| **Security** | `security` | Security fixes | -| **Deprecated** | `deprecate` | Deprecations | - -### Step 3: Generate User-Friendly Descriptions - -Transforms technical commits into readable descriptions: - -**Commit:** -``` -feat(auth): add OAuth2 support for Google and GitHub providers -``` - -**Changelog entry:** -``` -- OAuth2 authentication support for Google and GitHub (#123) -``` - -### Step 4: Link References - -Automatically links: -- Pull requests: `(#123)` -- Issues: References `Closes #456` → Links to #456 -- Commits: Links to full commit hash - -## Examples - -### Generate Latest Version - -```bash -/changelog v1.2.0 -``` - -**Output:** -```markdown -## [1.2.0] - 2024-01-15 - -### Added -- OAuth2 authentication support for Google and GitHub (#123) -- Dark mode theme switching (#125) -- Export data feature for user profiles (#127) -- Real-time notifications using WebSockets (#130) - -### Changed -- Improved database query performance by 40% (#124) -- Updated user interface with modern design (#126) -- Migrated from REST to GraphQL for better flexibility (#129) - -### Fixed -- Null pointer crash in user profile endpoint (#122) -- Memory leak in WebSocket connections (#128) -- Timezone display issues in date formatting (#131) - -### Security -- Patched XSS vulnerability in comment system (#132) -- Updated authentication token generation (#133) -``` - -### Generate Since Last Tag - -```bash -/changelog -``` - -Automatically finds last tag and generates changelog from there: - -```markdown -## [Unreleased] - -### Added -- New export functionality (#142) - -### Fixed -- Bug in date picker component (#143) -``` - -### Generate Since Specific Tag - -```bash -/changelog since:v1.1.0 -``` - -```markdown -## [1.2.0] - 2024-01-15 - -Changes since v1.1.0 (released 2023-12-01) - -### Added -- Feature A (#140) -- Feature B (#141) - -### Changed -- Improvement A (#145) - -### Fixed -- Bug A (#146) -- Bug B (#147) - -**Full Changelog**: https://github.com/org/repo/compare/v1.1.0...v1.2.0 -``` - -### Generate Since Date - -```bash -/changelog since:2024-01-01 -``` - -```markdown -## Changes Since 2024-01-01 - -### Added -- Features added this month - -### Fixed -- Bugs fixed this month -``` - -### Full Release Example - -Major version release with breaking changes: - -```bash -/changelog v2.0.0 -``` - -```markdown -## [2.0.0] - 2024-01-15 - -### ⚠️ BREAKING CHANGES -- Authentication API changed from v1 to v2 (#150) -- Database schema updated - migration required (#151) -- Minimum Node.js version now 18+ (#152) - -### Added -- New GraphQL API with comprehensive schema (#153) -- Advanced search with filters and sorting (#154) -- User roles and permissions system (#155) - -### Changed -- Complete UI redesign with improved UX (#156) -- Migrated to TypeScript for better type safety (#157) -- Updated all dependencies to latest versions (#158) - -### Fixed -- Multiple security vulnerabilities patched (#159) -- Performance issues under high load (#160) - -### Removed -- Legacy REST API endpoints (deprecated in v1.5) (#161) -- Internet Explorer support (#162) - -### Migration Guide -See [MIGRATION.md](./MIGRATION.md) for upgrade instructions. - -**Full Changelog**: https://github.com/org/repo/compare/v1.9.0...v2.0.0 -``` - -## Changelog Format - -Follows [Keep a Changelog](https://keepachangelog.com/) format: - -```markdown -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -### Added -- Features in development - -## [1.2.0] - 2024-01-15 - -### Added -- New features in this version - -### Changed -- Changes in existing functionality - -### Deprecated -- Soon-to-be removed features - -### Removed -- Removed features - -### Fixed -- Bug fixes - -### Security -- Security patches - -## [1.1.0] - 2023-12-01 - -... - -[Unreleased]: https://github.com/org/repo/compare/v1.2.0...HEAD -[1.2.0]: https://github.com/org/repo/compare/v1.1.0...v1.2.0 -[1.1.0]: https://github.com/org/repo/releases/tag/v1.1.0 -``` - -## Output - -After generating the changelog: - -```markdown -## Changelog Generated - -**Version**: v1.2.0 -**Date**: 2024-01-15 -**Commits Analyzed**: 23 - -### Summary -- **Added**: 4 features -- **Changed**: 3 improvements -- **Fixed**: 5 bugs -- **Security**: 2 patches - -### File Updated -`CHANGELOG.md` - New section added at top - -### Next Steps -1. Review generated changelog -2. Edit for clarity if needed -3. Commit the changelog -4. Tag the release -``` - -## Integration with Releases - -### Create Release with Changelog - -```bash -# Generate changelog -/changelog v1.2.0 - -# Create git tag -git tag -a v1.2.0 -m "Release v1.2.0" - -# Push tag -git push origin v1.2.0 - -# Create GitHub release -gh release create v1.2.0 \ - --title "Version 1.2.0" \ - --notes-file CHANGELOG.md -``` - -### Automated Release Notes - -The changelog can be used for: -- GitHub Releases -- GitLab Release Notes -- NPM package releases -- Documentation sites -- Email announcements - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--format=[style]` | Output format | `/changelog --format=github v1.2.0` | -| `--output=[file]` | Output file | `/changelog --output=RELEASE.md` | -| `--template=[file]` | Custom template | `/changelog --template=.github/changelog.md` | -| `--include-authors` | Include contributor names | `/changelog --include-authors` | - -## Format Options - -### Standard (Keep a Changelog) -```markdown -### Added -- Feature description (#123) -``` - -### GitHub Release -```markdown -## What's Changed -* Feature description by @username in #123 -``` - -### Compact -```markdown -- Add: Feature description (#123) -- Fix: Bug description (#124) -``` - -## Commit Message Requirements - -For best results, use [Conventional Commits](https://www.conventionalcommits.org/): - -``` -type(scope): description - -[optional body] - -[optional footer] -``` - -**Examples:** -``` -feat(auth): add OAuth2 support -fix(api): handle null users -docs(readme): update installation -refactor(db): optimize queries -``` - -## Related Commands - -- [/ship](/claudekit/commands/ship/) - Ship with auto-generated commits -- [/commit](/claudekit/commands/commit/) - Create conventional commits -- [/deploy](/claudekit/commands/deploy/) - Deploy with release notes - -## Tips - -**Use conventional commits**: The better your commit messages, the better the generated changelog. - -**Review before committing**: Always review and edit the generated changelog for clarity. - -**Link to issues**: Reference issues in commits to auto-link in changelog. - -**Keep it user-focused**: Edit technical language to be user-friendly. - -**Group related changes**: Combine similar commits into single changelog entries. - -**Highlight breaking changes**: Always call out breaking changes prominently. - -**Update regularly**: Generate changelog with each release, don't let it get stale. - -**Include migration guides**: For breaking changes, link to migration documentation. - -## Customization - -Modify changelog behavior in `CLAUDE.md`: - -```markdown -## Changelog Settings - -### Format -- Style: Keep a Changelog -- Include authors: Yes -- Link format: GitHub - -### Categories -- Added: feat -- Changed: refactor, perf -- Fixed: fix -- Security: security - -### Template -Use custom template from `.github/changelog-template.md` -``` diff --git a/website/src/content/docs/commands/checkpoint.md b/website/src/content/docs/commands/checkpoint.md deleted file mode 100644 index 31b3369..0000000 --- a/website/src/content/docs/commands/checkpoint.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: /checkpoint -description: Save and restore conversation context using git-based checkpoints ---- - -# /checkpoint - -## Purpose - -Save and restore conversation context using git-based checkpoints. Enables session recovery and state preservation for complex, multi-session work. - -## Usage - -```bash -/checkpoint [operation] [name] [flags] -``` - -## 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 | - -## Examples - -```bash -# Save current state -/checkpoint save auth-progress - -# Save with notes -/checkpoint save auth --notes="WIP: implementing token refresh" - -# Show all checkpoints -/checkpoint list - -# Restore a checkpoint -/checkpoint restore auth-progress - -# Remove old checkpoint -/checkpoint delete old-checkpoint - -# Preview what will be saved -/checkpoint save feature-x --dry-run -``` - -## 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 (e.g., `auth-oauth-integration`) -2. **Add Notes**: Future you will thank present you -3. **Checkpoint Often**: Before context switches or risky changes -4. **Clean Up**: Delete obsolete checkpoints regularly - -## Recovery Workflow - -When resuming work after a break: - -```bash -# 1. See what checkpoints exist -/checkpoint list - -# 2. Restore the relevant context -/checkpoint restore feature-auth - -# 3. Continue where you left off -# Context is loaded, files are restored -``` - -## Use Cases - -### Multi-Day Feature Work - -```bash -# End of day 1 -/checkpoint save oauth-day1 --notes="Completed user model, starting token service" - -# Start of day 2 -/checkpoint restore oauth-day1 -``` - -### Experimental Changes - -```bash -# Before trying risky refactor -/checkpoint save before-refactor - -# If refactor doesn't work out -/checkpoint restore before-refactor -``` - -### Context Switching - -```bash -# Save current work -/checkpoint save feature-payments - -# Switch to urgent bug -/fix "login timeout issue" - -# Return to feature work -/checkpoint restore feature-payments -``` - -## Limitations - -- Checkpoints use git stash (requires git repository) -- Large uncommitted changes may be slow to save/restore -- Metadata stored in `.claude/checkpoints/` -- Consider committing before checkpointing for safety - -## Related Commands - -- [/load](/claudekit/commands/load) - Load specific components -- [/status](/claudekit/commands/status) - Check current project status -- [/spawn](/claudekit/commands/spawn) - Launch parallel tasks diff --git a/website/src/content/docs/commands/commit.md b/website/src/content/docs/commands/commit.md deleted file mode 100644 index b298737..0000000 --- a/website/src/content/docs/commands/commit.md +++ /dev/null @@ -1,362 +0,0 @@ ---- -title: /commit -description: Create a well-formatted commit with auto-generated conventional commit messages ---- - -# /commit - -Smart commit creation with auto-generated messages that follow the Conventional Commits standard. - -## Purpose - -Creates well-structured commits by: -- Analyzing your staged changes -- Auto-generating descriptive commit messages -- Following Conventional Commits format -- Adding helpful metadata and co-author attribution - -Perfect for when you want to commit without creating a PR (use `/ship` for the full workflow). - -## Usage - -```bash -/commit [optional hint] -``` - -## Arguments - -| Argument | Description | Example | -|----------|-------------|---------| -| `[hint]` | Optional hint for message focus | `auth`, `bugfix`, `refactor` | - -The hint helps guide the message generation but isn't required. - -## Workflow - -### Step 1: Analyze Changes - -The command first examines your repository state: - -```bash -git status -git diff --staged -git log --oneline -5 -``` - -This provides context about: -- What files are staged -- What changes were made -- Recent commit history - -### Step 2: Categorize Changes - -Automatically determines the commit type: - -| Type | Used For | -|------|----------| -| `feat` | New features | -| `fix` | Bug fixes | -| `docs` | Documentation only | -| `style` | Formatting, whitespace | -| `refactor` | Code restructuring without behavior change | -| `test` | Adding or updating tests | -| `chore` | Maintenance (deps, config, etc.) | - -### Step 3: Generate Message - -Creates a message following this format: - -``` -type(scope): subject - -body (optional) - -footer (optional) -``` - -**Components:** -- **Type**: From categorization above -- **Scope**: Affected area (auth, api, ui, etc.) -- **Subject**: Concise description (max 50 chars) -- **Body**: Detailed explanation with bullet points -- **Footer**: Issue references, breaking changes - -### Step 4: Create Commit - -Executes the commit with the generated message: - -```bash -git commit -m "$(cat <<'EOF' -type(scope): subject - -- Change 1 -- Change 2 - -🤖 Generated with Claude Code - -Co-Authored-By: Claude -EOF -)" -``` - -## Examples - -### Feature Commit - -**Staged changes:** New authentication files - -```bash -/commit auth -``` - -**Generated commit:** -``` -feat(auth): add password reset functionality - -- Add reset token generation -- Implement email sending -- Add rate limiting for reset requests - -🤖 Generated with Claude Code - -Co-Authored-By: Claude -``` - -### Bug Fix Commit - -**Staged changes:** Fix in profile endpoint - -```bash -/commit -``` - -**Generated commit:** -``` -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 - -🤖 Generated with Claude Code - -Co-Authored-By: Claude -``` - -### Refactor Commit - -**Staged changes:** Database code reorganization - -```bash -/commit refactor -``` - -**Generated commit:** -``` -refactor(database): extract query builders - -Split large database service into focused modules -for better maintainability and testing. - -🤖 Generated with Claude Code - -Co-Authored-By: Claude -``` - -### Documentation Commit - -**Staged changes:** README updates - -```bash -/commit docs -``` - -**Generated commit:** -``` -docs(readme): update installation instructions - -- Add prerequisites section -- Update configuration examples -- Fix broken links - -🤖 Generated with Claude Code - -Co-Authored-By: Claude -``` - -### Test Commit - -**Staged changes:** New test files - -```bash -/commit test -``` - -**Generated commit:** -``` -test(auth): add missing login tests - -- Add test for invalid credentials -- Add test for locked account -- Add test for expired session - -🤖 Generated with Claude Code - -Co-Authored-By: Claude -``` - -### Chore Commit - -**Staged changes:** Package updates - -```bash -/commit -``` - -**Generated commit:** -``` -chore(deps): update dependencies - -- Update React to 18.2 -- Update TypeScript to 5.3 -- Remove unused packages - -🤖 Generated with Claude Code - -Co-Authored-By: Claude -``` - -## Commit Message Guidelines - -### Subject Line Rules -- **Max 50 characters** - Keep it concise -- **Imperative mood** - "Add" not "Added" or "Adds" -- **No period** at the end -- **Capitalize** the first letter -- **Be specific** - Describe what changed, not why - -### Body Guidelines -- **Wrap at 72 characters** for readability -- **Explain what and why**, not how -- **Use bullet points** for multiple changes -- **Reference issues** when applicable - -### Good vs Bad Examples - -**Good:** -``` -feat(auth): add OAuth2 support - -- Implement Google and GitHub providers -- Add token refresh mechanism -- Update user model for OAuth data - -Closes #123 -``` - -**Bad:** -``` -Added oauth stuff - -I added oauth because we need it. It works now. -``` - -## Output - -After creating the commit, you'll see: - -```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, the command validates: - -- [ ] No secrets in staged files -- [ ] No debug statements (`console.log`, `debugger`, `print`) -- [ ] No unintentional TODO comments -- [ ] Code is properly formatted - -If issues are found, you'll be prompted to fix them first. - -## Amending Commits - -If pre-commit hooks modify files automatically (like formatters), the command handles it: - -```bash -# Stage modified files and amend -git add -A -git commit --amend --no-edit -``` - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--mode=[mode]` | Behavioral mode | `/commit --mode=token-efficient` | -| `--format=[fmt]` | Output format | `/commit --format=concise` | -| `--no-verify` | Skip pre-commit hooks | `/commit --no-verify` | - -## Related Commands - -- [/ship](/claudekit/commands/ship/) - Full workflow with commit + PR -- [/pr](/claudekit/commands/pr/) - Create PR from commits -- [/changelog](/claudekit/commands/changelog/) - Generate changelog from commits - -## Tips - -**Use descriptive hints**: While optional, hints like `auth`, `api`, or `ui` help generate more accurate messages. - -**Review before committing**: The command shows you the message before creating the commit, so you can verify it's accurate. - -**Amend if needed**: If the generated message isn't quite right, you can amend it: -```bash -git commit --amend -``` - -**Customize format**: Modify commit message format in `CLAUDE.md` under "Git Conventions". - -**Breaking changes**: For breaking changes, the footer will include: -``` -BREAKING CHANGE: describe the breaking change -``` diff --git a/website/src/content/docs/commands/debug.md b/website/src/content/docs/commands/debug.md deleted file mode 100644 index c873875..0000000 --- a/website/src/content/docs/commands/debug.md +++ /dev/null @@ -1,312 +0,0 @@ ---- -title: /debug -description: Analyze and debug errors, exceptions, and unexpected behavior ---- - -# /debug - Debug Command - -## Purpose - -Analyze and debug errors, exceptions, or unexpected behavior with systematic investigation and root cause analysis. This is a streamlined version of `/fix` focused on diagnosis and investigation. - -## Usage - -```bash -/debug [error message or description] -``` - -## Arguments - -- `[error message]` - Stack trace or error output -- `[description]` - Natural language description of unexpected behavior - -## How It Works - -The `/debug` command follows a systematic 3-step debugging process: - -### Step 1: Analyze Error - -1. **Parse Error Message and Stack Trace** - - Extracts error type (TypeError, ValueError, etc.) - - Identifies file and line number - - Reads stack trace for execution path - -2. **Identify Error Location** - - Pinpoints the exact failing line - - Examines surrounding code - - Checks function context - -3. **Understand Error Type** - - Categorizes error (logic, runtime, type, etc.) - - Identifies common causes for this error type - - Notes relevant language-specific behavior - -### Step 2: Investigate - -1. **Trace Execution Path** - - Follows code flow from entry to error - - Maps variable states at each step - - Identifies where state becomes invalid - -2. **Check Related Code** - - Examines caller functions - - Reviews recent changes to area - - Searches for similar patterns - -3. **Form Hypotheses** - - Lists possible root causes - - Ranks by likelihood - - Identifies tests to validate each hypothesis - -### Step 3: Fix - -1. **Implement Minimal Fix** - - Addresses root cause - - Keeps changes focused - - Preserves existing behavior - -2. **Verify Fix Works** - - Tests the specific error case - - Runs related tests - - Checks for side effects - -3. **Add Regression Test** - - Creates test that would catch this bug - - Documents the error scenario - - Ensures test fails without fix - -## Debug Output Format - -```markdown -## Debug Report - -### Error -``` -TypeError: Cannot read property 'email' of undefined - at getUserEmail (src/services/UserService.ts:45) - at processUser (src/api/users.ts:23) -``` - -### Analysis -The error occurs when trying to access `user.email` but `user` is undefined. - -### Location -**File**: `src/services/UserService.ts` -**Line**: 45 -**Function**: `getUserEmail` - -### Execution Trace -1. API receives request → `processUser()` -2. Calls `getUserEmail(userId)` -3. Inside getUserEmail: - ```typescript - const user = this.fetchUser(userId); // Missing await! - return user.email; // user is a Promise, not User object - ``` - -### Root Cause -**Missing `await` keyword** - `fetchUser()` is async but wasn't awaited, so `user` is a Promise object instead of a User object. - -### Hypotheses Tested -1. ✅ Missing await - Confirmed by checking function signature -2. ❌ User doesn't exist - Would be null, not undefined -3. ❌ Database error - Would throw different error - -### Fix -```typescript -// Before -async getUserEmail(userId: string) { - const user = this.fetchUser(userId); - return user.email; -} - -// After -async getUserEmail(userId: string) { - const user = await this.fetchUser(userId); - if (!user) { - throw new NotFoundError(`User ${userId} not found`); - } - return user.email; -} -``` - -### Verification -```bash -# Test the fix -pnpm test src/services/UserService.test.ts - -# Run full suite -pnpm test -``` - -### Prevention -Added regression test: `test_getUserEmail_awaits_user_fetch` -``` - -## Common Debug Patterns - -### Null/Undefined Errors - -```typescript -// Symptom -Cannot read property 'X' of undefined - -// Common Causes -- Missing await on async function -- Object not initialized -- API returned null -- Array/object access out of bounds - -// Investigation -1. Check if value should exist -2. Trace where it's set -3. Verify async operations -``` - -### Type Errors - -```python -# Symptom -TypeError: unsupported operand type(s) for +: 'int' and 'str' - -# Common Causes -- Mixed types in operation -- Missing type conversion -- Unexpected input type - -# Investigation -1. Print types at error line -2. Check input sources -3. Verify type conversions -``` - -### Race Conditions - -```typescript -// Symptom -Intermittent failures, works sometimes - -// Common Causes -- Async operations out of order -- Shared state without locking -- Component unmounted during async - -// Investigation -1. Add logging to trace timing -2. Check for missing awaits -3. Look for shared mutable state -``` - -### Infinite Loops/Recursion - -```python -# Symptom -RecursionError: maximum recursion depth exceeded - -# Common Causes -- Missing base case -- Base case never reached -- Infinite loop condition - -# Investigation -1. Check base/termination condition -2. Verify condition can be met -3. Add iteration counter logging -``` - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--depth=[1-5]` | Investigation depth (1=quick, 5=exhaustive) | `--depth=4` | -| `--trace` | Show detailed execution trace | `--trace` | -| `--hypothesis` | Show all hypotheses considered | `--hypothesis` | -| `--format=[fmt]` | Output format (concise/detailed) | `--format=concise` | - -### Flag Examples - -```bash -# Quick debug with minimal output -/debug --depth=1 --format=concise "error message" - -# Deep investigation with full trace -/debug --depth=5 --trace --hypothesis "intermittent failure" - -# Detailed analysis -/debug --format=detailed "TypeError in auth.ts" -``` - -## Examples - -### Runtime Error - -**Input:** -```bash -/debug IndexError: list index out of range in process_items at line 42 -``` - -**Output:** -1. Identifies array access issue -2. Traces loop bounds -3. Finds off-by-one error -4. Suggests fix with correct range - -### Unexpected Behavior - -**Input:** -```bash -/debug "User authentication succeeds but session not created" -``` - -**Output:** -1. Traces auth flow -2. Finds session creation after response sent -3. Identifies async timing issue -4. Recommends await before response - -### Intermittent Issue - -**Input:** -```bash -/debug --depth=5 "Test fails randomly, passes on retry" -``` - -**Output:** -1. Analyzes for race conditions -2. Checks for time-dependent logic -3. Reviews shared state access -4. Identifies missing await in test setup - -## When to Use - -Use `/debug` when you need to: - -- **Investigate an error** without immediately fixing it -- **Understand why** something breaks -- **Diagnose intermittent** issues -- **Trace execution** paths -- **Form hypotheses** about root causes - -Use `/fix` instead when you want to: - -- Fix the issue immediately -- Add regression tests -- Complete the full fix workflow - -## Deliverables - -After running `/debug`, you receive: - -1. **Error Analysis** - Detailed breakdown of the error -2. **Execution Trace** - Step-by-step flow to error -3. **Root Cause** - Explanation of why it fails -4. **Hypotheses** - Tested theories about cause -5. **Fix Recommendation** - Suggested solution (optional) -6. **Prevention Strategy** - How to avoid similar issues - -## Related Commands - -- [/fix](/claudekit/commands/fix) - Complete fix workflow with tests -- [/test](/claudekit/commands/test) - Generate tests after debugging -- [/review](/claudekit/commands/review) - Review code for potential issues -- [/refactor](/claudekit/commands/refactor) - Improve code after fix diff --git a/website/src/content/docs/commands/deploy.md b/website/src/content/docs/commands/deploy.md deleted file mode 100644 index 5be304b..0000000 --- a/website/src/content/docs/commands/deploy.md +++ /dev/null @@ -1,467 +0,0 @@ ---- -title: /deploy -description: Deploy your application to staging or production with comprehensive safety checks ---- - -# /deploy - -Safe, automated deployments with built-in validation, health checks, and rollback capabilities. - -## Purpose - -Handles deployment workflow including: -- Pre-deployment validation -- Build verification -- Security scanning -- Environment-specific deployment -- Post-deployment health checks -- Monitoring and rollback - -Ensures safe deployments with comprehensive checks at every stage. - -## Usage - -```bash -/deploy [environment] -``` - -## Arguments - -| Argument | Description | -|----------|-------------| -| `staging` | Deploy to staging environment | -| `production` | Deploy to production (requires confirmation) | -| `preview` | Deploy to preview/ephemeral environment | - -## Workflow - -### Pre-Deploy Checks - -Before any deployment, the command validates: - -#### 1. Build Verification - -**Python projects:** -```bash -python -m build -python -m pytest -``` - -**Node.js projects:** -```bash -pnpm build -pnpm test -``` - -**Validation:** -- [ ] Build completes successfully -- [ ] No build warnings -- [ ] Build artifacts are generated -- [ ] Output size is reasonable - -#### 2. Run Tests - -Executes full test suite: - -```bash -# Python -pytest -v --cov=src --cov-report=term - -# Node.js -pnpm test -pnpm test:e2e -``` - -**Requirements:** -- [ ] All tests pass -- [ ] Coverage meets threshold (80%+) -- [ ] No skipped tests -- [ ] E2E tests pass - -#### 3. Security Scan - -Checks for vulnerabilities: - -**Node.js:** -```bash -npm audit --audit-level=high -pnpm audit --audit-level=high -``` - -**Python:** -```bash -pip-audit -safety check -``` - -**Validation:** -- [ ] No high/critical vulnerabilities -- [ ] Dependencies are up to date -- [ ] No known security issues - -#### 4. Environment Verification - -**Staging:** -- [ ] Staging branch is up to date -- [ ] No merge conflicts -- [ ] Environment variables configured - -**Production:** -- [ ] Production branch matches main/master -- [ ] All PRs merged and approved -- [ ] Release notes prepared -- [ ] Rollback plan ready - -### Deploy Process - -#### Staging Deployment - -Automated deployment to staging: - -```bash -# Build for staging -pnpm build:staging - -# Deploy to staging environment -# (Implementation depends on your hosting) -``` - -**Common platforms:** - -**Vercel:** -```bash -vercel deploy --prod=false -``` - -**Cloudflare Pages:** -```bash -wrangler pages deploy dist --project-name=app-staging -``` - -**AWS:** -```bash -aws deploy create-deployment \ - --application-name my-app \ - --deployment-group-name staging -``` - -**Heroku:** -```bash -git push heroku-staging main -``` - -#### Production Deployment - -**Requires explicit confirmation:** - -``` -⚠️ Production Deployment -This will deploy to production environment. - -Environment: production -Version: v1.2.3 -Commits: 15 new commits since last deploy - -Continue? (yes/no): -``` - -**After confirmation:** - -```bash -# Tag release -git tag -a v1.2.3 -m "Release v1.2.3" -git push origin v1.2.3 - -# Build for production -pnpm build:production - -# Deploy -# (Platform-specific deployment) -``` - -### Post-Deploy Validation - -After deployment, automated checks run: - -#### 1. Health Checks - -```bash -# Check application health -curl https://app.example.com/health - -# Expected response: -{ - "status": "healthy", - "version": "v1.2.3", - "timestamp": "2024-01-15T10:30:00Z" -} -``` - -#### 2. Smoke Tests - -Essential functionality tests: - -- [ ] Homepage loads -- [ ] API endpoints respond -- [ ] Authentication works -- [ ] Database connection active -- [ ] Critical features functional - -#### 3. Monitor Logs - -Watch for errors: - -```bash -# Check recent logs -# (Platform-specific log viewing) - -# Look for: -# - Error patterns -# - Performance issues -# - Unexpected warnings -``` - -## Examples - -### Deploy to Staging - -```bash -/deploy staging -``` - -**Output:** -```markdown -## Deployment Started - -**Environment**: staging -**Version**: main@abc1234 -**Time**: 2024-01-15 10:30:00 UTC - -### Pre-Deploy Checks -- [x] Build successful -- [x] Tests passing (127 tests) -- [x] Security scan clean -- [x] Environment variables verified - -### Deploying... -- [x] Build artifacts created -- [x] Uploading to staging -- [x] Deployment complete - -### Post-Deploy Checks -- [x] Health check passed -- [x] Smoke tests passed -- [x] No errors in logs - -## Deployment Complete - -**URL**: https://staging.example.com -**Status**: Healthy -**Response Time**: 234ms - -### Next Steps -1. Test the staging deployment -2. Verify all features work -3. Deploy to production when ready -``` - -### Deploy to Production - -```bash -/deploy production -``` - -**Interactive confirmation:** -```markdown -⚠️ Production Deployment - -**Environment**: production -**Version**: v1.2.3 -**Branch**: main - -### Changes Since Last Deploy -- feat(auth): add OAuth2 support (#123) -- fix(api): handle null users (#124) -- perf(db): optimize queries (#125) - -**15 commits** | **5 PRs** | **3 contributors** - -### Pre-Deploy Checklist -- [x] All tests passing -- [x] Security scan clean -- [x] Changelog updated -- [x] Team notified - -Continue with production deployment? (yes/no): yes -``` - -**After confirmation:** -```markdown -## Deployment Started - -**Environment**: production -**Version**: v1.2.3 -**Time**: 2024-01-15 14:30:00 UTC - -### Pre-Deploy Checks -- [x] Build successful -- [x] Tests passing (127 tests) -- [x] Security scan clean -- [x] Release tagged - -### Deploying... -- [x] Build artifacts created -- [x] Uploading to production -- [x] Deployment complete -- [x] Cache invalidated - -### Post-Deploy Checks -- [x] Health check passed -- [x] Smoke tests passed -- [x] Performance metrics normal -- [x] No errors in logs - -## Deployment Complete - -**URL**: https://example.com -**Version**: v1.2.3 -**Status**: Healthy -**Response Time**: 189ms - -### Monitoring -- [ ] Watch error rates (5 min) -- [ ] Monitor performance (15 min) -- [ ] Check user feedback - -### Rollback Plan -If issues occur: -```bash -/deploy rollback v1.2.2 -``` -``` - -### Deploy to Preview - -For preview deployments (PR previews): - -```bash -/deploy preview -``` - -Creates ephemeral environment for testing: - -```markdown -## Preview Deployment - -**Environment**: preview-pr-123 -**Branch**: feature/new-ui -**URL**: https://preview-pr-123.example.com - -### Status -- [x] Deployed successfully -- [x] Ready for testing - -**Expires**: 7 days -``` - -## Output - -Standard deployment output includes: - -```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 - -### Metrics -- **Build Time**: 2m 34s -- **Deploy Time**: 1m 12s -- **Total Time**: 3m 46s -- **Response Time**: 234ms - -### Next Steps -1. Test deployment -2. Monitor logs -3. Verify functionality -``` - -## Rollback - -If deployment issues occur: - -```bash -/deploy rollback [version] -``` - -**Example:** -```bash -/deploy rollback v1.2.2 -``` - -Reverts to previous version with zero-downtime. - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--skip-tests` | Skip test execution | `/deploy staging --skip-tests` | -| `--force` | Skip confirmations (dangerous!) | `/deploy production --force` | -| `--dry-run` | Simulate deployment | `/deploy production --dry-run` | -| `--tag=[version]` | Specify release tag | `/deploy production --tag=v1.3.0` | - -## Environment Configuration - -Configure deployment settings in `CLAUDE.md`: - -```markdown -## Deployment - -### Staging -- **URL**: https://staging.example.com -- **Platform**: Vercel -- **Branch**: main -- **Auto-deploy**: Yes - -### Production -- **URL**: https://example.com -- **Platform**: Vercel -- **Branch**: main -- **Auto-deploy**: No (manual approval) -- **Confirmation**: Required - -### Checks -- Required: tests, security scan, build -- Optional: performance benchmarks -``` - -## Related Commands - -- [/ship](/claudekit/commands/ship/) - Commit and create PR -- [/test](/claudekit/commands/test/) - Run tests -- [/changelog](/claudekit/commands/changelog/) - Generate release notes - -## Tips - -**Test on staging first**: Always deploy to staging before production. - -**Use dry-run**: Preview what will happen with `--dry-run` flag. - -**Monitor after deploy**: Watch logs and metrics for at least 15 minutes after production deploys. - -**Have a rollback plan**: Know how to quickly revert if issues occur. - -**Automate staging**: Let staging deploy automatically, but keep production manual. - -**Tag releases**: Use semantic versioning for production releases. - -**Update changelog**: Keep changelog current with each production deployment. - -**Notify team**: Alert team before production deployments. diff --git a/website/src/content/docs/commands/doc.md b/website/src/content/docs/commands/doc.md deleted file mode 100644 index f72e5ec..0000000 --- a/website/src/content/docs/commands/doc.md +++ /dev/null @@ -1,382 +0,0 @@ ---- -title: /doc -description: Generate or update documentation including API docs, README files, and code comments ---- - -# /doc - -## Purpose - -Generate or update documentation including API docs, README files, code comments, and technical specifications. Creates comprehensive, accurate documentation that helps developers understand and use the codebase effectively. - -## Usage - -```bash -/doc [target] -``` - -## Arguments - -- **target**: What to document - - File/function path: `src/services/auth.ts` - Document specific code - - `api` - Generate API documentation - - `readme` - Update README file - - `changelog` - Generate changelog from commits - - `all` - Document everything - -## Workflow - -### For Code Documentation - -#### 1. Analyze Code -- Read the code thoroughly -- Understand purpose and behavior -- Identify inputs and outputs -- Note side effects and edge cases - -#### 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 information - -### For Changelog - -#### 1. Analyze Commits -```bash -git log --oneline --since="last release" -``` - -#### 2. Categorize Changes -- Added -- Changed -- Fixed -- Removed - -## Examples - -```bash -# Document a specific file -/doc src/services/auth.ts - -# Generate API documentation -/doc api - -# Update README -/doc readme - -# Generate changelog -/doc changelog - -# Document all API endpoints -/doc api/ - -# Add docstrings to all functions in a module -/doc src/utils/ -``` - -## Documentation 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 - */ -function calculateDiscount(price: number, percentage: number): number { -``` - -### API Endpoint Documentation - -```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" - } -} -\`\`\` - -#### Parameters - -| Field | Type | Required | Description | -|-------|------|----------|-------------| -| items | array | Yes | Array of order items | -| items[].productId | string | Yes | Product identifier | -| items[].quantity | number | Yes | Quantity to order | -| shippingAddress | object | Yes | Delivery address | - -### Response (201 Created) - -\`\`\`json -{ - "id": "order_456", - "status": "pending", - "total": 99.99, - "createdAt": "2024-01-15T10:00:00Z" -} -\`\`\` - -### Error Responses - -| Status | Code | Description | -|--------|------|-------------| -| 400 | INVALID_ITEMS | Items array is empty or invalid | -| 401 | UNAUTHORIZED | Invalid or missing token | -| 422 | OUT_OF_STOCK | One or more items unavailable | -``` - -### 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 | -| retries | number | 3 | Number of retry attempts | -``` - -### Changelog Entry - -```markdown -## [1.2.0] - 2024-01-15 - -### Added -- Password reset functionality (#123) -- Email verification for new accounts -- Two-factor authentication support - -### Changed -- Improved error messages for validation failures -- Updated dependencies to latest versions -- Enhanced logging for debugging - -### Fixed -- Race condition in session handling (#456) -- Incorrect timezone in date displays -- Memory leak in WebSocket connections - -### Security -- Patched XSS vulnerability in user input -- Updated authentication token expiry -``` - -## Output - -```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 -- `refreshToken()` - Error scenarios - -#### API Documentation -- POST /api/auth/login -- POST /api/auth/logout -- POST /api/auth/refresh -- POST /api/auth/verify - -#### README Sections -- Installation instructions -- Quick start guide -- Configuration options -- Environment variables - -### Coverage - -- Functions documented: 15/18 (83%) -- Endpoints documented: 12/12 (100%) -- README completeness: 90% - -### Quality Checks - -✅ All examples tested and working -✅ Type annotations complete -✅ Error cases documented -✅ Links verified - -### Next Steps - -1. Add examples to remaining 3 functions -2. Create getting started tutorial -3. Add architecture diagram -4. Document deployment process -``` - -## Flags - -| Flag | Description | -|------|-------------| -| `--format=[md\|html\|openapi]` | Documentation format | -| `--update` | Update existing docs only | -| `--examples` | Include code examples | -| `--comprehensive` | Maximum detail level | - -## Documentation Types - -### Code Documentation -- Function/method docstrings -- Class documentation -- Module-level documentation -- Inline comments for complex logic - -### API Documentation -- Endpoint descriptions -- Request/response formats -- Authentication requirements -- Error codes and handling - -### User Documentation -- README files -- Getting started guides -- Configuration guides -- Troubleshooting guides - -### Technical Documentation -- Architecture diagrams -- Design decisions -- Database schemas -- Deployment guides - -## Best Practices - -1. **Keep It Current**: Update docs with code changes -2. **Include Examples**: Real, working code examples -3. **Document Edge Cases**: Error scenarios and limitations -4. **Clear Language**: Write for your audience -5. **Test Examples**: Ensure all code examples work -6. **Version Docs**: Match documentation to code versions - -## Use Cases - -### Onboarding New Developers - -```bash -# Generate comprehensive project documentation -/doc all -``` - -### Before Release - -```bash -# Update changelog and README -/doc changelog -/doc readme -``` - -### API Development - -```bash -# Document all API endpoints -/doc api -``` - -### Code Maintainability - -```bash -# Add docstrings to service layer -/doc src/services/ -``` - -## Related Commands - -- [/api-gen](/claudekit/commands/api-gen) - Generate API code and docs -- [/review](/claudekit/core-commands/review) - Review documentation quality -- [/help](/claudekit/commands/help) - Command help diff --git a/website/src/content/docs/commands/execute-plan.md b/website/src/content/docs/commands/execute-plan.md deleted file mode 100644 index be87a79..0000000 --- a/website/src/content/docs/commands/execute-plan.md +++ /dev/null @@ -1,338 +0,0 @@ ---- -title: /execute-plan -description: Execute detailed implementation plans using subagents with code review gates ---- - -# /execute-plan - -Execute a detailed implementation plan using fresh subagents per task with mandatory code review gates between tasks. - -## Purpose - -The `/execute-plan` command automates plan execution while maintaining high quality through systematic code reviews. It spawns fresh subagents for each task, preventing context pollution and ensuring focused implementation. - -## Usage - -```bash -/execute-plan [plan-file-path] -``` - -## Arguments - -- **plan-file-path**: Path to the plan file (created with `/plan --detailed`) - -## 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 to other tasks -- Easier to retry individual tasks - -### Why Code Review Between Tasks? - -- Catches issues early before they compound -- Ensures code matches intent -- Prevents technical debt accumulation -- Creates natural checkpoints for rollback - -## How It Works - -### Step 1: Load Plan - -1. Reads the plan file -2. Verifies plan is complete and approved -3. Creates TodoWrite tracking with all tasks -4. Sets first task to `in_progress` - -### Step 2: Execute Task (For Each Task) - -For each task in the plan: - -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 changes -3. **Subagent returns** completion summary - -### Step 3: Code Review - -After each task completes: - -1. Dispatch code-reviewer subagent -2. Review scope: **only changes from current task** -3. Reviewer returns findings categorized as: - - **Critical**: Must fix before proceeding - - **Important**: Should fix before proceeding - - **Minor**: Can fix later - -### Step 4: Handle Review Findings - -``` -IF Critical or Important issues found: - 1. Dispatch fix subagent for each issue - 2. Re-request code review - 3. Repeat until no Critical/Important issues - -IF only Minor issues: - 1. Note for later cleanup - 2. Proceed to next task -``` - -### Step 5: Mark Complete - -1. Update TodoWrite - mark task completed -2. Move to next task -3. Repeat from Step 2 - -### Step 6: Final Review - -After all tasks complete: - -1. Dispatch comprehensive code review -2. Review entire implementation against plan -3. Verify all success criteria met -4. Run full test suite -5. Use `finishing-development-branch` skill - -## Critical Rules - -### Never Skip Code Reviews - -Every single task must be reviewed before proceeding. No exceptions. - -### Never Proceed with Critical Issues - -Critical issues must be fixed immediately: -``` -implement → review → fix critical → re-review → proceed -``` - -### Never Run Parallel Implementation - -Tasks run **sequentially**, one at a time: -``` -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 - -### When a Task Fails - -1. Capture error details -2. Attempt fix (max 2 retries) -3. If still failing: - - Pause execution - - Report to user with: - - Which task failed - - Error details - - Suggested resolution - - Wait for user decision - -### When 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 - -During execution, you see real-time progress: - -```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 - -When execution completes: - -```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` works) - -## Examples - -### Execute a Saved Plan - -```bash -/execute-plan plans/user-authentication.md -``` - -Executes the detailed plan from the specified file. - -### After Creating a Plan - -```bash -# Step 1: Create detailed plan -/plan --detailed --save=plans/oauth.md "implement OAuth2 authentication" - -# Step 2: Execute the plan -/execute-plan plans/oauth.md -``` - -Complete workflow from planning to automated execution. - -### Resume After Pause - -If execution pauses due to an error: - -```bash -# Fix the issue manually, then resume -/execute-plan --resume plans/oauth.md -``` - -Resumes from the last completed task. - -## Best Practices - -### Before Execution - -1. **Review the plan** - Make sure it's accurate -2. **Check environment** - Tests run, dependencies installed -3. **Clean working directory** - Commit or stash changes -4. **Set aside time** - Don't interrupt during execution - -### During Execution - -1. **Monitor progress** - Watch for warnings or issues -2. **Don't interrupt** - Let tasks complete -3. **Review deferred items** - Note minor issues for cleanup - -### After Execution - -1. **Run full test suite** - Verify everything works -2. **Review deferred issues** - Fix minor items -3. **Manual testing** - Test critical paths -4. **Create PR** - Use `/ship` command - -## Workflow Integration - -### Complete Feature Development Flow - -```bash -# 1. Brainstorm design -/brainstorm "user authentication system" - -# 2. Create detailed plan -/plan --detailed --save=plans/auth.md "implement authentication from design" - -# 3. Execute plan with automation -/execute-plan plans/auth.md - -# 4. Ship to production -/ship "feat: add user authentication system" -``` - -### Plan Review Flow - -```bash -# 1. Create plan -/plan --detailed --save=plans/feature.md "feature description" - -# 2. Review plan with team -/review plans/feature.md - -# 3. Execute reviewed plan -/execute-plan plans/feature.md -``` - -## Troubleshooting - -### "Plan file not found" -- Check the file path is correct -- Use absolute paths or paths relative to repo root - -### "Plan not detailed enough" -- Plan must be created with `--detailed` flag -- Regular plans need manual execution - -### "Tests failing during execution" -- Check test environment is set up correctly -- Verify dependencies are installed -- May need to fix plan or environment - -### "Code review keeps failing" -- Review the critical issues being reported -- May need to revise the plan -- Consider pausing and fixing manually - -## Related Commands - -- [/plan](/claudekit/commands/plan) - Create detailed plans for execution -- [/brainstorm](/claudekit/commands/brainstorm) - Design features before planning -- [/ship](/claudekit/commands/ship) - Create PR after execution -- [/review](/claudekit/commands/review) - Review code or plans - -## Customization - -Execution behavior can be customized via `CLAUDE.md`: -- Review strictness levels -- Retry counts for failures -- Parallel task limits -- TDD enforcement - -See the [Configuration Guide](/claudekit/configuration) for details. diff --git a/website/src/content/docs/commands/feature.md b/website/src/content/docs/commands/feature.md deleted file mode 100644 index 1108fd3..0000000 --- a/website/src/content/docs/commands/feature.md +++ /dev/null @@ -1,203 +0,0 @@ ---- -title: /feature -description: End-to-end feature development workflow with planning, implementation, testing, and review ---- - -# /feature - Feature Development Workflow - -## Purpose - -Complete end-to-end feature development workflow that orchestrates planning, implementation guidance, testing, and code review. This command guides you through the entire lifecycle of building a new feature from requirements to merge-ready code. - -## Usage - -```bash -/feature [feature description or issue reference] -``` - -## Arguments - -- `[feature description]` - Natural language description of the feature to build -- `[issue reference]` - GitHub issue number or ticket ID - -## How It Works - -The `/feature` command executes a comprehensive 6-phase workflow: - -### Phase 1: Planning - -First, the command analyzes your feature request and creates an implementation plan: - -1. **Understand Requirements** - - Parses the feature description thoroughly - - Identifies acceptance criteria - - Lists assumptions that need validation - - Clarifies any ambiguous requirements with you - -2. **Explore Codebase** - - Finds related existing implementations - - Identifies patterns and conventions to follow - - Locates integration points - - Notes dependencies - -3. **Create Task Breakdown** - - Decomposes into atomic, verifiable tasks - - Orders tasks by dependencies - - Includes testing requirements - - Estimates complexity (S/M/L) - -4. **Track with TodoWrite** - All tasks are tracked for progress - -### 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 - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--mode=[mode]` | Use specific behavioral mode | `--mode=implementation` | -| `--depth=[1-5]` | Planning thoroughness level (1=quick, 5=exhaustive) | `--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 Examples - -```bash -# Implementation-focused mode with minimal prose -/feature --mode=implementation "add user profile page" - -# Thorough planning with session checkpoint -/feature --depth=5 --checkpoint "implement payment flow" - -# Quick feature with concise output -/feature --format=concise "add logging utility" -``` - -## Examples - -### Basic Feature - -**Input:** -```bash -/feature Add password reset functionality with email verification -``` - -**Output:** -1. Implementation plan with 8 tasks covering model, service, routes, email, tests -2. Step-by-step implementation of password reset flow -3. Tests for happy path and error cases -4. Updated API documentation -5. Commit message and PR description ready - -### Feature with Issue Reference - -**Input:** -```bash -/feature #142 - Add dark mode toggle -``` - -**Output:** -1. Fetches context from GitHub issue #142 -2. Creates plan based on acceptance criteria -3. Implements theme switching logic -4. Adds tests for theme persistence -5. Updates component documentation - -## Deliverables - -After running `/feature`, you receive: - -1. **Implementation Plan** - Structured task breakdown with estimates -2. **Code Changes** - Complete feature implementation -3. **Tests** - Comprehensive test coverage -4. **Documentation** - Updated docs and comments -5. **Commit/PR** - Ready for code review and merge - -## Related Commands - -- [/plan](/claudekit/commands/plan) - Create implementation plan only -- [/test](/claudekit/commands/test) - Generate tests for existing code -- [/review](/claudekit/commands/review) - Comprehensive code review -- [/tdd](/claudekit/commands/tdd) - Test-driven development approach diff --git a/website/src/content/docs/commands/fix.md b/website/src/content/docs/commands/fix.md deleted file mode 100644 index 9a54847..0000000 --- a/website/src/content/docs/commands/fix.md +++ /dev/null @@ -1,298 +0,0 @@ ---- -title: /fix -description: Smart debugging and bug fixing workflow with root cause analysis and regression tests ---- - -# /fix - Bug Fix Workflow - -## Purpose - -Intelligent debugging and bug fixing workflow that analyzes errors, identifies root causes, implements fixes, and adds regression tests to prevent recurrence. - -## Usage - -```bash -/fix [error message, bug description, or issue reference] -``` - -## Arguments - -- `[error message]` - Stack trace or error output from your application -- `[bug description]` - Natural language description of unexpected behavior -- `[issue reference]` - GitHub issue number or bug ticket ID - -## How It Works - -The `/fix` command executes a systematic 6-phase debugging workflow: - -### Phase 1: Error Analysis - -1. **Parse Error Information** - - Extracts error type and message - - Parses stack trace if available - - Identifies 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** - - Follows the code path to the error - - Identifies state at each step - - Finds where expectations diverge - -2. **Form Hypotheses** - - Lists possible causes ranked by likelihood - - Identifies minimal tests to validate each - -3. **Validate Hypothesis** - - Tests the most likely cause first - - Confirms root cause before fixing - - Doesn't fix symptoms only - -### Phase 3: Search Related Code - -1. **Find Similar Code** - - Searches for similar patterns - - Checks if same bug exists elsewhere - - Identifies 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** - - Fixes the root cause, not symptoms - - Keeps changes minimal and focused - - Considers edge cases - -2. **Add Defensive Code** (if appropriate) - - Input validation - - Null checks - - Error handling - -3. **Update Related Code** (if needed) - - Fixes same issue in similar code - - Updates shared utilities - -### Phase 5: Verification - -1. **Test the Fix** - - Verifies original error is resolved - - Checks related functionality - - Runs existing test suite - -2. **Add Regression Test** - - Writes test that would have caught this bug - - Includes edge cases discovered - - Ensures 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) - - Adds clarifying comments - - Documents non-obvious behavior - -## Common Fix Patterns - -### Null/Undefined Access - -```typescript -// Before - Crashes on null -const name = user.profile.name; - -// After - Safe with optional chaining -const name = user?.profile?.name ?? 'Unknown'; -``` - -### Missing Error Handling - -```python -# Before - Crashes on invalid JSON -data = json.loads(response.text) - -# After - Handles errors gracefully -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 - May update unmounted component -const data = await fetchData(); -setState(data); - -// After - Checks if still mounted -useEffect(() => { - let cancelled = false; - fetchData().then(data => { - if (!cancelled) setState(data); - }); - return () => { cancelled = true; }; -}, []); -``` - -### Off-by-One Error - -```python -# Before - IndexError on last iteration -for i in range(len(items) + 1): - process(items[i]) - -# After - Correct range -for i in range(len(items)): - process(items[i]) -# Or better: use iteration -for item in items: - process(item) -``` - -## 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 (1=quick, 5=exhaustive) | `--depth=4` | -| `--format=[fmt]` | Output format (concise/detailed) | `--format=concise` | -| `--skip-regression` | Skip regression test creation | `--skip-regression` | -| `--checkpoint` | Create checkpoint before fixing | `--checkpoint` | - -### Persona Options - -| Persona | Focus Area | -|---------|------------| -| `security` | Security vulnerabilities, OWASP top 10 | -| `performance` | Speed, memory usage, efficiency | -| `reliability` | Error handling, edge cases, resilience | - -### Flag Examples - -```bash -# Deep investigation for intermittent issues -/fix --mode=deep-research "intermittent timeout error" - -# Security-focused fix -/fix --persona=security "SQL injection vulnerability" - -# Thorough race condition analysis -/fix --depth=5 "race condition in auth flow" - -# Quick typo fix with minimal output -/fix --format=concise "typo in error message" -``` - -## Examples - -### Runtime Error - -**Input:** -```bash -/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 -5. Verification: All tests passing - -### Bug Description - -**Input:** -```bash -/fix Users can see deleted posts in their feed -``` - -**Output:** -1. Investigation: Traces feed generation logic -2. Root cause: Soft-delete flag not checked in feed query -3. Fix: Add WHERE clause filtering deleted posts -4. Tests: Verify deleted posts don't appear -5. Check: Scans for similar issues in other queries - -## Deliverables - -After running `/fix`, you receive: - -```markdown -## Bug Fix Complete - -### Issue -TypeError: Cannot read property 'email' of undefined - -### Root Cause -User object is undefined because async fetch wasn't awaited - -### Location -`src/services/UserService.ts:45` - getUserEmail method - -### Fix Applied - -**Before:** -```typescript -async getUserEmail(userId: string) { - const user = this.fetchUser(userId); // Missing await - return user.email; // Crashes if user is undefined -} -``` - -**After:** -```typescript -async getUserEmail(userId: string) { - const user = await this.fetchUser(userId); - if (!user) { - throw new NotFoundError(`User ${userId} not found`); - } - return user.email; -} -``` - -### Regression Test Added -`src/services/UserService.test.ts` - `test_getUserEmail_with_nonexistent_user_throws_error` - -### Verification -- [x] Original error no longer occurs -- [x] Existing tests pass -- [x] New regression test passes -- [x] No new issues introduced -``` - -## Related Commands - -- [/debug](/claudekit/commands/debug) - Deep debugging analysis -- [/test](/claudekit/commands/test) - Generate additional tests -- [/review](/claudekit/commands/review) - Code review for fixes -- [/refactor](/claudekit/commands/refactor) - Improve code after fix diff --git a/website/src/content/docs/commands/help.md b/website/src/content/docs/commands/help.md deleted file mode 100644 index b6e5163..0000000 --- a/website/src/content/docs/commands/help.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: /help -description: Display available commands and their usage ---- - -# /help - -## Purpose - -Display available commands and their usage. Get quick reference for Claude Kit commands or detailed help for specific commands. - -## Usage - -```bash -/help [command-name] -``` - -## Arguments - -- **command-name** (optional): Specific command to get help for. If omitted, shows all available commands. - -## Available Commands - -### Development Workflow - -| Command | Description | -|---------|-------------| -| `/feature` | Full feature development workflow | -| `/fix` | Debug and fix bugs | -| `/review` | Comprehensive code review | -| `/test` | Generate tests | -| `/tdd` | Test-driven development workflow | -| `/refactor` | Improve code structure | - -### Planning & Design - -| Command | Description | -|---------|-------------| -| `/plan` | Create detailed implementation plan | -| `/brainstorm` | Interactive design session | -| `/execute-plan` | Execute plan with subagents | -| `/research` | Technology research | - -### 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 | -| `/api-gen` | Generate API code and docs | - -### Security & Quality - -| Command | Description | -|---------|-------------| -| `/security-scan` | Scan for vulnerabilities | -| `/optimize` | Performance optimization | - -### Context Management - -| Command | Description | -|---------|-------------| -| `/mode` | Switch behavioral mode | -| `/index` | Generate project index | -| `/load` | Load components into context | -| `/checkpoint` | Save/restore session state | -| `/spawn` | Launch parallel tasks | - -### Utilities - -| Command | Description | -|---------|-------------| -| `/status` | Project status overview | -| `/help` | Display this help | - -## Examples - -```bash -# Show all commands -/help - -# Get help for specific command -/help feature - -# Get help for mode command -/help mode - -# Get help for checkpoint -/help checkpoint -``` - -## Getting Detailed Help - -For detailed help on a specific command: - -```bash -/help [command-name] -``` - -This will show: -- Command purpose -- Usage syntax -- Available arguments -- Supported flags -- Workflow steps -- Practical examples - -## Command Categories - -### Core Workflow -Commands for the main development cycle: `/feature`, `/fix`, `/review`, `/test` - -### Enhanced Methodology -Advanced workflows: `/plan --detailed`, `/brainstorm`, `/tdd`, `/execute-plan` - -### Context Management -Optimize your session: `/mode`, `/index`, `/load`, `/checkpoint`, `/spawn` - -### Quality & Security -Code quality tools: `/security-scan`, `/optimize`, `/review` - -### Documentation -Generate docs: `/doc`, `/api-gen` - -## Universal Flags - -Most commands support these flags: - -| Flag | Description | -|------|-------------| -| `--mode=[mode]` | Override behavioral mode | -| `--depth=[1-5]` | Thoroughness level | -| `--format=[fmt]` | Output format (concise/detailed/json) | -| `--save=[path]` | Save output to file | - -## Quick Start - -New to Claude Kit? Try these commands: - -```bash -# 1. See project structure -/index - -# 2. Check current status -/status - -# 3. Load a component to work on -/load api - -# 4. Start development -/feature "Add user authentication" -``` - -## Related Resources - -- **CLAUDE.md**: Project-specific configuration -- **Skills**: `.claude/skills/` directory -- **Modes**: `.claude/modes/` directory -- **Commands**: `.claude/commands/` directory - -## Need More Help? - -- Check command documentation in `/claudekit/commands/` -- Review skills in `/claudekit/skills/` -- Read methodology guides in `/claudekit/methodology/` -- See examples in project CLAUDE.md - -## Related Commands - -- [/status](/claudekit/commands/status) - Check project status -- [/mode](/claudekit/commands/mode) - Switch modes diff --git a/website/src/content/docs/commands/index-cmd.md b/website/src/content/docs/commands/index-cmd.md deleted file mode 100644 index a4b1e79..0000000 --- a/website/src/content/docs/commands/index-cmd.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: /index -description: Generate a comprehensive project structure index for faster navigation -slug: commands/index-cmd ---- - -# /index - -## Purpose - -Generate a comprehensive project structure index for faster navigation and context loading. Creates a `PROJECT_INDEX.md` file mapping the codebase structure. - -## Usage - -```bash -/index [flags] -``` - -## Workflow - -### Step 1: Scan Project Structure - -Scans the entire project directory structure, excluding: -- `node_modules/` -- `.git/` -- `__pycache__/` -- `dist/`, `build/`, `.next/` -- `venv/`, `.venv/` -- Coverage and cache directories - -### Step 2: Identify Key Components - -Categorizes 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 - -Identifies: -- Package managers and dependencies (package.json, requirements.txt, etc.) -- Internal import relationships between key files -- External service integrations - -### Step 4: Generate Index - -Creates `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 | - -## Examples - -```bash -# Generate standard project index -/index - -# Generate shallow index (3 levels deep) -/index --depth=3 - -# Include GraphQL files in the index -/index --include="*.graphql" - -# Save to custom location -/index --output=docs/INDEX.md -``` - -## Output - -After generating the index, you'll receive: -1. Index file location -2. Number of files indexed -3. Key components discovered -4. Suggestion to use `/load` to load specific components - -## Benefits - -- **Faster Navigation**: Quickly locate files and components -- **Context Loading**: Use with `/load` for efficient context management -- **Onboarding**: Help new team members understand codebase structure -- **Documentation**: Auto-generated architecture overview - -## Related Commands - -- [/load](/claudekit/commands/load) - Load specific components into context -- [/status](/claudekit/commands/status) - Check current project status diff --git a/website/src/content/docs/commands/load.md b/website/src/content/docs/commands/load.md deleted file mode 100644 index cb4eb2a..0000000 --- a/website/src/content/docs/commands/load.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: /load -description: Load specific project components into context for focused work ---- - -# /load - -## Purpose - -Load specific project components into context for focused work. Uses the project index to efficiently load relevant files. - -## Usage - -```bash -/load [component] [flags] -``` - -## Arguments - -- **component**: Can be a category name, file path, or pattern - - Category name: `api`, `models`, `services`, `utils`, `tests`, etc. - - File path: `src/services/user.ts` - - Pattern: `src/auth/*` - -## Workflow - -### Step 1: Check for Index - -First, checks if `PROJECT_INDEX.md` exists: -- If exists: Uses index for efficient loading -- If not: Suggests running `/index` first, or does quick scan - -### Step 2: Identify Component - -Parses 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 - -Reads the identified files and summarizes: -- File purposes -- Key exports/functions -- Dependencies -- Current state - -### Step 4: Context Summary - -Provides 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 | - -## Examples - -```bash -# Load all API routes -/load api - -# Load all data models -/load models - -# Load specific file -/load src/services/user.ts - -# Load auth + related files -/load auth --related - -# Load all key components -/load --all - -# Quick overview of everything -/load --all --shallow -``` - -## 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 - -The command suggests 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]" - -## Use Cases - -### Starting Work on a Feature - -```bash -# Load the entire authentication system -/load auth --related - -# Now you can work with full context -``` - -### Bug Investigation - -```bash -# Load the specific service and its tests -/load src/services/payment.ts -/load tests/payment.test.ts -``` - -### Code Review - -```bash -# Load all files in a directory -/load src/api/orders/ -``` - -### Architecture Understanding - -```bash -# Get overview of all components -/load --all --shallow -``` - -## Related Commands - -- [/index](/claudekit/commands/index) - Generate project structure index -- [/status](/claudekit/commands/status) - Check project status -- [/checkpoint](/claudekit/commands/checkpoint) - Save/restore session state diff --git a/website/src/content/docs/commands/mode.md b/website/src/content/docs/commands/mode.md deleted file mode 100644 index 5ba4a82..0000000 --- a/website/src/content/docs/commands/mode.md +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: /mode -description: Switch between behavioral modes to optimize responses for different task types ---- - -# /mode - -## Purpose - -Switch between behavioral modes to optimize responses for different task types. Modes adjust communication style, output format, and problem-solving approach. - -## Usage - -```bash -/mode [mode-name] -``` - -## Arguments - -- **mode-name** (optional): The mode to activate. If omitted, shows the current active mode. - -## Available Modes - -| Mode | Description | Best For | -|------|-------------|----------| -| `default` | Balanced standard behavior | General tasks | -| `brainstorm` | Creative exploration, more questions | Design, ideation | -| `token-efficient` | 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 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 | - -## Examples - -```bash -# Switch to brainstorm mode for design discussions -/mode brainstorm - -# Switch to efficient mode for cost savings -/mode token-efficient - -# Show current active mode -/mode - -# List all available modes -/mode --list - -# Reset to default mode -/mode default -``` - -## Mode Persistence - -- Modes persist for the entire 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 a single command: - -```bash -/feature --mode=implementation "Add login feature" -/review --mode=deep-research src/auth/ -/plan --mode=brainstorm "Design notification system" -``` - -## Recommended Workflows - -### Feature Development - -```bash -/mode brainstorm # Explore approaches -# [discuss design] -/mode implementation # Execute plan -# [write code] -/mode review # Check quality -# [review code] -``` - -### Bug Investigation - -```bash -/mode deep-research # Investigate thoroughly -# [analyze bug] -/mode implementation # Apply fix -# [fix bug] -/mode default # Return to normal -``` - -### Cost-Conscious Session - -```bash -/mode token-efficient # Set for session -# [work on multiple tasks] -/mode default # Reset when done -``` - -## Mode Files - -Mode definitions are stored 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 in your project. - -## Related Commands - -- [/help](/claudekit/commands/help) - Get help on any command -- [/status](/claudekit/commands/status) - Check project status diff --git a/website/src/content/docs/commands/optimize.md b/website/src/content/docs/commands/optimize.md deleted file mode 100644 index 2cb9a73..0000000 --- a/website/src/content/docs/commands/optimize.md +++ /dev/null @@ -1,295 +0,0 @@ ---- -title: /optimize -description: Analyze and optimize code performance ---- - -# /optimize - -## Purpose - -Analyze and optimize code performance. Identifies bottlenecks, suggests improvements, and implements optimizations while ensuring correctness. - -## Usage - -```bash -/optimize [file-or-function] -``` - -## Arguments - -- **file-or-function**: Path to file or function to optimize - - File path: `src/services/data-processor.ts` - - Function name: `processUserData` - - Module: `src/utils/` - -## Workflow - -### Step 1: Analyze Current Performance - -1. **Identify bottlenecks** - - Analyze time complexity - - Check space complexity - - Look for redundant operations - -2. **Profile if possible** - - Check for N+1 queries - - Identify unnecessary loops - - Find repeated calculations - -### Step 2: Identify Opportunities - -1. **Algorithm improvements** - - Better data structures - - More efficient algorithms - - Reduce complexity - -2. **Caching opportunities** - - Memoization - - Result caching - - Computed properties - -3. **Async optimizations** - - Parallel execution - - Batch operations - - Lazy loading - -### Step 3: Implement Optimizations - -1. **Make targeted changes** - - Implement improvements - - Preserve functionality - - Add comments - -2. **Verify improvements** - - Test correctness - - Measure performance - - Compare before/after - -## Output - -```markdown -## Optimization Report: [Component] - -### Current Performance -- Time complexity: O(n²) -- Space complexity: O(n) -- Estimated execution time: 500ms for 1000 items -- Issues found: 3 - -### Bottlenecks Identified - -1. **Nested loop in data processing** - - Location: `processData()` lines 45-60 - - Impact: High - - Current: O(n²) - -2. **Redundant database queries** - - Location: `getUserData()` lines 120-135 - - Impact: Medium - - Issue: N+1 query pattern - -3. **Inefficient array operations** - - Location: `filterResults()` lines 88-92 - - Impact: Low - - Issue: Multiple array iterations - -### Optimizations Applied - -#### 1. Algorithm Improvement -**Before:** -```typescript -// O(n²) nested loop -for (const item of items) { - for (const tag of tags) { - if (item.tags.includes(tag)) { - results.push(item); - } - } -} -``` - -**After:** -```typescript -// O(n) with Set lookup -const tagSet = new Set(tags); -const results = items.filter(item => - item.tags.some(tag => tagSet.has(tag)) -); -``` - -**Impact:** Time complexity reduced from O(n²) to O(n) - -#### 2. Caching Implementation -**Before:** -```typescript -function calculateScore(user) { - // Recalculates every time - return expensiveCalculation(user); -} -``` - -**After:** -```typescript -const scoreCache = new Map(); -function calculateScore(user) { - if (scoreCache.has(user.id)) { - return scoreCache.get(user.id); - } - const score = expensiveCalculation(user); - scoreCache.set(user.id, score); - return score; -} -``` - -**Impact:** 95% cache hit rate in typical usage - -#### 3. Batch Processing -**Before:** -```typescript -for (const userId of userIds) { - await db.getUser(userId); // N queries -} -``` - -**After:** -```typescript -const users = await db.getUsers(userIds); // 1 query -``` - -**Impact:** Reduced database queries from N to 1 - -### Performance Improvements - -| Metric | Before | After | Improvement | -|--------|--------|-------|-------------| -| Time Complexity | O(n²) | O(n log n) | 90% faster | -| Execution Time | 500ms | 50ms | 10x faster | -| Database Queries | 100 | 1 | 99% reduction | -| Memory Usage | 150MB | 80MB | 47% reduction | - -### Testing - -All existing tests pass: -- ✅ Unit tests: 45/45 -- ✅ Integration tests: 12/12 -- ✅ Performance benchmarks added - -### Recommendations - -1. **Monitor in production**: Track actual performance metrics -2. **Consider further optimization**: Implement pagination for large datasets -3. **Add benchmarks**: Create performance regression tests - -### Files Modified -- `src/services/data-processor.ts` -- `tests/data-processor.test.ts` (added benchmarks) -``` - -## Optimization Strategies - -### 1. Algorithm Optimization -- Replace inefficient algorithms -- Use appropriate data structures -- Reduce time/space complexity - -### 2. Caching -- Memoize expensive calculations -- Cache API responses -- Use computed properties - -### 3. Database Optimization -- Batch queries -- Add indexes -- Optimize query patterns -- Use eager loading - -### 4. Async Optimization -- Parallel execution with `Promise.all()` -- Lazy loading -- Stream processing - -### 5. Code-Level Optimization -- Avoid premature optimization -- Profile before optimizing -- Focus on hot paths - -## Examples - -```bash -# Optimize specific file -/optimize src/services/report-generator.ts - -# Optimize by function name -/optimize calculateTotalSales - -# Optimize entire module -/optimize src/utils/ - -# Optimize with performance persona -/optimize --persona=performance src/api/users.ts -``` - -## Flags - -| Flag | Description | -|------|-------------| -| `--profile` | Include profiling data | -| `--benchmark` | Add performance benchmarks | -| `--aggressive` | More aggressive optimizations | -| `--safe` | Conservative optimizations only | -| `--persona=performance` | Performance-focused analysis | - -## Best Practices - -1. **Profile First**: Don't optimize without measuring -2. **Preserve Correctness**: Always verify behavior unchanged -3. **Add Tests**: Include performance regression tests -4. **Document Changes**: Explain why optimizations were made -5. **Measure Impact**: Compare before/after metrics - -## Common Optimizations - -### N+1 Query Prevention -```typescript -// Before: N+1 queries -const users = await db.getUsers(); -for (const user of users) { - user.posts = await db.getPostsByUser(user.id); -} - -// After: 2 queries -const users = await db.getUsers(); -const posts = await db.getPostsByUsers(users.map(u => u.id)); -// Map posts to users -``` - -### Memoization -```typescript -const memoize = (fn) => { - const cache = new Map(); - return (...args) => { - const key = JSON.stringify(args); - if (cache.has(key)) return cache.get(key); - const result = fn(...args); - cache.set(key, result); - return result; - }; -}; -``` - -### Debouncing -```typescript -const debounce = (fn, delay) => { - let timeout; - return (...args) => { - clearTimeout(timeout); - timeout = setTimeout(() => fn(...args), delay); - }; -}; -``` - -## Related Commands - -- [/review](/claudekit/core-commands/review) - Code review with performance checks -- [/test](/claudekit/core-commands/test) - Add performance tests -- [/fix](/claudekit/core-commands/fix) - Fix performance issues diff --git a/website/src/content/docs/commands/overview.md b/website/src/content/docs/commands/overview.md deleted file mode 100644 index 3a1a16c..0000000 --- a/website/src/content/docs/commands/overview.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: Commands Overview -description: All Claude Kit commands organized by category. ---- - -# Commands Overview - -Claude Kit provides 27+ slash commands that automate common development workflows. Commands are organized into categories based on their purpose. - -## Command Categories - -### Development Commands - -Core commands for building features and fixing bugs: - -| Command | Description | -|---------|-------------| -| [`/feature`](/claudekit/commands/feature/) | End-to-end feature development workflow | -| [`/fix`](/claudekit/commands/fix/) | Smart debugging and bug fixing | -| [`/review`](/claudekit/commands/review/) | Comprehensive code review | -| [`/test`](/claudekit/commands/test/) | Generate tests for code | -| [`/refactor`](/claudekit/commands/refactor/) | Code refactoring workflow | -| [`/debug`](/claudekit/commands/debug/) | Interactive debugging session | -| [`/tdd`](/claudekit/commands/tdd/) | Test-driven development workflow | - -### Planning Commands - -Commands for planning and research: - -| Command | Description | -|---------|-------------| -| [`/plan`](/claudekit/commands/plan/) | Create structured implementation plans | -| [`/brainstorm`](/claudekit/commands/brainstorm/) | Interactive design and ideation | -| [`/execute-plan`](/claudekit/commands/execute-plan/) | Execute a plan with subagents | -| [`/research`](/claudekit/commands/research/) | Technology research and analysis | - -### Git & Deployment Commands - -Commands for version control and deployment: - -| Command | Description | -|---------|-------------| -| [`/ship`](/claudekit/commands/ship/) | Commit and create PR workflow | -| [`/commit`](/claudekit/commands/commit/) | Create a git commit | -| [`/pr`](/claudekit/commands/pr/) | Create a pull request | -| [`/deploy`](/claudekit/commands/deploy/) | Deployment workflow | -| [`/changelog`](/claudekit/commands/changelog/) | Generate changelog entries | - -### Documentation Commands - -Commands for generating documentation: - -| Command | Description | -|---------|-------------| -| [`/doc`](/claudekit/commands/doc/) | Generate documentation | -| [`/api-gen`](/claudekit/commands/api-gen/) | Generate API documentation | - -### Utility Commands - -Helper commands for various tasks: - -| Command | Description | -|---------|-------------| -| [`/mode`](/claudekit/commands/mode/) | Switch behavioral modes | -| [`/index`](/claudekit/commands/index/) | Generate project structure index | -| [`/load`](/claudekit/commands/load/) | Load project context | -| [`/checkpoint`](/claudekit/commands/checkpoint/) | Save/restore session state | -| [`/spawn`](/claudekit/commands/spawn/) | Launch parallel background tasks | -| [`/status`](/claudekit/commands/status/) | Show project status | -| [`/help`](/claudekit/commands/help/) | Show help information | -| [`/optimize`](/claudekit/commands/optimize/) | Optimize code performance | -| [`/security-scan`](/claudekit/commands/security-scan/) | Security vulnerability scan | - -## Command Structure - -All commands follow a consistent structure: - -```bash -/command [arguments] [--flags] -``` - -### Arguments - -Most commands accept a description or target as the main argument: - -```bash -/feature "add user authentication" -/fix "TypeError in UserService.ts" -/review src/auth/ -``` - -### Flags - -Commands support flags for customization: - -| Flag | Description | Example | -|------|-------------|---------| -| `--mode=[mode]` | Use specific behavioral mode | `--mode=implementation` | -| `--depth=[1-5]` | Thoroughness level | `--depth=3` | -| `--format=[fmt]` | Output format | `--format=concise` | -| `--save=[path]` | Save output to file | `--save=plan.md` | -| `--checkpoint` | Create state checkpoint | `--checkpoint` | -| `--persona=[type]` | Apply persona expertise | `--persona=security` | - -### Flag Examples - -```bash -# Use implementation mode for faster coding -/feature --mode=implementation "add logging utility" - -# Deep security review -/review --persona=security --depth=5 src/auth/ - -# Concise output -/fix --format=concise "typo in error message" - -# Save plan to file -/plan --save=plans/auth.md "implement authentication" -``` - -## Common Workflows - -### Feature Development - -```bash -# 1. Brainstorm the approach -/brainstorm "how should we implement user roles?" - -# 2. Create a detailed plan -/plan "implement role-based access control" - -# 3. Build the feature -/feature "add RBAC with admin and user roles" - -# 4. Ship it -/ship "feat: add role-based access control" -``` - -### Bug Fixing - -```bash -# 1. Debug the issue -/fix "users can't login after password reset" - -# 2. Review the fix -/review src/auth/password-reset.ts - -# 3. Ship the fix -/ship "fix: resolve password reset login issue" -``` - -### Code Quality - -```bash -# 1. Review code -/review src/services/ - -# 2. Run security scan -/security-scan src/ - -# 3. Optimize performance -/optimize src/services/data-processor.ts -``` - -## Getting Help - -Get help for any command: - -```bash -/help # Show all commands -/help feature # Show /feature details -/help fix # Show /fix details -``` - -## Next Steps - -- [/feature](/claudekit/commands/feature/) — Learn the flagship command -- [/fix](/claudekit/commands/fix/) — Master debugging workflow -- [Modes](/claudekit/modes/overview/) — Optimize Claude's behavior diff --git a/website/src/content/docs/commands/plan.md b/website/src/content/docs/commands/plan.md deleted file mode 100644 index 3f27b90..0000000 --- a/website/src/content/docs/commands/plan.md +++ /dev/null @@ -1,257 +0,0 @@ ---- -title: /plan -description: Create structured implementation plans with task breakdown and time estimates ---- - -# /plan - -Create structured implementation plans with task breakdown, dependencies, and time estimates for complex work. - -## Purpose - -The `/plan` command helps you transform complex features or tasks into actionable, well-organized implementation plans. It breaks down work into manageable chunks, identifies dependencies, estimates effort, and highlights risks. - -## Usage - -```bash -/plan [task description or feature request] -``` - -## Arguments - -- **task description**: Description of the feature, task, or work you need planned - -## How It Works - -### Phase 1: Understanding - -The planner first clarifies what you're trying to build: -- Identifies core functionality needed -- Lists explicit and implicit requirements -- Defines acceptance criteria -- Asks clarifying questions if needed - -### Phase 2: Research - -Next, it explores your codebase to understand context: -- Finds related implementations -- Identifies patterns to follow -- Locates integration points -- Notes existing conventions - -### Phase 3: Task Breakdown - -Work is decomposed into clear, actionable tasks: -- Each task takes 15-60 minutes (standard mode) -- Clear completion criteria for each task -- Dependencies mapped out -- Tasks sized as S/M/L/XL - -### Phase 4: Documentation - -Finally, a comprehensive plan document is created: -- Task list with phases -- Files to create/modify -- Risk assessment -- Success criteria - -## Planning Modes - -### Standard Mode - -Default planning with 15-60 minute tasks: - -```bash -/plan "implement user authentication" -``` - -**Task sizes:** -- **S**: < 30 minutes -- **M**: 30-60 minutes -- **L**: 1-2 hours -- **XL**: 2-4 hours - -### Detailed Mode - -Superpowers-style planning with 2-5 minute tasks and exact code: - -```bash -/plan --detailed "implement user authentication" -``` - -**Features:** -- Bite-sized tasks (2-5 minutes each) -- Exact file paths included -- Complete code samples (not descriptions) -- TDD steps per task (write test → verify fail → implement → verify pass → commit) -- Expected command outputs specified - -**When to use detailed mode:** -- Complex features requiring precision -- When you want automated execution with `/execute-plan` -- Team members new to the codebase -- When you want minimal decision-making during implementation - -## Output Format - -Plans include the following sections: - -### Summary -Brief 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 -Organized into phases with dependencies: - -| # | Task | Size | Depends On | -|---|------|------|------------| -| 1 | Create data model | M | - | -| 2 | Set up database migration | S | 1 | -| 3 | Add model tests | M | 1 | - -### Files to Create/Modify -Complete list of files that will be touched - -### Dependencies -External packages and internal prerequisites - -### Risks -Potential issues and mitigation strategies - -### Success Criteria -Checklist for determining completion - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--detailed` | Use 2-5 min tasks with exact code | `--detailed` | -| `--mode=[mode]` | Use specific behavioral mode | `--mode=brainstorm` | -| `--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` | - -### 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 | - -## Examples - -### Basic Feature Planning - -```bash -/plan "add password reset functionality" -``` - -Creates a standard plan with 15-60 minute tasks for implementing password reset. - -### Detailed Planning for Execution - -```bash -/plan --detailed "implement OAuth2 authentication" -``` - -Creates a detailed plan with 2-5 minute tasks, ready for automated execution with `/execute-plan`. - -### Planning with Brainstorming Mode - -```bash -/plan --mode=brainstorm "redesign checkout flow" -``` - -Uses brainstorming mode to explore multiple approaches before settling on a plan. - -### Saving Plan to File - -```bash -/plan --save=plans/payment-integration.md "integrate Stripe payments" -``` - -Creates plan and saves it to the specified file for later reference. - -### Comprehensive Deep Planning - -```bash -/plan --depth=5 --save=plans/migration.md "migrate from MongoDB to PostgreSQL" -``` - -Creates an exhaustive plan with thorough analysis for a complex migration. - -## Workflow Integration - -### Planning → Execution - -1. Create detailed plan: - ```bash - /plan --detailed "feature description" - ``` - -2. Execute plan with subagents: - ```bash - /execute-plan path/to/plan.md - ``` - -### Design → Planning → Execution - -1. Brainstorm design: - ```bash - /brainstorm "feature concept" - ``` - -2. Create implementation plan: - ```bash - /plan --detailed "feature from design" - ``` - -3. Execute with automation: - ```bash - /execute-plan path/to/plan.md - ``` - -## Best Practices - -### When to Use Standard Mode -- Quick features with clear requirements -- Experienced developers familiar with codebase -- Exploratory or research-heavy tasks -- When you want flexibility during implementation - -### When to Use Detailed Mode -- Complex features requiring precision -- When multiple developers will implement -- Features requiring automated execution -- When you want to minimize implementation decisions - -### Tips for Better Plans -1. **Be specific** in your task description -2. **Include context** about existing implementations -3. **Mention constraints** (performance, security, etc.) -4. **State preferences** for approaches or technologies -5. **Ask for comparisons** if uncertain about approach - -## Related Commands - -- [/brainstorm](/claudekit/commands/brainstorm) - Design features before planning implementation -- [/execute-plan](/claudekit/commands/execute-plan) - Execute detailed plans with subagents -- [/research](/claudekit/commands/research) - Research technologies before planning -- [/tdd](/claudekit/commands/tdd) - Test-driven development workflow - -## Customization - -Plans can be customized via `CLAUDE.md`: -- Task size definitions -- Required plan sections -- Estimation approach -- Risk assessment criteria - -See the [Configuration Guide](/claudekit/configuration) for details. diff --git a/website/src/content/docs/commands/pr.md b/website/src/content/docs/commands/pr.md deleted file mode 100644 index 609fbb6..0000000 --- a/website/src/content/docs/commands/pr.md +++ /dev/null @@ -1,343 +0,0 @@ ---- -title: /pr -description: Create a well-documented pull request with proper description and checks ---- - -# /pr - -Create comprehensive pull requests with auto-generated descriptions, checklists, and proper formatting. - -## Purpose - -Generates pull requests that: -- Include detailed change summaries -- Provide test plans and checklists -- Link to related issues -- Follow your team's PR template -- Are ready for reviewer attention - -Use this when you've already committed changes and just need the PR (for full workflow, use `/ship`). - -## Usage - -```bash -/pr [title] -``` - -**Auto-generate title from commits:** -```bash -/pr auto -``` - -## Arguments - -| Argument | Description | -|----------|-------------| -| `[title]` | PR title in conventional commit format | -| `auto` | Generate title from recent commits | - -## Workflow - -### Step 1: Prepare Changes - -The command first validates your branch is ready: - -```bash -git status -git diff main...HEAD -``` - -Analyzes: -- All commits on your branch -- Files changed -- Lines added/removed -- Potential conflicts - -### Step 2: Verify Ready - -Checks that your branch meets PR requirements: - -**Required checks:** -- [ ] All tests passing -- [ ] Code has been reviewed (or self-reviewed) -- [ ] No merge conflicts with base branch -- [ ] Branch is pushed to remote - -**If checks fail**, you'll get guidance on what to fix before creating the PR. - -### Step 3: Create Pull Request - -Uses GitHub CLI to create the PR: - -```bash -gh pr create \ - --title "type(scope): description" \ - --body "[generated body]" -``` - -The PR body includes: -- Summary of changes -- Test plan -- Screenshots (for UI changes) -- Checklist -- Related issues - -## Examples - -### Feature PR - -**Create PR for new feature:** - -```bash -/pr "add OAuth2 authentication support" -``` - -**Generated PR:** - -**Title:** `feat(auth): add OAuth2 authentication support` - -**Body:** -```markdown -## Summary -- Implement Google OAuth2 provider -- Implement GitHub OAuth2 provider -- Add token refresh mechanism -- Update user model for OAuth data -- Add comprehensive test coverage - -## Test Plan -- [x] Unit tests for OAuth providers -- [x] Integration tests for auth flow -- [x] Manual testing with Google account -- [x] Manual testing with GitHub account -- [x] Token refresh tested - -## Changes -**Added:** -- `src/auth/oauth/google.ts` - Google OAuth implementation -- `src/auth/oauth/github.ts` - GitHub OAuth implementation -- `tests/auth/oauth.test.ts` - OAuth test suite - -**Modified:** -- `src/models/user.ts` - Added OAuth fields -- `src/auth/routes.ts` - Added OAuth routes - -## Checklist -- [x] Tests added/updated -- [x] Documentation updated -- [x] No breaking changes -- [x] Follows code style guidelines - -Closes #123 - -🤖 Generated with Claude Code -``` - -### Bug Fix PR - -**Create PR for bug fix:** - -```bash -/pr "fix null pointer crash in user profile" -``` - -**Generated PR:** - -**Title:** `fix(api): handle null user in profile endpoint` - -**Body:** -```markdown -## Summary -- Fixed crash when accessing deleted user profiles -- Added null check before user data access -- Return proper 404 response for missing users -- Added regression test - -## Bug Details -The profile endpoint crashed with a null pointer exception when -attempting to access a user that had been deleted. This occurred -because the endpoint didn't check if the user exists before -accessing user properties. - -## Test Plan -- [x] Unit test for deleted user scenario -- [x] Integration test for 404 response -- [x] Manual testing with deleted user ID -- [x] Verified fix doesn't affect existing functionality - -## Changes -**Modified:** -- `src/api/profile.ts` - Added null check -- `tests/api/profile.test.ts` - Added regression test - -## Checklist -- [x] Tests added/updated -- [x] No breaking changes -- [x] Follows code style guidelines - -Fixes #456 - -🤖 Generated with Claude Code -``` - -### Auto-Generated PR - -**Let the command create title from commits:** - -```bash -/pr auto -``` - -Analyzes your commits and generates an appropriate title: - -``` -feat(ui): add dark mode support -refactor(ui): improve theme switching -test(ui): add dark mode tests -``` - -**Generated title:** `feat(ui): add dark mode support` - -### Documentation PR - -**Create PR for docs:** - -```bash -/pr "update API documentation" -``` - -**Generated PR:** - -**Title:** `docs(api): update API documentation` - -**Body:** -```markdown -## Summary -- Updated endpoint documentation -- Added request/response examples -- Fixed broken links -- Added authentication section -- Improved error documentation - -## Changes -**Modified:** -- `docs/api.md` - Updated all sections -- `README.md` - Fixed API links - -## Checklist -- [x] Documentation updated -- [x] Examples tested -- [x] Links verified -- [x] No breaking changes - -🤖 Generated with Claude Code -``` - -## PR Body Template - -The generated PR follows this structure: - -```markdown -## Summary -Brief overview of changes with bullet points - -## [Conditional Sections] -- **Bug Details** (for fixes) -- **Feature Description** (for features) -- **Breaking Changes** (if applicable) - -## Test Plan -- [ ] Unit tests -- [ ] Integration tests -- [ ] Manual testing -- [ ] Specific scenarios tested - -## Screenshots -[For UI changes - automatically detected] - -## Changes -**Added:** -- List of new files - -**Modified:** -- List of changed files - -**Removed:** -- List of deleted files - -## Checklist -- [ ] Tests added/updated -- [ ] Documentation updated -- [ ] No breaking changes -- [ ] Follows code style - -[Issue references] - -🤖 Generated with Claude Code -``` - -## Output - -After creating the PR, you'll see: - -```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 - -### Status -✓ Ready for review -✓ All checks passing -✓ No conflicts - -### Next Steps -1. Request reviews from: @teammate1, @teammate2 -2. Address feedback -3. Merge when approved -``` - -## Pre-PR Validation - -The command checks: - -- [ ] **Branch is pushed** - Must exist on remote -- [ ] **Tests passing** - All CI checks green -- [ ] **No conflicts** - Clean merge with base branch -- [ ] **Commits are valid** - No WIP or fixup commits -- [ ] **Required files updated** - Changelog, docs, etc. - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--base=[branch]` | Target branch (default: main) | `/pr --base=develop "new feature"` | -| `--draft` | Create as draft PR | `/pr --draft "work in progress"` | -| `--reviewers=[users]` | Request specific reviewers | `/pr --reviewers=alice,bob "feature"` | -| `--mode=[mode]` | Behavioral mode | `/pr --mode=token-efficient auto` | - -## Related Commands - -- [/ship](/claudekit/commands/ship/) - Full commit + PR workflow -- [/commit](/claudekit/commands/commit/) - Create commits -- [/review](/claudekit/commands/review/) - Review code before PR -- [/changelog](/claudekit/commands/changelog/) - Generate changelog - -## Tips - -**Use 'auto' for multi-commit PRs**: When your branch has several related commits, let the command analyze them to generate the best title. - -**Draft PRs for WIP**: Use `--draft` flag for work-in-progress PRs that aren't ready for review. - -**Request reviewers**: Add `--reviewers` to automatically request reviews from specific team members. - -**Link issues**: Reference issues in your title or use keywords like "Closes #123" to auto-link. - -**Customize template**: Modify the PR template in `CLAUDE.md` under "PR Requirements". - -**Screenshot detection**: For UI changes, the command will prompt you to add screenshots to the PR body. diff --git a/website/src/content/docs/commands/refactor.md b/website/src/content/docs/commands/refactor.md deleted file mode 100644 index 023f359..0000000 --- a/website/src/content/docs/commands/refactor.md +++ /dev/null @@ -1,390 +0,0 @@ ---- -title: /refactor -description: Improve code structure, readability, and performance without changing behavior ---- - -# /refactor - Refactoring Command - -## Purpose - -Improve code structure, readability, or performance without changing external behavior. Applies proven refactoring patterns to make code more maintainable, testable, and efficient. - -## Usage - -```bash -/refactor [file or function] [goal: clean | extract | simplify | optimize] -``` - -## Arguments - -- `[file or function]` - Target code to refactor -- `[goal]` - Optional refactoring objective: - - `clean` - Remove dead code, improve naming - - `extract` - Extract reusable functions/components - - `simplify` - Reduce complexity and nesting - - `optimize` - Improve performance - -## How It Works - -The `/refactor` command follows a safe, incremental approach: - -### Step 1: Understand Current Code - -1. **Read Thoroughly** - - Analyzes what the code does - - Identifies its purpose and responsibilities - - Maps inputs, outputs, and side effects - -2. **Note Existing Tests** - - Finds test coverage for the code - - Ensures tests exist before refactoring - - If no tests exist, generates them first - -3. **Identify Patterns** - - Recognizes code smells - - Finds refactoring opportunities - - Notes dependencies and coupling - -### Step 2: Plan Refactoring - -1. **Identify Improvements** - - Code smells to address - - Patterns to apply - - Metrics to improve - -2. **Ensure Test Safety** - - Verifies tests exist - - Adds missing tests if needed - - Ensures tests are comprehensive - -3. **Plan Incremental Changes** - - Breaks into small, safe steps - - Orders changes by dependencies - - Plans verification after each step - -### Step 3: Execute Refactoring - -1. **Make Small Changes** - - One refactoring at a time - - Maintains behavior at each step - - Keeps code working continuously - -2. **Run Tests After Each Change** - ```bash - # Python - pytest -v - - # TypeScript - pnpm test - ``` - -3. **Commit Incrementally** - - Commits after each successful refactoring - - Makes rollback easy if needed - - Documents what changed and why - -## Refactoring Types - -### Extract Function/Method - -**When**: Code duplication or long methods - -```typescript -// Before -function processUser(user: User) { - if (!user.email || !user.email.includes('@')) { - throw new Error('Invalid email'); - } - if (user.name.length < 2) { - throw new Error('Name too short'); - } - // ... more logic -} - -// After -function processUser(user: User) { - validateUser(user); - // ... more logic -} - -function validateUser(user: User) { - validateEmail(user.email); - validateName(user.name); -} - -function validateEmail(email: string) { - if (!email || !email.includes('@')) { - throw new Error('Invalid email'); - } -} - -function validateName(name: string) { - if (name.length < 2) { - throw new Error('Name too short'); - } -} -``` - -### Simplify Conditionals - -**When**: Complex nested if statements - -```typescript -// Before -if (user) { - if (user.isActive) { - if (user.subscription) { - if (user.subscription.isPaid) { - return true; - } - } - } -} -return false; - -// After -return user?.isActive - && user?.subscription?.isPaid - ?? false; -``` - -### Replace Magic Numbers - -**When**: Unexplained numeric literals - -```python -# Before -def calculate_discount(price): - if price > 100: - return price * 0.9 - return price - -# After -DISCOUNT_THRESHOLD = 100 -DISCOUNT_RATE = 0.1 - -def calculate_discount(price): - if price > DISCOUNT_THRESHOLD: - return price * (1 - DISCOUNT_RATE) - return price -``` - -### Improve Naming - -**When**: Unclear variable/function names - -```typescript -// Before -function calc(x: number, y: number): number { - const z = x * y * 0.2; - return z; -} - -// After -function calculateTax(subtotal: number, quantity: number): number { - const TAX_RATE = 0.2; - const totalBeforeTax = subtotal * quantity; - return totalBeforeTax * TAX_RATE; -} -``` - -### Remove Dead Code - -**When**: Unused functions, commented code - -```python -# Before -def old_function(): # Not called anywhere - pass - -def current_function(): - # result = old_way() # Old implementation - result = new_way() - return result - -# After -def current_function(): - result = new_way() - return result -``` - -### Extract Class/Module - -**When**: Too many responsibilities in one class - -```typescript -// Before -class User { - name: string; - email: string; - - validateEmail() { /* ... */ } - sendEmail(subject: string, body: string) { /* ... */ } - formatEmailTemplate(template: string) { /* ... */ } -} - -// After -class User { - name: string; - email: string; - - validateEmail() { /* ... */ } -} - -class EmailService { - sendEmail(to: string, subject: string, body: string) { /* ... */ } - formatTemplate(template: string, data: any) { /* ... */ } -} -``` - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--goal=[goal]` | Refactoring objective | `--goal=simplify` | -| `--safe` | Extra cautious, more test verification | `--safe` | -| `--aggressive` | Larger refactoring steps | `--aggressive` | -| `--format=[fmt]` | Output format (concise/detailed) | `--format=concise` | -| `--test-first` | Generate tests before refactoring | `--test-first` | - -### Goal Options - -| Goal | Focus | -|------|-------| -| `clean` | Remove clutter, improve naming | -| `extract` | Pull out reusable code | -| `simplify` | Reduce complexity | -| `optimize` | Improve performance | -| `patterns` | Apply design patterns | - -### Flag Examples - -```bash -# Simplify complex function -/refactor --goal=simplify src/utils/validation.ts - -# Extract with extra safety checks -/refactor --safe --goal=extract src/services/user.ts - -# Performance optimization -/refactor --goal=optimize src/api/heavy-query.ts - -# Clean up with tests first -/refactor --test-first --goal=clean src/legacy/ -``` - -## Examples - -### Simplify Complex Logic - -**Input:** -```bash -/refactor --goal=simplify src/services/auth.ts -``` - -**Output:** -```markdown -## Refactoring Complete: src/services/auth.ts - -### Changes Made -1. Extracted `validateCredentials()` function -2. Simplified nested conditionals using early returns -3. Replaced magic numbers with named constants -4. Improved variable names for clarity - -### Before -```typescript -function login(email, pwd) { - if (email) { - if (pwd) { - if (pwd.length >= 8) { - const u = db.find(email); - if (u) { - if (bcrypt.compare(pwd, u.pwd)) { - return generateToken(u); - } - } - } - } - } - throw new Error('Invalid'); -} -``` - -### After -```typescript -const MIN_PASSWORD_LENGTH = 8; - -function login(email: string, password: string): string { - validateCredentials(email, password); - - const user = db.findByEmail(email); - if (!user) { - throw new AuthError('Invalid credentials'); - } - - const passwordMatches = bcrypt.compare(password, user.hashedPassword); - if (!passwordMatches) { - throw new AuthError('Invalid credentials'); - } - - return generateToken(user); -} - -function validateCredentials(email: string, password: string) { - if (!email) { - throw new ValidationError('Email required'); - } - if (!password || password.length < MIN_PASSWORD_LENGTH) { - throw new ValidationError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`); - } -} -``` - -### Metrics -- Cyclomatic complexity: 8 → 3 -- Function length: 18 lines → 12 lines -- Nesting depth: 5 → 2 - -### Tests -- All 12 existing tests passing -- No behavior changes -``` - -### Extract Reusable Code - -**Input:** -```bash -/refactor --goal=extract src/components/UserList.tsx -``` - -**Output:** -1. Identifies repeated patterns -2. Extracts into reusable hooks/components -3. Updates all usage sites -4. Verifies tests still pass - -## Deliverables - -After running `/refactor`, you receive: - -1. **Refactored Code** - Improved implementation -2. **Before/After Comparison** - Clear visual diff -3. **Metrics** - Complexity, length, nesting improvements -4. **Test Results** - Confirmation of unchanged behavior -5. **Commit Message** - Describing the refactoring - -## Best Practices - -1. **Always Have Tests First** - Never refactor untested code -2. **Small Steps** - Make one change at a time -3. **Run Tests Frequently** - After each change -4. **Commit Often** - Easy rollback if something breaks -5. **Preserve Behavior** - Never change what the code does, only how - -## Related Commands - -- [/test](/claudekit/commands/test) - Generate tests before refactoring -- [/review](/claudekit/commands/review) - Review code quality -- [/feature](/claudekit/commands/feature) - Build features with good structure -- [/fix](/claudekit/commands/fix) - Fix bugs, then refactor diff --git a/website/src/content/docs/commands/research.md b/website/src/content/docs/commands/research.md deleted file mode 100644 index c458b34..0000000 --- a/website/src/content/docs/commands/research.md +++ /dev/null @@ -1,327 +0,0 @@ ---- -title: /research -description: Research technologies, libraries, or approaches with comprehensive analysis ---- - -# /research - -Research a technology, library, or approach with comprehensive analysis, comparisons, and recommendations. - -## Purpose - -The `/research` command helps you make informed technology decisions by gathering information, analyzing trade-offs, comparing alternatives, and providing clear recommendations. - -## Usage - -```bash -/research [topic or technology] -``` - -## Arguments - -- **topic**: The technology, library, pattern, or approach you want to research - -## How It Works - -### 1. Gather Information - -The assistant collects information from: -- Official documentation -- Community resources and discussions -- Best practices and patterns -- Known issues and gotchas - -### 2. Analyze - -Thorough analysis includes: -- Pros and cons -- Performance characteristics -- Learning curve and complexity -- Ecosystem and community support -- Maintenance and longevity -- Best practices - -### 3. Recommend - -Clear recommendations with: -- Summary of findings -- Specific recommendation -- Rationale for recommendation -- Next steps for implementation -- Alternatives if recommendation doesn't fit - -## Output Format - -Research results are presented in a structured format: - -```markdown -## Research: [Topic] - -### Summary -[High-level overview of the technology] - -### Pros -- [Advantage 1] -- [Advantage 2] -- [Advantage 3] - -### Cons -- [Limitation 1] -- [Limitation 2] - -### Use Cases -- Best for: [Scenarios] -- Avoid when: [Scenarios] - -### Alternatives -[Comparison table with alternatives] - -### Best Practices -- [Practice 1] -- [Practice 2] - -### Recommendation -[Clear recommendation with rationale] - -### Next Steps -1. [Action item 1] -2. [Action item 2] -``` - -## 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` | - -### Depth Levels - -| Level | Behavior | Best For | -|-------|----------|----------| -| 1 | Quick overview, key points only | Quick validation | -| 2 | Standard analysis | General research | -| 3 | Thorough with examples | Technology evaluation | -| 4 | Comprehensive with trade-offs | Important decisions | -| 5 | Exhaustive with citations | Critical architecture choices | - -## Examples - -### Basic Technology Research - -```bash -/research "Redis for session storage" -``` - -Standard research on using Redis for sessions. - -### Deep Technology Comparison - -```bash -/research --compare "React vs Vue vs Svelte" -``` - -Comprehensive comparison of frontend frameworks with trade-off analysis. - -### Thorough Investigation - -```bash -/research --depth=5 "authentication libraries for Node.js" -``` - -Exhaustive research with detailed analysis and citations. - -### Sequential Problem Solving - -```bash -/research --sequential "root cause of memory leak" -``` - -Uses step-by-step sequential thinking for complex debugging. - -### Save Research Results - -```bash -/research --save=docs/orm-research.md "TypeORM vs Prisma vs Drizzle" -``` - -Researches ORM options and saves results to file. - -### Quick Overview - -```bash -/research --depth=1 "GraphQL subscriptions" -``` - -Quick overview for validation without deep analysis. - -### Deep Research Mode - -```bash -/research --mode=deep-research "distributed tracing approaches" -``` - -Uses deep-research mode for thorough analysis with citations. - -## Research Types - -### Technology Selection - -Compare libraries, frameworks, or tools: -```bash -/research --compare "state management libraries for React" -``` - -### Pattern Exploration - -Research design patterns and architectures: -```bash -/research "event sourcing patterns" -``` - -### Best Practices - -Investigate recommended approaches: -```bash -/research "API versioning strategies" -``` - -### Problem Investigation - -Debug or understand complex issues: -```bash -/research --sequential "solving N+1 query problems" -``` - -### Integration Research - -Research how to integrate technologies: -```bash -/research "integrating Next.js with Strapi CMS" -``` - -## Workflow Integration - -### Research → Brainstorm → Plan - -1. **Research options:** - ```bash - /research --compare "authentication approaches" - ``` - -2. **Design solution:** - ```bash - /brainstorm "authentication system design" - ``` - -3. **Plan implementation:** - ```bash - /plan --detailed "implement chosen auth approach" - ``` - -### Research → Direct Implementation - -For simple integrations: -```bash -# Research the library -/research "Stripe payment integration" - -# Implement directly -/feature "integrate Stripe payments" -``` - -### Pre-Planning Research - -Before creating detailed plans: -```bash -# Research unfamiliar technology -/research --depth=4 "WebSocket scaling strategies" - -# Plan with research insights -/plan "implement scalable WebSocket server" -``` - -## Best Practices - -### Be Specific - -```bash -# Too vague -/research "databases" - -# Better -/research "time-series databases for IoT data" - -# Even better -/research --compare "InfluxDB vs TimescaleDB vs QuestDB for IoT sensor data" -``` - -### Include Context - -```bash -/research "caching strategies for a high-traffic API with 100k+ requests/minute" -``` - -### State Constraints - -```bash -/research "frontend frameworks compatible with SSR and supporting TypeScript" -``` - -### Save Important Research - -```bash -/research --save=docs/decisions/cache-strategy.md --depth=5 "caching architecture" -``` - -### Use Appropriate Depth - -- **Depth 1-2**: Validation, quick checks -- **Depth 3**: Standard technology evaluation -- **Depth 4-5**: Critical architecture decisions - -## When to Use - -**Good use cases:** -- Evaluating technology options -- Understanding new libraries or frameworks -- Investigating architectural patterns -- Comparing competing solutions -- Debugging complex issues -- Learning best practices - -**Less useful for:** -- Technologies you're already familiar with -- Simple implementation questions -- Project-specific code (use `/review` instead) - -## Tips for Better Research - -1. **Be specific** about your use case and constraints -2. **Include scale** if performance matters (users, requests, data size) -3. **Mention existing stack** for compatibility analysis -4. **State priorities** (speed vs reliability vs cost) -5. **Ask for comparisons** when evaluating options -6. **Use --sequential** for complex debugging or investigations -7. **Save research** for future reference and team sharing - -## Related Commands - -- [/brainstorm](/claudekit/commands/brainstorm) - Design solutions after research -- [/plan](/claudekit/commands/plan) - Plan implementation after research -- [/review](/claudekit/commands/review) - Review existing code or implementations -- [/compare](/claudekit/commands/compare) - Side-by-side comparison (alternative) - -## Customization - -Research behavior can be customized via `CLAUDE.md`: -- Default depth level -- Output format preferences -- Comparison criteria -- Citation requirements - -See the [Configuration Guide](/claudekit/configuration) for details. diff --git a/website/src/content/docs/commands/review.md b/website/src/content/docs/commands/review.md deleted file mode 100644 index 52903b2..0000000 --- a/website/src/content/docs/commands/review.md +++ /dev/null @@ -1,354 +0,0 @@ ---- -title: /review -description: Comprehensive code review with focus on quality, security, performance, and maintainability ---- - -# /review - Code Review Command - -## Purpose - -Comprehensive code review that analyzes quality, security, performance, and maintainability. Acts as an automated code reviewer that checks for issues across multiple dimensions before code reaches production. - -## Usage - -```bash -/review [file path | 'staged' | 'pr' | PR number] -``` - -## Arguments - -- `[file path]` - Review specific file(s), supports glob patterns -- `staged` - Review all staged changes (`git diff --staged`) -- `pr` - Review current branch changes vs main -- `[PR number]` - Review specific pull request from GitHub - -## How It Works - -The `/review` command executes a comprehensive 5-phase review process: - -### Phase 1: Identify Review Scope - -1. **Determine What to Review** - - Single file: Reads the specified file - - `staged`: Gets staged changes with `git diff --staged` - - `pr`: Gets branch diff with `git diff main...HEAD` - - PR number: Fetches PR details with `gh pr view` - -2. **Gather Context** - - Understands the purpose of changes - - Checks related tests - - Reviews CLAUDE.md for project standards - -### Phase 2: Code Quality Review - -Checks 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 - -Checks 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 - -Checks 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 - -Checks 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 - -## Review Output Format - -```markdown -## Code Review: src/api/users.ts - -**Reviewed**: 1 file, 142 lines -**Verdict**: Request Changes - ---- - -### 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 - -## 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 (1=quick, 5=exhaustive) | `--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` | - -### 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 queries, complexity, memory | -| `quality` | Readability, maintainability | -| `testing` | Coverage, test patterns | - -### Flag Examples - -```bash -# Security-focused review of auth code -/review --persona=security src/auth/ - -# Thorough review of staged changes -/review --depth=5 --format=detailed staged - -# Performance-focused review -/review --focus=performance src/services/heavy-computation.ts - -# Deep review with saved report -/review --mode=deep-research --save pr -``` - -## Examples - -### Review Staged Changes - -**Input:** -```bash -/review staged -``` - -**Output:** -Complete review of all staged changes with: -- Security vulnerability scan -- Code quality assessment -- Performance analysis -- Actionable feedback organized by severity - -### Review Pull Request - -**Input:** -```bash -/review pr #142 -``` - -**Output:** -- Fetches PR from GitHub -- Reviews all changed files -- Categorizes issues by severity -- Provides approval recommendation - -### Security-Focused Review - -**Input:** -```bash -/review --persona=security --depth=5 src/api/ -``` - -**Output:** -- Deep security analysis -- OWASP top 10 checks -- Auth/authorization review -- Input validation verification - -## Deliverables - -After running `/review`, you receive: - -1. **Issue List** - Organized by severity (Critical, Recommendations, Suggestions) -2. **Code Examples** - Before/after code snippets for fixes -3. **Checklist Results** - Security, quality, testing, documentation -4. **Verdict** - Approve, Request Changes, or Needs Discussion -5. **Action Items** - Prioritized list of required fixes - -## Related Commands - -- [/fix](/claudekit/commands/fix) - Fix identified issues -- [/refactor](/claudekit/commands/refactor) - Address code quality suggestions -- [/test](/claudekit/commands/test) - Add missing tests -- [/feature](/claudekit/commands/feature) - Complete feature workflow with review diff --git a/website/src/content/docs/commands/security-scan.md b/website/src/content/docs/commands/security-scan.md deleted file mode 100644 index 6e730eb..0000000 --- a/website/src/content/docs/commands/security-scan.md +++ /dev/null @@ -1,316 +0,0 @@ ---- -title: /security-scan -description: Scan code and dependencies for security vulnerabilities ---- - -# /security-scan - -## Purpose - -Scan code and dependencies for security vulnerabilities. Performs comprehensive security analysis including dependency audits, code pattern scanning, and secret detection. - -## Usage - -```bash -/security-scan [scope] -``` - -## Arguments - -- **scope** (optional): What to scan - - `deps` - Dependency vulnerabilities only - - `code` - Code patterns and vulnerabilities - - `secrets` - Hardcoded secrets and credentials - - `all` - Comprehensive scan (default) - -## Workflow - -### Step 1: Dependency Scan - -Check for known vulnerabilities in dependencies: - -```bash -# Node.js projects -npm audit - -# Python projects -pip-audit -``` - -Identifies: -- Outdated packages with security issues -- Known CVEs in dependencies -- Severity levels (Critical, High, Medium, Low) -- Available fixes and upgrades - -### Step 2: Code Scan - -Analyze code for security vulnerabilities: - -**Patterns checked:** -- SQL injection vulnerabilities -- XSS (Cross-Site Scripting) risks -- Command injection -- Path traversal -- Insecure deserialization -- Unsafe eval() usage -- Weak cryptography - -### Step 3: Secret Detection - -Scan for exposed secrets: - -**Detected items:** -- API keys -- Passwords -- Tokens and credentials -- Private keys -- Database connection strings -- AWS/cloud credentials - -## Output - -```markdown -## Security Scan Results - -### Summary - -| Category | Critical | High | Medium | Low | Total | -|----------|----------|------|--------|-----|-------| -| Dependencies | 0 | 2 | 5 | 8 | 15 | -| Code Vulnerabilities | 0 | 1 | 3 | 2 | 6 | -| Exposed Secrets | 0 | 0 | 0 | 0 | 0 | -| **Total** | **0** | **3** | **8** | **10** | **21** | - -### Critical Issues - -None found ✅ - -### High Severity Issues (3) - -#### 1. SQL Injection Risk -**File:** `src/api/users.ts:45` -**Severity:** High -**Issue:** Unsanitized user input in SQL query - -```typescript -// Vulnerable code -const query = `SELECT * FROM users WHERE id = ${userId}`; -``` - -**Recommendation:** -```typescript -// Use parameterized queries -const query = 'SELECT * FROM users WHERE id = ?'; -const result = await db.query(query, [userId]); -``` - -#### 2. Outdated Dependency: express -**Package:** `express@4.17.1` -**Severity:** High -**CVE:** CVE-2022-24999 -**Issue:** Denial of Service vulnerability - -**Recommendation:** -```bash -npm install express@4.18.2 -``` - -#### 3. Command Injection Risk -**File:** `src/utils/file-processor.ts:78` -**Severity:** High -**Issue:** Unsanitized input to shell command - -```typescript -// Vulnerable code -exec(`convert ${filename} output.pdf`); -``` - -**Recommendation:** -```typescript -// Use safe alternatives -import { execFile } from 'child_process'; -execFile('convert', [filename, 'output.pdf']); -``` - -### Medium Severity Issues (8) - -#### XSS Risk in Template -**File:** `src/views/profile.tsx:23` -**Severity:** Medium - -```typescript -// Vulnerable -
- -// Safe -
{sanitize(userBio)}
-``` - -#### Weak Password Hashing -**File:** `src/auth/password.ts:12` -**Severity:** Medium - -```typescript -// Weak -crypto.createHash('md5').update(password).digest('hex'); - -// Strong -import bcrypt from 'bcrypt'; -await bcrypt.hash(password, 10); -``` - -[... additional findings ...] - -### Dependencies Requiring Updates - -| Package | Current | Latest | Severity | -|---------|---------|--------|----------| -| express | 4.17.1 | 4.18.2 | High | -| lodash | 4.17.19 | 4.17.21 | Medium | -| axios | 0.21.1 | 1.6.0 | Medium | - -### Remediation Steps - -#### Immediate Actions (Critical/High) -1. ✅ No critical issues -2. 🔧 Fix SQL injection in `src/api/users.ts` -3. 🔧 Fix command injection in `src/utils/file-processor.ts` -4. 📦 Update express to 4.18.2 - -#### Short-term Actions (Medium) -1. Implement input sanitization for XSS prevention -2. Upgrade password hashing to bcrypt -3. Update medium-severity dependencies - -#### Long-term Improvements -1. Implement automated security scanning in CI/CD -2. Add security headers middleware -3. Set up dependency update automation -4. Conduct security code review training - -### Best Practices Violations - -- ❌ Secrets in environment variables (not .env) -- ❌ Missing rate limiting on public endpoints -- ❌ No input validation middleware -- ❌ Missing security headers - -### Security Score: 72/100 - -**Category Scores:** -- Dependencies: 65/100 -- Code Security: 78/100 -- Secret Management: 100/100 -- Best Practices: 60/100 -``` - -## Scan Scopes - -### Dependencies Only -```bash -/security-scan deps -``` -Fast scan of package vulnerabilities - -### Code Only -```bash -/security-scan code -``` -Deep code analysis for vulnerability patterns - -### Secrets Only -```bash -/security-scan secrets -``` -Check for exposed credentials - -### Comprehensive -```bash -/security-scan all -``` -Full security audit (recommended) - -## Examples - -```bash -# Full security scan -/security-scan - -# Only check dependencies -/security-scan deps - -# Code vulnerabilities only -/security-scan code - -# Find exposed secrets -/security-scan secrets - -# Security-focused review -/review --persona=security src/auth/ -``` - -## Flags - -| Flag | Description | -|------|-------------| -| `--fix` | Auto-fix issues where possible | -| `--report=[path]` | Save detailed report to file | -| `--exclude=[pattern]` | Exclude files/patterns | -| `--strict` | Fail on any medium+ severity | - -## Common Vulnerabilities - -### SQL Injection -```typescript -// Bad -const query = `SELECT * FROM users WHERE email = '${email}'`; - -// Good -const query = 'SELECT * FROM users WHERE email = ?'; -db.query(query, [email]); -``` - -### XSS (Cross-Site Scripting) -```typescript -// Bad -
- -// Good -import DOMPurify from 'dompurify'; -
{DOMPurify.sanitize(userContent)}
-``` - -### Command Injection -```typescript -// Bad -exec(`ping ${userInput}`); - -// Good -execFile('ping', [userInput]); -``` - -### Hardcoded Secrets -```typescript -// Bad -const apiKey = 'sk_live_abc123xyz'; - -// Good -const apiKey = process.env.API_KEY; -``` - -## Best Practices - -1. **Regular Scans**: Run security scans regularly, not just before releases -2. **CI/CD Integration**: Automate security scanning in your pipeline -3. **Dependency Updates**: Keep dependencies up to date -4. **Code Review**: Include security in code review process -5. **Principle of Least Privilege**: Minimize permissions and access -6. **Input Validation**: Always validate and sanitize user input -7. **Secrets Management**: Use environment variables and secret management tools - -## Related Commands - -- [/review --persona=security](/claudekit/core-commands/review) - Security-focused code review -- [/fix](/claudekit/core-commands/fix) - Fix identified vulnerabilities -- [/optimize](/claudekit/commands/optimize) - Performance optimization diff --git a/website/src/content/docs/commands/ship.md b/website/src/content/docs/commands/ship.md deleted file mode 100644 index 36876f5..0000000 --- a/website/src/content/docs/commands/ship.md +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: /ship -description: Complete workflow to commit changes, run reviews, execute tests, and create a pull request ---- - -# /ship - -The ultimate command for shipping code. Runs quality checks, creates commits, and generates pull requests in one streamlined workflow. - -## Purpose - -Complete end-to-end workflow that: -- Reviews your code for quality and security -- Runs the test suite -- Creates a well-formatted commit -- Pushes changes to remote -- Generates a pull request ready for review - -## Usage - -```bash -/ship [commit message] -``` - -**Quick mode** (skip review): -```bash -/ship quick -``` - -## Arguments - -| Argument | Description | -|----------|-------------| -| `[commit message]` | Your commit message - used as the commit subject line | -| `quick` | Skip code review and auto-generate commit message | - -## Workflow - -The `/ship` command follows a comprehensive 5-phase workflow: - -### Phase 1: Pre-Ship Checks - -First, the command validates your changes: - -```bash -git status -git diff --staged -``` - -**Automatic validation:** -- No secrets or API keys in code -- No debug statements (`console.log`, `print()`) -- No large blocks of commented-out code -- Identifies all modified, added, and deleted files - -### Phase 2: Code Review (unless 'quick' mode) - -Runs an automated self-review: - -- **Code quality**: Checks style compliance and best practices -- **Security**: Identifies potential vulnerabilities -- **Type safety**: Verifies TypeScript types, Python type hints -- **Critical issues**: Must be fixed before proceeding -- **Recommendations**: Noted but don't block the ship - -### Phase 3: Run Tests - -Executes your test suite and validates coverage: - -**Python projects:** -```bash -pytest -v -``` - -**TypeScript/JavaScript projects:** -```bash -pnpm test -``` - -**Validation checks:** -- All tests must pass -- No new warnings introduced -- Code coverage not decreased -- New code has test coverage - -### Phase 4: Create Commit - -Creates a conventional commit with auto-generated message: - -```bash -git add -A -git commit -m "type(scope): subject - -body explaining the changes - -🤖 Generated with Claude Code - -Co-Authored-By: Claude " -``` - -The commit message follows [Conventional Commits](https://www.conventionalcommits.org/) format. - -### Phase 5: Push and Create PR - -Pushes your branch and creates a pull request: - -```bash -git push -u origin [branch-name] -gh pr create --title "type(scope): description" --body "[PR body]" -``` - -The PR includes: -- Summary of changes -- Test plan checklist -- Manual testing notes -- Link to related issues - -## Examples - -### Standard Ship - -Ship a new authentication feature: - -```bash -/ship "add OAuth2 login support" -``` - -**Generated commit:** -``` -feat(auth): add OAuth2 login support - -- Implement Google OAuth provider -- Implement GitHub OAuth provider -- Add session token generation -- Update user model for OAuth data - -🤖 Generated with Claude Code - -Co-Authored-By: Claude -``` - -### Quick Ship - -For small changes where you want to skip the review: - -```bash -/ship quick -``` - -Auto-generates everything and creates the PR immediately. - -### Bug Fix Ship - -```bash -/ship "fix null user crash in profile endpoint" -``` - -**Generated commit:** -``` -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 - -🤖 Generated with Claude Code - -Co-Authored-By: Claude -``` - -## Output - -After successful completion, you'll see a comprehensive 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 -``` - -## Commit Message Formats - -The command auto-generates appropriate commit messages based on your changes: - -### Feature Addition -``` -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 -``` - -### Refactoring -``` -refactor(scope): improve [area] - -- Extracted [logic] to [location] -- Renamed [old] to [new] -- Simplified [complex code] -``` - -### Documentation -``` -docs(scope): update [documentation] - -- Added [section] -- Fixed [errors] -- Updated [examples] -``` - -## Pre-Ship Checklist - -The command automatically validates: - -- [ ] All changes are staged -- [ ] No unintended files included -- [ ] Tests pass -- [ ] No secrets in code -- [ ] No debug statements -- [ ] Commit message is descriptive -- [ ] PR description is complete - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--mode=[mode]` | Override behavioral mode | `/ship --mode=token-efficient "fix bug"` | -| `--format=[fmt]` | Output format (concise/detailed) | `/ship --format=concise quick` | -| `--skip-tests` | Skip test execution | `/ship --skip-tests "docs update"` | - -## Related Commands - -- [/commit](/claudekit/commands/commit/) - Create a commit without PR -- [/pr](/claudekit/commands/pr/) - Create PR from existing commits -- [/review](/claudekit/commands/review/) - Run code review separately -- [/test](/claudekit/commands/test/) - Run tests separately - -## Tips - -**For small changes**: Use `/ship quick` to skip the review and speed up the process. - -**For critical changes**: Let the full workflow run to catch potential issues before they reach reviewers. - -**For documentation**: Use `--skip-tests` to avoid running the full test suite. - -**Customization**: Modify ship behavior in `CLAUDE.md` under "Agent Behavior Overrides". diff --git a/website/src/content/docs/commands/spawn.md b/website/src/content/docs/commands/spawn.md deleted file mode 100644 index ed72cc0..0000000 --- a/website/src/content/docs/commands/spawn.md +++ /dev/null @@ -1,251 +0,0 @@ ---- -title: /spawn -description: Launch background tasks for parallel execution ---- - -# /spawn - -## Purpose - -Launch background tasks for parallel execution. Enables concurrent work on independent tasks with result aggregation. - -## Usage - -```bash -/spawn "[task description]" -/spawn [operation] -``` - -## 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 | - -## Examples - -```bash -# Spawn research task -/spawn "Research OAuth2 best practices" - -# Spawn analysis with specific agent -/spawn "Analyze user service for performance" --agent=scout - -# Spawn security review -/spawn "Review security of auth module" --agent=security-auditor - -# Check task status -/spawn --list - -# Collect all results -/spawn --collect - -# Wait for all tasks to complete -/spawn --wait - -# Cancel a task -/spawn --cancel 1 -``` - -## Parallel Workflows - -### Research Phase - -```bash -# Launch multiple research tasks -/spawn "Research authentication approaches" -/spawn "Analyze current auth implementation" -/spawn "Review competitor auth patterns" - -# Continue other work... - -# Wait for all to complete -/spawn --wait - -# Collect and synthesize -/spawn --collect -``` - -### Multi-File Review - -```bash -# Review different modules in parallel -/spawn "Review src/auth/ for security" -/spawn "Review src/api/ for performance" -/spawn "Review src/db/ for SQL injection" - -# Collect findings -/spawn --collect - -# Address issues -``` - -### Comprehensive Analysis - -```bash -# Multiple analysis tasks -/spawn "Analyze dependencies for vulnerabilities" -/spawn "Check code coverage gaps" -/spawn "Find performance bottlenecks" - -/spawn --collect -``` - -## Best Practices - -1. **Independent Tasks**: Only spawn truly independent work that doesn't depend on other tasks -2. **Clear Descriptions**: Specific task descriptions get better results -3. **Regular Collection**: Don't let results pile up unchecked -4. **Resource Awareness**: Don't spawn too many concurrent tasks (3-5 is usually optimal) - -## Use Cases - -### Feature Planning - -```bash -# Parallel research before implementation -/spawn "Research state management libraries" -/spawn "Analyze existing state handling code" -/spawn "Find examples of similar features" - -/spawn --collect -# Make informed decision based on all research -``` - -### Code Quality Audit - -```bash -# Audit different aspects simultaneously -/spawn "Check for security vulnerabilities" -/spawn "Identify performance issues" -/spawn "Find code duplication" -/spawn "Check test coverage gaps" - -/spawn --collect -``` - -### Documentation Tasks - -```bash -# Generate docs for multiple modules -/spawn "Document API endpoints" -/spawn "Generate type documentation" -/spawn "Create usage examples" - -/spawn --collect -``` - -## Limitations - -- Tasks cannot communicate with each other -- Results are collected, not streamed -- Heavy tasks may take time to complete -- Some tasks benefit from sequential execution (e.g., dependent work) -- Spawned tasks use additional API tokens - -## Combines With - -- [/mode orchestration](/claudekit/commands/mode) - Manages multiple spawned tasks -- [/plan](/claudekit/core-commands/plan) - Plan tasks, then spawn parallel execution -- [/checkpoint](/claudekit/commands/checkpoint) - Save state before spawning tasks - -## Related Commands - -- [/status](/claudekit/commands/status) - Check project status -- [/load](/claudekit/commands/load) - Load components for tasks diff --git a/website/src/content/docs/commands/status.md b/website/src/content/docs/commands/status.md deleted file mode 100644 index 4fbf446..0000000 --- a/website/src/content/docs/commands/status.md +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: /status -description: Get current project status including tasks, git state, and recent activity ---- - -# /status - -## Purpose - -Get current project status including tasks, git state, and recent activity. Provides a comprehensive overview of where you are in your development workflow. - -## Usage - -```bash -/status -``` - -## Workflow - -### 1. Check Git Status - -```bash -git status -git log --oneline -5 -``` - -Provides: -- Current branch -- Modified/staged/untracked files -- Recent commits - -### 2. Review Tasks - -Shows: -- Tasks in progress -- Pending tasks -- Tasks completed today - -### 3. Recent Activity - -Displays: -- Recent commits (last 5) -- Open pull requests -- Open issues - -## Output - -```markdown -## Project Status - -### Git -- Branch: `feature/oauth-integration` -- Status: 3 modified files, 1 staged -- Ahead of origin by 2 commits - -### Tasks -- In Progress: 2 - - Implement token refresh - - Add OAuth callback -- Pending: 5 -- Completed Today: 3 - -### Recent Commits -1. feat: add JWT token generation -2. test: add auth service tests -3. refactor: extract validation logic -4. fix: handle expired tokens -5. docs: update API documentation - -### Open Pull Requests -- #123: Add OAuth2 authentication -- #119: Fix session timeout issue - -### Active Spawned Tasks -- #1: Research auth patterns (running) -- #2: Security scan (completed) - -### Checkpoints -- feature-auth (2h ago) -- oauth-progress (1d ago) -``` - -## What It Shows - -| Section | Information | -|---------|-------------| -| **Git** | Branch, uncommitted changes, sync status | -| **Tasks** | In-progress, pending, completed | -| **Commits** | Last 5 commits on current branch | -| **PRs** | Open pull requests (if GitHub integration) | -| **Spawned Tasks** | Active background tasks | -| **Checkpoints** | Recent session checkpoints | - -## Use Cases - -### Daily Standup - -```bash -# Quick overview before standup -/status - -# Shows what you worked on and what's in progress -``` - -### Context Recovery - -```bash -# After coming back from a break -/status - -# Reminds you where you left off -``` - -### Before Switching Branches - -```bash -# Check status before switching work -/status - -# Ensure nothing uncommitted will be lost -``` - -### Project Overview - -```bash -# Quick snapshot of project state -/status - -# See all active work at a glance -``` - -## Integration with Other Commands - -### With /checkpoint - -```bash -/status # See current state -/checkpoint save progress # Save before switching -``` - -### With /spawn - -```bash -/spawn --list # See background tasks -/status # See overall status including spawned tasks -``` - -### With /load - -```bash -/status # See what's modified -/load src/auth/ # Load the changed component -``` - -## Tips - -1. **Use Regularly**: Quick status check before starting work -2. **Before Commits**: Verify what's changed before committing -3. **Context Switches**: Check status when switching tasks -4. **Team Coordination**: Share status output in team discussions - -## Related Commands - -- [/checkpoint](/claudekit/commands/checkpoint) - Save/restore session state -- [/spawn](/claudekit/commands/spawn) - Check background tasks -- [/help](/claudekit/commands/help) - Get command help diff --git a/website/src/content/docs/commands/tdd.md b/website/src/content/docs/commands/tdd.md deleted file mode 100644 index 709b33b..0000000 --- a/website/src/content/docs/commands/tdd.md +++ /dev/null @@ -1,457 +0,0 @@ ---- -title: /tdd -description: Test-driven development workflow - write failing tests first, then implement ---- - -# /tdd - Test-Driven Development Workflow - -## Purpose - -Start a strict test-driven development (TDD) workflow where you write failing tests first, then implement code to make them pass. Enforces the Red-Green-Refactor cycle with mandatory verification. - -## Usage - -```bash -/tdd [feature or function description] -``` - -## Arguments - -- `[feature description]` - What you want to build using TDD -- `[function name]` - Specific function to develop with TDD - -## How It Works - -The `/tdd` command enforces a strict 4-phase TDD workflow: - -### Phase 1: Red - Write Failing Tests - -1. **Understand Requirements** - - What should the code do? - - What are the inputs and outputs? - - What edge cases exist? - - What errors should be handled? - -2. **Write Tests First** - ```python - def test_feature_does_expected_thing(): - """Test the main functionality.""" - result = feature("input") - assert result == "expected" - - def test_feature_handles_edge_case(): - """Test edge case behavior.""" - result = feature("") - assert result == "default" - - def test_feature_raises_on_invalid(): - """Test error handling.""" - with pytest.raises(ValueError): - feature(None) - ``` - -3. **Run Tests (Expect Failure)** - ```bash - pytest -v # Should FAIL - feature() doesn't exist yet - ``` - -**Non-Negotiable Rule**: NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST - -### Phase 2: Green - Make Tests Pass - -1. **Implement Minimal Code** - - Write just enough code to pass tests - - Don't add extra features - - Don't optimize prematurely - - Keep it simple - -2. **Run Tests (Expect Success)** - ```bash - pytest -v # Should PASS - all tests green - ``` - -3. **Verify Every Claim** - - Don't say "tests should pass" - - Run the actual command - - Read the complete output - - Verify it matches your claim - -### Phase 3: Refactor - -1. **Improve Code Quality** - - Clean up implementation - - Remove duplication - - Improve naming - - Apply patterns - -2. **Run Tests (Ensure Still Passing)** - ```bash - pytest -v # Should still PASS - ``` - -3. **Keep Tests Green** - - Never break tests during refactoring - - If tests fail, revert and try again - - Tests are your safety net - -### Phase 4: Repeat - -Add more test cases and repeat the cycle: -1. Write next failing test -2. Make it pass -3. Refactor if needed -4. Commit - -## TDD Best Practices - -### DO -- ✅ Write one test at a time -- ✅ Run tests after every change -- ✅ Keep red-green-refactor cycles short (minutes, not hours) -- ✅ Commit after each green phase -- ✅ Test behavior, not implementation -- ✅ Start with simplest test cases - -### DON'T -- ❌ Write production code before tests -- ❌ Write multiple tests before implementing -- ❌ Skip running tests -- ❌ Keep code that makes tests pass without running them -- ❌ Use vague language like "should work" or "probably passes" - -## Strict TDD Rules - -Based on `.claude/skills/methodology/test-driven-development/SKILL.md`: - -### Rule 1: No Production Code Without Failing Test - -**WRONG:** -``` -"Let me write the function first, then add tests" -"I'll implement it and test as I go" -``` - -**RIGHT:** -``` -1. Write test that calls feature() -2. Run test - watch it FAIL -3. Write feature() to make test PASS -4. Run test - watch it PASS -``` - -### Rule 2: If You Already Wrote Code, Delete It - -If you accidentally wrote production code before tests: - -**WRONG:** -``` -"I'll keep this code as reference while writing tests" -"Let me comment it out for now" -``` - -**RIGHT:** -``` -Delete the code completely. -Write the test. -Rewrite the implementation. -``` - -### Rule 3: Verify Before Claiming - -Based on `.claude/skills/methodology/verification-before-completion/SKILL.md`: - -Before saying "tests pass": - -1. **Identify** the exact command to run tests -2. **Execute** it completely and freshly -3. **Read** the complete output -4. **Verify** output matches your claim -5. **Only then** make the claim - -**Forbidden Language:** -- ❌ "should work" -- ❌ "probably fixed" -- ❌ "seems to pass" -- ❌ "tests should pass" - -**Required Language:** -- ✅ "Tests pass: [paste output]" -- ✅ "Verified by running: [command]" - -## Testing Anti-Patterns to Avoid - -Based on `.claude/skills/methodology/testing-anti-patterns/SKILL.md`: - -### 1. Testing Mock Behavior - -**WRONG:** -```python -def test_sends_email(): - mock_mailer = Mock() - send_email(mock_mailer, "test@example.com") - mock_mailer.send.assert_called_once() # Testing mock, not code! -``` - -**RIGHT:** -```python -def test_sends_email(): - mailer = FakeMailer() # Real implementation - send_email(mailer, "test@example.com") - assert mailer.sent_emails[0].to == "test@example.com" -``` - -### 2. Test-Only Methods in Production - -**WRONG:** -```python -class User: - def __init__(self, name): - self.name = name - - def set_id_for_testing(self, id): # Only for tests! - self.id = id -``` - -**RIGHT:** -```python -class User: - def __init__(self, name, id=None): - self.name = name - self.id = id or generate_id() - -# Test uses real constructor -user = User("John", id="test-id-123") -``` - -### 3. Incomplete Mocks - -**WRONG:** -```typescript -const mockDb = { - findUser: vi.fn() - // Missing other methods that will be called! -}; -``` - -**RIGHT:** -```typescript -const mockDb: Database = { - findUser: vi.fn(), - saveUser: vi.fn(), - deleteUser: vi.fn(), - // All methods implemented -}; -``` - -## Example TDD Session - -### Input -```bash -/tdd "Create a password validator that checks strength" -``` - -### Output - -```markdown -## TDD Session: Password Validator - -### Phase 1: RED - Write Failing Test - -Created `tests/test_password_validator.py`: - -```python -import pytest -from src.password_validator import validate_password - -def test_validates_strong_password(): - """Test that strong password passes validation.""" - result = validate_password("StrongP@ss123") - assert result is True - -def test_rejects_short_password(): - """Test that short password fails.""" - with pytest.raises(ValueError, match="too short"): - validate_password("weak") - -def test_rejects_password_without_numbers(): - """Test that password without numbers fails.""" - with pytest.raises(ValueError, match="must contain number"): - validate_password("NoNumbers!") -``` - -Running tests: -```bash -$ pytest tests/test_password_validator.py -v - -test_password_validator.py::test_validates_strong_password FAILED - ModuleNotFoundError: No module named 'src.password_validator' -``` - -✅ Tests FAIL as expected (module doesn't exist) - ---- - -### Phase 2: GREEN - Make Tests Pass - -Created `src/password_validator.py`: - -```python -import re - -MIN_LENGTH = 8 - -def validate_password(password: str) -> bool: - """ - Validate password strength. - - Args: - password: Password to validate - - Returns: - True if password is strong - - Raises: - ValueError: If password doesn't meet requirements - """ - if len(password) < MIN_LENGTH: - raise ValueError(f"Password too short (minimum {MIN_LENGTH})") - - if not re.search(r'\d', password): - raise ValueError("Password must contain number") - - if not re.search(r'[A-Z]', password): - raise ValueError("Password must contain uppercase letter") - - if not re.search(r'[!@#$%^&*]', password): - raise ValueError("Password must contain special character") - - return True -``` - -Running tests: -```bash -$ pytest tests/test_password_validator.py -v - -test_password_validator.py::test_validates_strong_password PASSED -test_password_validator.py::test_rejects_short_password PASSED -test_password_validator.py::test_rejects_password_without_numbers PASSED - -====== 3 passed in 0.12s ====== -``` - -✅ All tests PASS - ---- - -### Phase 3: REFACTOR - Improve Code - -Extracted validation rules into separate functions: - -```python -import re -from typing import List - -MIN_LENGTH = 8 -REQUIRED_PATTERNS = [ - (r'\d', "number"), - (r'[A-Z]', "uppercase letter"), - (r'[!@#$%^&*]', "special character"), -] - -def validate_password(password: str) -> bool: - """Validate password strength.""" - check_length(password) - check_required_patterns(password) - return True - -def check_length(password: str) -> None: - """Check password meets minimum length.""" - if len(password) < MIN_LENGTH: - raise ValueError(f"Password too short (minimum {MIN_LENGTH})") - -def check_required_patterns(password: str) -> None: - """Check password contains required character types.""" - for pattern, name in REQUIRED_PATTERNS: - if not re.search(pattern, password): - raise ValueError(f"Password must contain {name}") -``` - -Running tests: -```bash -$ pytest tests/test_password_validator.py -v - -====== 3 passed in 0.11s ====== -``` - -✅ Tests still PASS after refactoring - ---- - -### Phase 4: REPEAT - Add More Tests - -Added edge case test: - -```python -def test_rejects_empty_password(): - """Test that empty password fails.""" - with pytest.raises(ValueError, match="too short"): - validate_password("") -``` - -```bash -$ pytest tests/test_password_validator.py -v - -====== 4 passed in 0.13s ====== -``` - -✅ New test passes immediately (covered by existing implementation) - ---- - -### Cycle Summary -- **Red**: 3 tests written, all failed initially ✅ -- **Green**: Implementation created, all tests pass ✅ -- **Refactor**: Extracted helper functions, tests still pass ✅ -- **Repeat**: Added edge case test ✅ - -### Final Stats -- Tests: 4 (all passing) -- Coverage: 100% -- Lines of code: 28 -- Complexity: Low (simple functions) -``` - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--strict` | Extra strict TDD enforcement | `--strict` | -| `--framework=[fw]` | Specify test framework | `--framework=vitest` | -| `--format=[fmt]` | Output format (concise/detailed) | `--format=concise` | - -### Flag Examples - -```bash -# Strict TDD with verbose output -/tdd --strict --format=detailed "user authentication" - -# TDD with specific framework -/tdd --framework=jest "form validation" -``` - -## Deliverables - -After a TDD session, you receive: - -1. **Test File** - Complete test suite written first -2. **Implementation** - Minimal code that passes tests -3. **Verification** - Proof that tests failed then passed -4. **Refactored Code** - Clean, well-structured implementation -5. **Coverage Report** - Typically 100% for TDD code - -## Related Commands - -- [/test](/claudekit/commands/test) - Generate tests for existing code -- [/feature](/claudekit/commands/feature) - Full feature workflow -- [/fix](/claudekit/commands/fix) - Fix bugs with regression tests -- [/refactor](/claudekit/commands/refactor) - Refactor while keeping tests green diff --git a/website/src/content/docs/commands/test.md b/website/src/content/docs/commands/test.md deleted file mode 100644 index 960d4fb..0000000 --- a/website/src/content/docs/commands/test.md +++ /dev/null @@ -1,355 +0,0 @@ ---- -title: /test -description: Generate comprehensive tests including unit tests, integration tests, and edge cases ---- - -# /test - Test Generation Command - -## Purpose - -Generate comprehensive tests for specified code including unit tests, integration tests, and edge cases. Analyzes your code to create test suites that catch bugs and verify behavior. - -## Usage - -```bash -/test [file path | function name | 'coverage' | 'all'] -``` - -## Arguments - -- `[file path]` - Generate tests for specific file or pattern -- `[function name]` - Generate tests for specific function -- `coverage` - Analyze and improve test coverage -- `all` - Run all tests and report results - -## How It Works - -The `/test` command has two main modes: - -### Mode 1: File/Function Testing - -1. **Analyze Target Code** - - Reads the code to understand functionality - - Identifies inputs, outputs, and side effects - - Notes dependencies to mock - - Finds 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** - - Follows project testing conventions - - Uses appropriate mocking strategies - - Writes clear, descriptive test names - - Includes setup and teardown - -4. **Run and Verify** - ```bash - # Python - pytest [test_file] -v - - # TypeScript - pnpm test [test_file] - ``` - -### Mode 2: Coverage Analysis - -1. **Run Coverage Report** - ```bash - # Python - pytest --cov=src --cov-report=term-missing - - # TypeScript - pnpm test --coverage - ``` - -2. **Identify Gaps** - - Finds untested functions - - Identifies untested branches - - Notes missing edge cases - -3. **Generate Missing Tests** - - Prioritizes by risk - - Focuses on critical paths - - Adds 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(); - }); -}); -``` - -## 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` | - -### 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) | - -### Flag Examples - -```bash -# Analyze and improve coverage -/test --coverage src/services/ - -# Generate integration tests -/test --type=integration src/api/users.ts - -# TDD mode: failing tests first -/test --tdd src/utils/validator.ts - -# Edge case focused testing -/test --edge-cases --framework=pytest src/models/user.py -``` - -## Examples - -### Generate Tests for File - -**Input:** -```bash -/test src/services/auth.ts -``` - -**Output:** -```markdown -## Tests Generated - -### Target -`src/services/auth.ts` - AuthService class - -### Tests Created -- `src/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 src/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 -``` - -### Coverage Analysis - -**Input:** -```bash -/test coverage -``` - -**Output:** -1. Runs coverage report -2. Identifies untested files/functions -3. Generates tests for gaps -4. Prioritizes by criticality -5. Shows before/after coverage metrics - -### Generate Integration Tests - -**Input:** -```bash -/test --type=integration src/api/ -``` - -**Output:** -1. Identifies API endpoints -2. Creates end-to-end request tests -3. Mocks external dependencies -4. Tests error responses -5. Verifies status codes and payloads - -## Deliverables - -After running `/test`, you receive: - -1. **Test File(s)** - Complete test suite with: - - Happy path tests - - Edge case tests - - Error scenario tests - - Mocked dependencies - -2. **Coverage Report** - Before/after metrics showing improvement - -3. **Run Commands** - Exact commands to execute tests - -4. **Notes** - Testing strategy and recommendations - -## Related Commands - -- [/tdd](/claudekit/commands/tdd) - Test-driven development workflow -- [/feature](/claudekit/commands/feature) - Includes test generation -- [/fix](/claudekit/commands/fix) - Includes regression tests -- [/review](/claudekit/commands/review) - Reviews test quality diff --git a/website/src/content/docs/customization/claude-md.md b/website/src/content/docs/customization/claude-md.md deleted file mode 100644 index d9dd3d7..0000000 --- a/website/src/content/docs/customization/claude-md.md +++ /dev/null @@ -1,1012 +0,0 @@ ---- -title: CLAUDE.md Reference -description: Complete reference for configuring Claude Kit behavior through CLAUDE.md. ---- - -# CLAUDE.md Reference - -`CLAUDE.md` is your project's configuration file. It defines your tech stack, conventions, standards, and how Claude should behave when working on your codebase. - -## What is CLAUDE.md? - -`CLAUDE.md` is the central configuration file that tells Claude: - -- **What** your project uses (tech stack, frameworks, tools) -- **How** your project is organized (architecture, file structure) -- **Why** you make certain decisions (conventions, standards) -- **When** to use specific approaches (agent behavior overrides) - -It lives at `.claude/CLAUDE.md` in your project root. - -## File Structure Overview - -```markdown -# Project Name - Project Context - -## Overview -[Brief project description] - -## Quick Reference -[Command shortcuts and common tasks] - -## Tech Stack -[Languages, frameworks, databases, tools] - -## Architecture -[Project structure and organization] - -## Code Conventions -[Naming, style, file organization] - -## Testing Standards -[Coverage, naming, test types] - -## Security Standards -[Forbidden patterns, required practices] - -## Git Conventions -[Branch naming, commits, PR requirements] - -## Agent Behavior Overrides -[Customize how agents work] - -## Behavioral Modes -[Available modes and when to use them] - -## Command Flags -[Universal flags and options] - -## Environment Configuration -[Dev, test, deployment commands] - -## External Integrations -[APIs, services, third-party tools] - -## Documentation Standards -[What and how to document] -``` - -## Complete Section-by-Section Reference - -### 1. Overview - -Introduce your project: - -```markdown -## Overview - -This is a SaaS platform for team collaboration built with: -- Next.js frontend -- FastAPI backend -- PostgreSQL database -- Deployed on Cloudflare - -Team size: 2 developers -Focus: Speed of development with high quality -``` - -**What to include:** -- Project purpose -- Team size -- Development priorities - -### 2. Quick Reference - -List commonly used commands: - -```markdown -## Quick Reference - -### Core Commands - -| 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 | -``` - -**What to include:** -- Most-used commands -- Project-specific commands -- Quick task shortcuts - -### 3. Tech Stack - -Define your technology choices: - -```markdown -## Tech Stack - - -- **Languages**: Python 3.11, TypeScript 5.0 -- **Backend**: FastAPI 0.104, SQLAlchemy -- **Frontend**: Next.js 14, React 18 -- **Database**: PostgreSQL 15 -- **Testing**: pytest, Playwright, vitest -- **DevOps**: Docker, GitHub Actions, Cloudflare Pages -- **Tools**: pnpm, black, eslint -``` - -**What to include:** -- All languages and versions -- Frameworks with versions -- Databases and data stores -- Testing tools -- Deployment platforms -- Development tools - -**Why this matters:** -Claude uses this to: -- Choose appropriate syntax -- Suggest compatible libraries -- Follow version-specific patterns -- Load relevant skills - -### 4. Architecture - -Describe your project structure: - -```markdown -## Architecture - - - -### Backend (Python/FastAPI) -\`\`\` -backend/ -├── api/ -│ ├── routes/ # API endpoints -│ ├── models/ # SQLAlchemy models -│ └── schemas/ # Pydantic schemas -├── services/ # Business logic -├── utils/ # Shared utilities -└── tests/ # Test files -\`\`\` - -### Frontend (Next.js/React) -\`\`\` -frontend/ -├── app/ # App router pages -├── components/ # React components -│ ├── ui/ # shadcn/ui components -│ └── features/ # Feature components -├── lib/ # Utilities and API client -└── tests/ # Component tests -\`\`\` - -### Architecture Decisions -- **Monorepo**: Backend and frontend in same repo -- **API-First**: Backend exposes REST API -- **Component Library**: Using shadcn/ui for consistency -``` - -**What to include:** -- Directory structure -- Architecture patterns -- Key design decisions - -**Why this matters:** -Claude uses this to: -- Know where to put new files -- Follow your organization patterns -- Suggest appropriate file locations - -### 5. Code Conventions - -Define coding standards: - -```markdown -## Code Conventions - -### Naming Conventions - -| Type | Python | TypeScript | -|------|--------|-----------| -| Files | `snake_case.py` | `kebab-case.ts` | -| Functions | `snake_case` | `camelCase` | -| Classes | `PascalCase` | `PascalCase` | -| Constants | `UPPER_SNAKE` | `UPPER_SNAKE` | -| Components | N/A | `PascalCase.tsx` | - -### Code Style - -**Python:** -- Follow PEP 8 -- Use type hints for all functions -- Docstrings for public APIs (Google style) -- Max line length: 88 (Black default) - -**TypeScript:** -- Strict mode enabled -- No `any` types (use `unknown`) -- Prefer interfaces over types -- Use named exports - -### File Organization - -- One component/class per file -- Group related files in feature directories -- Test files adjacent to source: `component.tsx` + `component.test.tsx` -- Index files for clean imports - -### Example File Structure -\`\`\` -features/auth/ -├── components/ -│ ├── LoginForm.tsx -│ └── LoginForm.test.tsx -├── hooks/ -│ ├── useAuth.ts -│ └── useAuth.test.ts -└── index.ts # Export public API -\`\`\` -``` - -**What to include:** -- Naming conventions for all types -- Style guide rules -- File organization patterns -- Import/export conventions - -**Why this matters:** -Claude uses this to: -- Name files consistently -- Follow your style preferences -- Organize code like your team does - -### 6. Testing Standards - -Set testing requirements: - -```markdown -## Testing Standards - -### Coverage Requirements -- **Minimum coverage**: 80% -- **Critical paths**: 95% (auth, payments, data processing) -- **New features**: Must include tests - -### Test Naming - -**Python (pytest):** -\`\`\`python -def test_[function]_[scenario]_[expected](): - # Example: test_create_user_with_valid_data_succeeds -\`\`\` - -**TypeScript (vitest):** -\`\`\`typescript -describe('[Component]', () => { - it('should [behavior] when [scenario]', () => { - // Example: should display error when email is invalid - }); -}); -\`\`\` - -### Test Types - -1. **Unit Tests** (Required) - - All business logic functions - - All utility functions - - Test file naming: `*.test.ts` or `test_*.py` - -2. **Integration Tests** (Required) - - API endpoints - - Database operations - - External service integrations - -3. **E2E Tests** (For Critical Flows) - - User authentication - - Payment processing - - Core user journeys - -### Test Organization - -**Python:** -\`\`\` -tests/ -├── unit/ -├── integration/ -└── e2e/ -\`\`\` - -**TypeScript:** -\`\`\` -src/ -├── component.tsx -└── component.test.tsx # Tests adjacent to code -\`\`\` - -### Test Best Practices - -- **Arrange-Act-Assert** pattern -- Use fixtures/factories for test data -- Mock external dependencies -- Keep tests independent -- Test edge cases and errors -``` - -**What to include:** -- Coverage requirements -- Test naming conventions -- Required test types -- Test organization -- Testing best practices - -**Why this matters:** -Claude uses this to: -- Generate appropriate tests -- Meet coverage requirements -- Follow your test patterns - -### 7. Security Standards - -Define security requirements: - -```markdown -## Security Standards - -### Forbidden Patterns - -**Never allow these in code:** -- ❌ Hardcoded secrets or API keys -- ❌ `eval()` or dynamic code execution -- ❌ SQL string concatenation -- ❌ TypeScript `any` types -- ❌ Disabled security headers -- ❌ Raw user input in HTML -- ❌ Unvalidated redirects - -### Required Practices - -**Always enforce these:** -- ✅ Input validation on all user inputs -- ✅ Output encoding for rendered content -- ✅ Authentication on protected endpoints -- ✅ Rate limiting on public APIs -- ✅ Secrets via environment variables only -- ✅ HTTPS only (no HTTP) -- ✅ CSRF protection on state-changing operations -- ✅ SQL parameterized queries only - -### Security Checklist - -Before merging code: -- [ ] No secrets in code or commits -- [ ] All inputs validated -- [ ] All outputs encoded -- [ ] Authentication/authorization implemented -- [ ] Rate limiting configured -- [ ] HTTPS enforced -- [ ] Dependencies up to date (no critical CVEs) - -### Security Review - -**When to trigger security review:** -- Authentication/authorization changes -- Payment processing -- User data handling -- File uploads -- External API integration - -**How to request:** -\`\`\` -/review --persona=security src/auth/ -\`\`\` -``` - -**What to include:** -- Forbidden code patterns -- Required security practices -- Security review triggers -- Vulnerability prevention - -**Why this matters:** -Claude uses this to: -- Reject insecure code patterns -- Suggest secure alternatives -- Flag security concerns early - -### 8. Git Conventions - -Define Git workflow: - -```markdown -## Git Conventions - -### Branch Naming - -- `feature/[ticket]-[description]` — New features -- `fix/[ticket]-[description]` — Bug fixes -- `hotfix/[description]` — Emergency fixes -- `chore/[description]` — Maintenance tasks -- `docs/[description]` — Documentation only - -**Examples:** -- `feature/AUTH-123-add-oauth` -- `fix/PAY-456-cart-calculation` -- `hotfix/critical-security-patch` - -### Commit Messages - -Follow conventional commits: - -\`\`\` -type(scope): subject - -body (optional) - -footer (optional) -\`\`\` - -**Types:** -- `feat` — New feature -- `fix` — Bug fix -- `docs` — Documentation only -- `style` — Formatting, no code change -- `refactor` — Code restructure, no behavior change -- `test` — Adding/updating tests -- `chore` — Build, tools, dependencies - -**Examples:** -\`\`\` -feat(auth): add OAuth login support - -fix(payment): correct tax calculation for EU customers - -docs(api): update authentication examples - -refactor(db): extract query builder to separate module -\`\`\` - -### PR Requirements - -All PRs must have: -- [ ] Descriptive title and description -- [ ] Linked issue/ticket number -- [ ] All tests passing -- [ ] Code review approval (min 1) -- [ ] No merge conflicts -- [ ] Updated documentation (if applicable) - -### PR Template - -\`\`\`markdown -## Description -[What does this PR do?] - -## Related Issue -Fixes #[issue number] - -## Changes -- Change 1 -- Change 2 - -## Testing -- [ ] Unit tests added/updated -- [ ] Integration tests passing -- [ ] Manually tested - -## Screenshots (if applicable) -[Add screenshots] - -## Checklist -- [ ] Code follows style guidelines -- [ ] Tests pass locally -- [ ] Documentation updated -\`\`\` -``` - -**What to include:** -- Branch naming pattern -- Commit message format -- PR requirements -- PR template - -**Why this matters:** -Claude uses this to: -- Name branches correctly -- Write proper commit messages -- Create compliant PRs - -### 9. Agent Behavior Overrides - -Customize how built-in agents work: - -```markdown -## Agent Behavior Overrides - - - -### Planner Agent -- **Task Size**: 15-60 minutes (not 2-5 minutes) -- **Always Include**: Testing requirements for each task -- **Flag**: External dependencies and third-party APIs -- **Format**: Checklist with acceptance criteria - -### Code-Reviewer Agent -- **Priority**: Security first, then performance, then style -- **Strictness**: Enforce strict typing (no `any`) -- **Coverage**: Flag any code without tests -- **Style**: Auto-fix formatting issues, don't just comment - -### Tester Agent -- **Framework**: pytest for Python, vitest for TypeScript -- **Coverage**: Minimum 80%, target 90% -- **Focus**: Edge cases and error scenarios required -- **Integration**: Always include at least one integration test - -### Debugger Agent -- **First Step**: Always check logs before proposing fixes -- **Reproduce**: Attempt to reproduce before fixing -- **Tests**: Add regression test for every bug fix -- **Root Cause**: Find root cause, not just symptoms - -### Docs-Manager Agent -- **Level**: Write for intermediate developers -- **Format**: Markdown with code examples -- **Required**: API docs for all public functions -- **Examples**: Include at least one example per function -``` - -**What to include:** -- Which agents to customize -- Specific behavior changes -- Priorities and preferences - -**Why this matters:** -Overrides default agent behavior to match your team's workflow. - -### 10. Behavioral Modes - -Configure available modes: - -```markdown -## Behavioral Modes - - - -Modes adjust communication style, output format, and problem-solving approach. - -| Mode | Description | Best For | -|------|-------------|----------| -| `default` | Balanced standard behavior | General tasks | -| `brainstorm` | Creative exploration | Design, ideation | -| `token-efficient` | Compressed output | Cost savings | -| `deep-research` | Thorough analysis | Investigation | -| `implementation` | Code-focused | Executing plans | -| `review` | Critical analysis | Code review | -| `pair-programming` | Interactive, explanatory | Learning | - -### Mode Activation - -\`\`\`bash -/mode brainstorm # Switch mode for session -/feature --mode=implementation # Override for single command -\`\`\` - -Mode files: `.claude/modes/` - -### Custom Modes - -We've added these custom modes: -- `emergency-debug` — Fast production debugging -- `documentation` — Documentation-focused writing -``` - -**What to include:** -- Available modes -- When to use each -- Custom modes added - -### 11. Command Flags - -Document universal flags: - -```markdown -## Command Flags - - - -All commands support combinable flags for flexible customization. - -### Universal Flags - -| Flag | Description | Values | -|------|-------------|--------| -| `--mode=[mode]` | Behavioral mode | default, brainstorm, token-efficient | -| `--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" -\`\`\` -``` - -### 12. Environment Configuration - -Document development commands: - -```markdown -## Environment Configuration - - - -### Development - -**Python Backend:** -\`\`\`bash -cd backend -python -m venv venv -source venv/bin/activate # Windows: venv\Scripts\activate -pip install -r requirements.txt -uvicorn main:app --reload -\`\`\` - -**Node.js Frontend:** -\`\`\`bash -cd frontend -pnpm install -pnpm dev -\`\`\` - -### Testing - -**Backend:** -\`\`\`bash -pytest -v --cov=src -pytest --cov=src --cov-report=html # Coverage report -\`\`\` - -**Frontend:** -\`\`\`bash -pnpm test # Unit tests -pnpm test:coverage # With coverage -pnpm test:e2e # E2E tests -\`\`\` - -### Deployment - -**Staging:** -\`\`\`bash -pnpm build -pnpm deploy:staging -\`\`\` - -**Production:** -\`\`\`bash -pnpm build -pnpm deploy:production -# Requires manual approval in GitHub Actions -\`\`\` - -### Environment Variables - -Required variables: - -**Backend (.env):** -\`\`\` -DATABASE_URL=postgresql://user:pass@localhost/db -SECRET_KEY=your-secret-key -API_BASE_URL=http://localhost:8000 -\`\`\` - -**Frontend (.env.local):** -\`\`\` -NEXT_PUBLIC_API_URL=http://localhost:8000 -NEXT_PUBLIC_ENV=development -\`\`\` -``` - -**What to include:** -- Setup commands for each environment -- Test commands -- Deployment procedures -- Required environment variables - -### 13. External Integrations - -Document external services: - -```markdown -## External Integrations - - - -### APIs - -**GitHub API** -- Used for: Issue tracking, PR automation -- Auth: Personal access token in `GITHUB_TOKEN` -- Rate limit: 5000 requests/hour - -**Stripe API** -- Used for: Payment processing -- Auth: Secret key in `STRIPE_SECRET_KEY` -- Environment: Use test keys in development - -### Services - -**Database: PostgreSQL** -- Host: `DATABASE_URL` environment variable -- Migrations: `pnpm migrate` -- Backups: Automated daily at 2 AM UTC - -**Cache: Redis** (optional) -- Used for: Session storage, rate limiting -- Host: `REDIS_URL` environment variable - -**Storage: Cloudflare R2** -- Used for: User uploads, static assets -- Auth: Access key in `R2_ACCESS_KEY` - -### Third-Party Libraries - -**Critical dependencies:** -- `next-auth` — Authentication -- `prisma` — Database ORM -- `zod` — Validation -- `swr` — Data fetching - -**Update policy:** -- Security patches: Apply immediately -- Minor versions: Monthly review -- Major versions: Quarterly planning -``` - -**What to include:** -- External APIs and auth -- Database and storage services -- Key dependencies -- Update policies - -### 14. Documentation Standards - -Define documentation requirements: - -```markdown -## Documentation Standards - -### Code Documentation - -**Python:** -- Public functions: Google-style docstrings required -- Complex logic: Inline comments -- Type hints: Required for all functions - -\`\`\`python -def calculate_total(items: list[Item], discount: float = 0.0) -> float: - """ - Calculate total price with optional discount. - - Args: - items: List of items to calculate total for. - discount: Discount percentage (0.0 to 1.0). - - Returns: - Total price after discount. - - Raises: - ValueError: If discount is not between 0 and 1. - """ -\`\`\` - -**TypeScript:** -- Public functions: JSDoc required -- Components: Props interface with comments -- Complex logic: Inline comments - -\`\`\`typescript -/** - * Calculate total price with optional discount. - * - * @param items - Items to calculate total for - * @param discount - Discount percentage (0 to 1) - * @returns Total price after discount - * @throws {RangeError} If discount not between 0 and 1 - */ -function calculateTotal(items: Item[], discount = 0): number { -\`\`\` - -### API Documentation - -- OpenAPI/Swagger specs required -- Update with every API change -- Include request/response examples -- Document error responses - -### Project Documentation - -**README.md:** -- Quick start guide -- Prerequisites -- Setup instructions -- Common commands - -**CONTRIBUTING.md:** -- How to contribute -- Code review process -- Testing requirements - -**CHANGELOG.md:** -- Keep updated with each release -- Follow Keep a Changelog format -- Group changes by type (Added, Changed, Fixed) -``` - -**What to include:** -- Code documentation format -- API documentation requirements -- Project documentation files -- Update requirements - -## Complete CLAUDE.md Example - -Here's a complete, real-world example: - -```markdown -# Acme SaaS - Project Context - -## Overview - -Team collaboration platform with real-time features. -- Team: 2 developers -- Stack: Next.js + FastAPI + PostgreSQL -- Deploy: Cloudflare Pages + Cloudflare Workers - -## Tech Stack - -- **Frontend**: Next.js 14, React 18, TypeScript -- **Backend**: FastAPI, Python 3.11, SQLAlchemy -- **Database**: PostgreSQL 15 -- **Testing**: pytest, Playwright, vitest -- **DevOps**: Docker, GitHub Actions, Cloudflare - -## Code Conventions - -### Naming -- Files: `kebab-case.ts`, `snake_case.py` -- Functions: `camelCase` (TS), `snake_case` (Python) -- Classes: `PascalCase` - -### Style -- TypeScript: Strict mode, no `any` -- Python: PEP 8, type hints required -- Max line length: 88 (Black) - -## Testing Standards - -- Coverage minimum: 80% -- Test naming: `test_[function]_[scenario]_[expected]` -- Required: Unit tests for all business logic - -## Security Standards - -### Forbidden -- No hardcoded secrets -- No SQL concatenation -- No `any` types - -### Required -- Input validation -- Authentication on protected routes -- Rate limiting - -## Agent Behavior Overrides - -### Tester Agent -- Framework: pytest (Python), vitest (TypeScript) -- Coverage: 80% minimum -- Focus: Edge cases required - -### Code-Reviewer Agent -- Enforce strict typing -- Security-first reviews -- Flag missing tests - -## Environment Configuration - -### Development -\`\`\`bash -pnpm install -pnpm dev -\`\`\` - -### Testing -\`\`\`bash -pnpm test -\`\`\` -``` - -## CUSTOMIZATION POINTS - -Throughout `CLAUDE.md`, you'll find `` comments. These mark sections you should customize: - -```markdown -## Tech Stack - - -- **Languages**: Your languages here -``` - -Always customize: -- Tech Stack -- Architecture -- Code Conventions -- Testing Standards -- Agent Behavior Overrides -- Environment Configuration - -## Best Practices - -### 1. Start Simple - -Begin with basics: -- Tech stack -- Basic conventions -- Required testing - -Add complexity as needed. - -### 2. Keep It Updated - -Update `CLAUDE.md` when: -- Adding new technologies -- Changing conventions -- Updating standards -- Learning what works - -### 3. Be Specific - -```markdown -# Vague: Don't do this -- Write good tests -- Follow best practices - -# Specific: Do this -- Unit tests for all business logic (80% coverage) -- Integration tests for all API endpoints -- E2E tests for critical user flows -``` - -### 4. Use Examples - -```markdown -## Commit Messages - -Format: `type(scope): subject` - -Examples: -- `feat(auth): add OAuth login` -- `fix(cart): correct tax calculation` -``` - -## Next Steps - -- [Customization Overview](/claudekit/customization/overview/) — Start here -- [Creating Commands](/claudekit/customization/creating-commands/) — Add custom workflows -- [Creating Modes](/claudekit/customization/creating-modes/) — Define behaviors -- [Creating Skills](/claudekit/customization/creating-skills/) — Add knowledge - -## Getting Help - -- See the [template CLAUDE.md](https://github.com/yourusername/claudekit/blob/main/.claude/CLAUDE.md) in the repo -- Check [example configurations](https://github.com/yourusername/claudekit/tree/main/examples) for different project types -- Ask in [discussions](https://github.com/yourusername/claudekit/discussions) diff --git a/website/src/content/docs/customization/creating-agents-and-modes.md b/website/src/content/docs/customization/creating-agents-and-modes.md new file mode 100644 index 0000000..49d849f --- /dev/null +++ b/website/src/content/docs/customization/creating-agents-and-modes.md @@ -0,0 +1,214 @@ +--- +title: Creating Agents & Modes +description: How to create custom agents and behavioral modes for Claude Kit. +--- + +# Creating Agents & Modes + +Beyond skills, you can create specialized agents for focused tasks and behavioral modes for different work contexts. + +--- + +## Creating Agents + +Agents are specialized subagents that Claude dispatches for independent, focused work. Each agent gets a fresh context and specific tool access. + +### Agent Structure + +Agent files live in `.claude/agents/`: + +``` +.claude/agents/ +├── code-reviewer.md +├── debugger.md +└── my-custom-agent.md +``` + +### Agent File Format + +```markdown +--- +name: my-agent +description: One-line description of what this agent does and when to use it. +tools: [Read, Write, Edit, Bash, Grep, Glob] +model: sonnet +--- + +# My Agent + +## Role +[What this agent specializes in] + +## Approach +[How it should work through problems] + +## Output Format +[What it should return] + +## Examples +[Example inputs and expected outputs] +``` + +### Frontmatter Fields + +| Field | Required | Description | +|-------|----------|-------------| +| `name` | Yes | Agent identifier | +| `description` | Yes | When to dispatch this agent | +| `tools` | No | Tools the agent can use (defaults to all) | +| `model` | No | Model override (sonnet, opus, haiku) | + +### Example: Custom Agent + +```markdown +--- +name: migration-checker +description: Use when running database migrations to verify safety. + Check for destructive operations, missing rollbacks, and data loss risks. +tools: [Read, Grep, Glob, Bash] +model: sonnet +--- + +# Migration Checker + +## Role +Review database migration files for safety before execution. + +## Checklist +1. Check for destructive operations (DROP TABLE, DROP COLUMN) +2. Verify rollback/down migration exists +3. Check for data loss risks (column type changes, NOT NULL without default) +4. Estimate lock duration on large tables +5. Verify migration is idempotent + +## Output Format +Return a safety report: +- SAFE: No issues found +- WARNING: Issues that need review (list them) +- BLOCKED: Destructive changes that need approval +``` + +### When to Create an Agent vs. a Skill + +| Use an Agent when... | Use a Skill when... | +|---------------------|---------------------| +| Task needs isolated context | Knowledge should be in main conversation | +| Work can run independently | Patterns apply inline to current work | +| Multiple tasks can parallelize | Guidance is sequential/conversational | +| Fresh perspective needed | Context from conversation matters | + +--- + +## Creating Modes + +Modes change Claude's communication style, output format, and problem-solving approach for the duration of a session. + +### Mode Structure + +Mode files live in `.claude/modes/`: + +``` +.claude/modes/ +├── brainstorm.md +├── implementation.md +└── my-custom-mode.md +``` + +### Mode File Format + +```markdown +--- +name: my-mode +description: One-line description of this mode's behavior. +--- + +# My Mode + +## Communication Style +[How Claude should communicate in this mode] + +## Output Format +[What outputs should look like] + +## Problem-Solving Approach +[How Claude should approach tasks] + +## When to Use +[Best scenarios for this mode] +``` + +### Example: Custom Mode + +```markdown +--- +name: pair-programming +description: Interactive pair programming mode with frequent check-ins. +--- + +# Pair Programming Mode + +## Communication Style +- Think out loud — explain reasoning as you code +- Ask before making non-obvious decisions +- Suggest alternatives when multiple approaches exist +- Keep explanations conversational, not formal + +## Output Format +- Show code in small chunks (10-20 lines) +- Pause after each chunk for feedback +- Use comments to explain "why", not "what" + +## Problem-Solving Approach +- Start with the simplest approach +- Refactor only when the user agrees +- Test each change before moving on +- Never make large changes without discussion + +## When to Use +- Learning a new codebase together +- Complex features where design decisions need discussion +- Mentoring or teaching scenarios +``` + +### Example: Compliance Mode + +```markdown +--- +name: compliance +description: Strict compliance mode for regulated industries. +--- + +# Compliance Mode + +## Communication Style +- Formal, precise language +- Reference specific regulations when relevant +- Flag compliance risks proactively + +## Output Format +- Include audit trail comments in code +- Document all security decisions +- Generate compliance checklists + +## Problem-Solving Approach +- Security and compliance over convenience +- Prefer established patterns over novel solutions +- Require explicit approval for any data handling changes +``` + +## Activating Custom Modes + +Once created, switch to your mode naturally: + +``` +"switch to pair-programming mode" +"use compliance mode" +``` + +Or reference the mode-switching skill keywords. + +## Related Pages + +- [Agents Reference](/claudekit/reference/agents/) — All 20 built-in agents +- [Modes Reference](/claudekit/reference/modes/) — All 7 built-in modes +- [Creating Skills](/claudekit/customization/creating-skills/) — Custom skill creation diff --git a/website/src/content/docs/customization/creating-commands.md b/website/src/content/docs/customization/creating-commands.md deleted file mode 100644 index 9bd56f5..0000000 --- a/website/src/content/docs/customization/creating-commands.md +++ /dev/null @@ -1,590 +0,0 @@ ---- -title: Creating Custom Commands -description: Learn how to create custom slash commands for your project-specific workflows. ---- - -# Creating Custom Commands - -Custom commands let you automate project-specific workflows with simple slash commands. This guide shows you how to create commands that integrate seamlessly with Claude Kit. - -## Command File Structure - -Commands are markdown files in `.claude/commands/`: - -``` -.claude/commands/ -├── your-command.md # /your-command -├── deploy-prod.md # /deploy-prod -└── weekly-report.md # /weekly-report -``` - -The filename (without `.md`) becomes the command name. - -## Command Template - -Here's the complete template for a command file: - -```markdown -# /command-name - Short Description - -## Purpose - -Brief description of what this command does and why it exists. - -## Usage - -\`\`\` -/command-name [arguments] -\`\`\` - -## Arguments - -- `$ARGUMENTS`: Description of what arguments this command accepts - ---- - -Execute workflow for: **$ARGUMENTS** - -## Workflow - -### Phase 1: First Step - -Description of what happens in this phase. - -1. **Task 1** - - Details about task 1 - - What to check or do - -2. **Task 2** - - Details about task 2 - - Expected outcomes - -### Phase 2: Second Step - -Description of next phase. - -1. **Task 1** - - Details - - Actions - -## Output - -Describe what the command should produce: - -\`\`\`markdown -## [Command Name] Complete - -### Summary -[What was done] - -### Results -- Item 1 -- Item 2 - -### Next Steps -1. Next action -2. Another action -\`\`\` - -## Example - -**Input**: `/command-name example input` - -**Output**: Description of what happens with this example - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--flag-name` | What this flag does | `--flag-name=value` | - - -## Variations - -Optional section for project-specific variations. -``` - -## Command Anatomy - -### 1. Header Section - -```markdown -# /deploy - Deploy Application - -## Purpose - -Deploy the application to specified environment with pre-deployment checks, -database migrations, and post-deployment verification. -``` - -The header includes: - -- **Title**: Command name and one-line description -- **Purpose**: Detailed explanation of what and why - -### 2. Usage Section - -```markdown -## Usage - -\`\`\` -/deploy [environment] [--skip-tests] -\`\`\` - -## Arguments - -- `environment`: Target environment (staging, production) -- `--skip-tests`: Skip running tests before deployment -``` - -Define: - -- How to invoke the command -- What arguments it accepts -- Optional flags - -### 3. Separator Line - -```markdown ---- - -Deploy to **$ARGUMENTS** environment: -``` - -The `---` separator is important: - -- Everything above is documentation -- Everything below is the instruction Claude executes -- Use `$ARGUMENTS` to inject user input - -### 4. Workflow Section - -```markdown -## Workflow - -### Phase 1: Pre-deployment Checks - -1. **Verify Environment** - - Check environment exists - - Verify credentials - - Confirm deployment is allowed - -2. **Run Tests** - - Execute full test suite - - Check code coverage - - Fail if tests don't pass -``` - -Break down the command into: - -- Logical phases -- Numbered steps within phases -- Clear success criteria - -### 5. Output Section - -```markdown -## Output - -\`\`\`markdown -## Deployment Complete - -### Environment -Production - -### Changes Deployed -- API v2.3.1 -- Database migration: add_user_preferences -- Updated 15 files - -### Verification -- Health check: ✓ Passed -- Smoke tests: ✓ Passed - -### Rollback Command -/rollback production v2.3.0 -\`\`\` -``` - -Show what the successful output should look like. - -### 6. Examples Section - -```markdown -## Example - -**Input**: `/deploy production` - -**Output**: -1. Runs test suite (2 min) -2. Builds production bundle (1 min) -3. Deploys to production servers -4. Runs smoke tests -5. Reports deployment status -``` - -Provide concrete examples of usage. - -### 7. Flags Section - -```markdown -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--skip-tests` | Skip pre-deployment tests | `/deploy staging --skip-tests` | -| `--force` | Force deployment without confirmation | `/deploy prod --force` | -| `--rollback` | Rollback to previous version | `/deploy prod --rollback` | -``` - -Document all available flags. - -## Complete Example: Custom Deploy Command - -Here's a real-world example: - -```markdown -# /deploy - Deploy Application - -## Purpose - -Deploy the application to specified environment with automated checks, -database migrations, and verification steps. - -## Usage - -\`\`\` -/deploy [environment] -\`\`\` - -## Arguments - -- `environment`: Target environment (staging, production) - ---- - -Deploy to **$ARGUMENTS** environment: - -## Workflow - -### Phase 1: Pre-deployment Checks - -1. **Verify Environment Configuration** - - Check `.env.[environment]` file exists - - Verify required secrets are set - - Confirm environment is accessible - -2. **Run Test Suite** - ```bash - pnpm test - pnpm test:e2e - ``` - - All tests must pass - - Coverage must be >= 80% - -3. **Check for Breaking Changes** - - Review CHANGELOG.md - - Identify migration requirements - - Confirm database backup exists - -### Phase 2: Build - -1. **Build Production Bundle** - ```bash - pnpm build - ``` - - Verify build completes without errors - - Check bundle size - - Validate output directory - -2. **Run Database Migrations** - ```bash - pnpm migrate:$ARGUMENTS - ``` - - Apply pending migrations - - Verify migration success - - Create rollback script - -### Phase 3: Deploy - -1. **Deploy to Environment** - ```bash - pnpm deploy:$ARGUMENTS - ``` - - Upload built assets - - Update environment variables - - Restart services - -2. **Health Checks** - - Wait for services to start (30s) - - Verify API health endpoint - - Check database connectivity - -### Phase 4: Verification - -1. **Run Smoke Tests** - ```bash - pnpm smoke:$ARGUMENTS - ``` - - Test critical user paths - - Verify external integrations - - Check error rates - -2. **Monitor Deployment** - - Check application logs for errors - - Monitor performance metrics - - Verify no spike in error rate - -### Phase 5: Documentation - -1. **Update Deployment Log** - - Record deployment time - - Note version deployed - - List any manual steps taken - -2. **Notify Team** - - Post to Slack #deployments channel - - Include deployment summary - - Provide rollback instructions - -## Output - -\`\`\`markdown -## Deployment Complete: $ARGUMENTS - -### Version -v2.3.1 (commit: abc1234) - -### Deployment Time -2024-01-15 14:30 UTC (Duration: 4m 32s) - -### Changes Deployed -- Feature: User profile redesign -- Fix: Payment processing timeout -- Database: Migration #045 (add_user_preferences) - -### Verification Results -- Health Check: ✓ Passed -- Smoke Tests: ✓ All passed (12/12) -- Error Rate: 0.01% (normal) - -### Rollback Command -If issues arise, rollback with: -\`/rollback $ARGUMENTS v2.3.0\` - -### Monitoring -- Dashboard: https://monitoring.example.com -- Logs: https://logs.example.com -\`\`\` - -## Example - -**Input**: `/deploy production` - -**Output**: -1. Runs full test suite (3 min) -2. Builds production bundle (2 min) -3. Applies database migrations (30s) -4. Deploys to production cluster (1 min) -5. Runs smoke tests (1 min) -6. Posts deployment notification to Slack -7. Provides rollback command - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--skip-tests` | Skip test suite (not recommended for production) | `--skip-tests` | -| `--skip-migrations` | Skip database migrations | `--skip-migrations` | -| `--dry-run` | Simulate deployment without executing | `--dry-run` | -| `--force` | Skip confirmation prompts | `--force` | - -### Flag Usage - -```bash -/deploy staging --skip-tests # Deploy to staging without tests -/deploy production --dry-run # Simulate production deployment -/deploy production --skip-migrations # Deploy without DB changes -``` - - -## Project-Specific Variations - -Modify the workflow based on your deployment strategy: - -- Add CDN cache invalidation steps -- Include blue-green deployment logic -- Add feature flag configuration -- Include monitoring alert setup -``` - -## Best Practices - -### 1. Keep Commands Focused - -Each command should do ONE thing well: - -```markdown -# Good: Focused commands -/deploy [env] # Just deployment -/migrate [env] # Just migrations -/rollback [env] # Just rollback - -# Bad: Doing too much -/deploy-and-test-and-notify [env] -``` - -### 2. Use Clear Phase Names - -```markdown -# Good: Clear phases -### Phase 1: Pre-deployment Checks -### Phase 2: Build and Test -### Phase 3: Deploy - -# Bad: Vague phases -### Phase 1: Setup -### Phase 2: Main stuff -### Phase 3: Finish -``` - -### 3. Provide Verification Steps - -```markdown -## Workflow - -### Phase 2: Build - -1. **Build Application** - ```bash - pnpm build - ``` - - **Verification**: - - Check `dist/` folder exists - - Verify no build errors in output - - Confirm bundle size < 500KB -``` - -### 4. Include Error Handling - -```markdown -### Phase 3: Deploy - -1. **Deploy to Server** - - Upload build artifacts - - **If deployment fails**: - - Check server connectivity - - Verify deployment credentials - - Review server logs at `/var/log/app.log` - - Consider using `--force` flag -``` - -### 5. Add Real Examples - -```markdown -## Example - -**Scenario**: Deploy new feature to staging - -**Input**: `/deploy staging` - -**What happens**: -1. ✓ Tests pass (2m 15s) -2. ✓ Build succeeds (45s) -3. ✓ Migrations applied (2 migrations) -4. ✓ Deployment complete (30s) -5. ✓ Smoke tests pass (5/5) - -**Output**: Deployment summary with rollback command -``` - -## Common Command Patterns - -### Pattern 1: Multi-Step Workflow - -```markdown -# /release - Create Release - -## Workflow - -### Phase 1: Prepare -1. Verify clean working directory -2. Pull latest changes -3. Run full test suite - -### Phase 2: Version -1. Bump version number -2. Update CHANGELOG.md -3. Commit version changes - -### Phase 3: Release -1. Create git tag -2. Push to remote -3. Trigger CI/CD pipeline - -### Phase 4: Verify -1. Wait for CI build -2. Verify release artifacts -3. Post release notes -``` - -### Pattern 2: Interactive Workflow - -```markdown -# /onboard - Onboard New Team Member - -## Workflow - -### Phase 1: Environment Setup -1. **Ask for GitHub username** - - Add to organization - - Add to relevant teams - -2. **Ask for preferred IDE** - - Provide setup instructions - - Share configuration files -``` - -### Pattern 3: Conditional Workflow - -```markdown -# /optimize - Optimize Performance - -## Workflow - -### Phase 1: Analyze -1. Run performance profiler -2. Identify bottlenecks - - **If database is bottleneck**: - - Go to Phase 2: Database Optimization - - **If API is bottleneck**: - - Go to Phase 3: API Optimization -``` - -## Testing Your Command - -After creating a command, test it: - -1. **Invoke it**: `/your-command test input` -2. **Verify behavior**: Check that Claude follows the workflow -3. **Test flags**: Try each flag combination -4. **Check output**: Ensure output matches template - -## Next Steps - -- [Create Custom Modes](/claudekit/customization/creating-modes/) — Define behavioral patterns -- [Create Custom Skills](/claudekit/customization/creating-skills/) — Add knowledge modules -- [Configure CLAUDE.md](/claudekit/customization/claude-md/) — Set project standards - -## Examples to Study - -Check these built-in commands for inspiration: - -- `/feature` — Complex multi-phase workflow -- `/fix` — Debugging workflow with error handling -- `/ship` — Git workflow automation -- `/tdd` — Methodology-driven development diff --git a/website/src/content/docs/customization/creating-modes.md b/website/src/content/docs/customization/creating-modes.md deleted file mode 100644 index 99e3a67..0000000 --- a/website/src/content/docs/customization/creating-modes.md +++ /dev/null @@ -1,665 +0,0 @@ ---- -title: Creating Custom Modes -description: Learn how to create custom behavioral modes for different work contexts. ---- - -# Creating Custom Modes - -Modes change how Claude behaves, thinks, and communicates. This guide shows you how to create custom modes for your specific work contexts. - -## What Are Modes? - -Modes are behavioral configurations that adjust: - -- **Communication style** — Verbose vs. concise, formal vs. casual -- **Problem-solving approach** — Exploratory vs. direct, sequential vs. parallel -- **Output format** — Detailed explanations vs. code-only, structured vs. free-form - -Think of modes as "personality presets" for different types of work. - -## Mode File Structure - -Modes are markdown files in `.claude/modes/`: - -``` -.claude/modes/ -├── your-mode.md # /mode your-mode -├── pair-programming.md # /mode pair-programming -└── emergency-debug.md # /mode emergency-debug -``` - -The filename (without `.md`) becomes the mode name. - -## Mode Template - -Here's the complete template for a mode file: - -```markdown -# Mode Name - -## Description - -Brief description of what this mode does and when to use it. - -## When to Use - -- Scenario 1 -- Scenario 2 -- Scenario 3 - ---- - -## Behavior - -### Communication -- How to communicate in this mode -- What tone to use -- Level of verbosity - -### Problem Solving -- How to approach problems -- What to prioritize -- What to avoid - -### Output Format -- What format to use for responses -- How to structure information -- What to include/exclude - ---- - -## Activation - -\`\`\` -Use mode: mode-name -\`\`\` - -Or use command flag: -\`\`\` -/command --mode=mode-name [args] -\`\`\` - ---- - -## Example Behaviors - -### Before [Action] -\`\`\` -Example of behavior in this mode -\`\`\` - -### [Another Scenario] -\`\`\` -Example of different behavior -\`\`\` - ---- - -## Combines Well With - -- Related commands or modes -- Complementary workflows -``` - -## Mode Anatomy - -### 1. Header and Description - -```markdown -# Pair Programming Mode - -## Description - -Interactive development mode that simulates pair programming with -continuous feedback, explanations, and collaborative problem-solving. - -## When to Use - -- Learning new codebase or technology -- Working through complex problems -- When you want to understand the "why" behind decisions -- Teaching or mentoring scenarios -``` - -Define: - -- Mode name (clear and descriptive) -- What it does (2-3 sentences) -- When to activate it - -### 2. Behavior Section - -```markdown -## Behavior - -### Communication -- Explain reasoning behind every decision -- Ask clarifying questions before implementing -- Use "we" language (collaborative tone) -- Provide alternatives when multiple approaches exist - -### Problem Solving -- Think out loud while working -- Break down complex problems step-by-step -- Suggest improvements to existing code -- Point out potential issues before they become problems - -### Output Format -- Show code with inline explanations -- Include "why" comments -- Provide learning opportunities -- Offer refactoring suggestions -``` - -This is the core of the mode — it tells Claude HOW to behave. - -### 3. Activation Instructions - -```markdown -## Activation - -\`\`\` -Use mode: pair-programming -\`\`\` - -Or use command flag: -\`\`\` -/feature --mode=pair-programming "add user auth" -/fix --mode=pair-programming "bug in payment" -\`\`\` -``` - -Show both ways to activate the mode. - -### 4. Example Behaviors - -```markdown -## Example Behaviors - -### Before Writing Code -\`\`\` -Let me explain my approach before we code: - -1. We'll add authentication middleware to the router -2. This will check for a valid JWT token -3. We should also handle token expiration - -Does this approach make sense? Any concerns? -\`\`\` - -### During Implementation -\`\`\`typescript -// Let's add the auth middleware -// We're using JWT because it's stateless and scales well -export const authMiddleware = async (req, res, next) => { - // First, we extract the token from the Authorization header - const token = req.headers.authorization?.split(' ')[1]; - - // We should validate it exists before proceeding - if (!token) { - return res.status(401).json({ error: 'No token provided' }); - } - - // Now let's verify it... - // What error handling do you prefer here? -\`\`\` -\`\`\` -``` - -Provide concrete examples of how the mode changes behavior. - -### 5. Integration Suggestions - -```markdown -## Combines Well With - -- `/feature` command — Collaborative feature development -- `/refactor` command — Understanding refactoring decisions -- `deep-research` mode — When learning requires research -``` - -Suggest complementary commands and modes. - -## Complete Example: Emergency Debug Mode - -Here's a real-world example: - -```markdown -# Emergency Debug Mode - -## Description - -Fast, focused debugging mode for production issues. Prioritizes speed, -minimal output, and getting systems operational over perfect solutions. - -## When to Use - -- Production is down -- Critical bug affecting users -- Time-sensitive issues -- Emergency hotfixes -- When you need to ship a fix NOW - ---- - -## Behavior - -### Communication -- No pleasantries or explanations -- Direct commands and code only -- Skip "why" unless asked -- Use short, imperative sentences - -### Problem Solving -- Jump straight to most likely cause -- Apply quick fixes over perfect solutions -- Defer refactoring to later -- Focus on symptom relief first -- Add TODO comments for proper fixes - -### Output Format -- Code blocks without surrounding prose -- Bullet points over paragraphs -- Commands to run, not explanations -- Immediate actionable steps - -### Speed Over Perfection -- Quick fixes are acceptable -- Technical debt is acceptable -- Tests can be added later -- Documentation can wait -- Focus: Get it working NOW - ---- - -## Activation - -\`\`\` -Use mode: emergency-debug -\`\`\` - -Or use command flag: -\`\`\` -/fix --mode=emergency-debug "production API down" -/deploy --mode=emergency-debug "hotfix-123" -\`\`\` - ---- - -## Example Behaviors - -### Problem Report -**User**: "Production API returning 500 errors" - -**Response**: -\`\`\`bash -# Check logs -tail -f /var/log/api/error.log - -# Common causes: -1. Database connection -2. Memory leak -3. External API timeout - -# Quick check: -curl -v https://api.example.com/health -\`\`\` - -### Immediate Fix -\`\`\`typescript -// Quick fix: Add timeout to prevent hanging -const response = await fetch(url, { - signal: AbortSignal.timeout(5000) // 5s timeout -}); - -// TODO: Investigate why external API is slow -// TODO: Add proper retry logic -// TODO: Add monitoring for this endpoint -\`\`\` - -### Deployment -\`\`\`bash -# Skip tests for emergency deploy -git add . -git commit -m "hotfix: add API timeout" -git push origin hotfix/api-timeout - -# Deploy immediately -./deploy.sh production --skip-tests --force - -# Monitor for errors -watch -n 2 'curl -s https://api.example.com/health' -\`\`\` - ---- - -## Post-Emergency Checklist - -After crisis is resolved, create follow-up tasks: - -\`\`\`markdown -## TODO: Clean up emergency fix - -- [ ] Add tests for timeout handling -- [ ] Investigate root cause of slow API -- [ ] Implement proper retry logic -- [ ] Add monitoring/alerts -- [ ] Document incident -- [ ] Schedule post-mortem -\`\`\` - ---- - -## Combines Well With - -- `/fix` command — Emergency bug fixes -- `/deploy` command — Rapid deployment -- `token-efficient` mode — Fast, minimal output -- `--format=ultra` flag — Code-only responses - ---- - -## When NOT to Use - -- Feature development -- Refactoring work -- Code review -- Learning new patterns -- Non-urgent bugs -``` - -## Best Practices - -### 1. Define Clear Boundaries - -```markdown -## When to Use -- Specific scenario A -- Specific scenario B - -## When NOT to Use -- Different scenario X -- Different scenario Y -``` - -Help users know when to activate the mode. - -### 2. Show Behavior Changes with Examples - -```markdown -## Example Behaviors - -### Standard Mode -\`\`\` -Let me implement the user authentication feature. First, I'll -explain the architecture I'm proposing... -\`\`\` - -### This Mode -\`\`\`typescript -// Auth middleware -export const auth = (req, res, next) => { - const token = req.headers.authorization?.split(' ')[1]; - if (!token) return res.status(401).send(); - // ... -} -\`\`\` -``` - -Contrast with default behavior to show the difference. - -### 3. Be Specific About Communication Style - -```markdown -### Communication -- Use active voice: "Run this command" not "You could run this command" -- No hedging: "This fixes it" not "This should probably fix it" -- Short sentences: Average 10 words -- No adjectives unless critical -``` - -Precise instructions produce consistent behavior. - -### 4. Address Multiple Dimensions - -Cover all three behavioral dimensions: - -```markdown -### Communication -[How to talk] - -### Problem Solving -[How to think] - -### Output Format -[How to structure responses] -``` - -### 5. Provide Output Format Examples - -```markdown -### Output Format - -\`\`\`markdown -## Problem: [Issue] - -### Root Cause -[One sentence] - -### Fix -\`\`\`[code]\`\`\` - -### Test -\`\`\`[command]\`\`\` -\`\`\` -``` - -## Common Mode Patterns - -### Pattern 1: Verbosity Spectrum - -```markdown -# Ultra-Verbose Mode - -### Communication -- Explain every decision in detail -- Provide historical context -- Include multiple examples -- Add learning resources - -# Ultra-Concise Mode - -### Communication -- Code only, no prose -- One-line comments max -- Assume expert knowledge -- Skip obvious steps -``` - -### Pattern 2: Interaction Style - -```markdown -# Interactive Mode - -### Communication -- Ask questions before proceeding -- Validate each step -- Present options for user choice -- Collaborative decision-making - -# Autonomous Mode - -### Communication -- Make decisions independently -- Move through phases without stopping -- Report results at end -- Minimal back-and-forth -``` - -### Pattern 3: Focus Area - -```markdown -# Security-First Mode - -### Problem Solving -- Security is top priority -- Flag any potential vulnerability -- Suggest secure alternatives -- Reference OWASP guidelines - -# Performance-First Mode - -### Problem Solving -- Optimize for speed -- Minimize resource usage -- Benchmark all changes -- Profile before/after -``` - -### Pattern 4: Workflow Style - -```markdown -# Exploratory Mode - -### Problem Solving -- Generate multiple alternatives -- Discuss trade-offs -- Delay final decisions -- Map solution space - -# Execution Mode - -### Problem Solving -- Follow established patterns -- Use proven solutions -- Move quickly to implementation -- Avoid bikeshedding -``` - -## Advanced Mode Features - -### Combining Modes - -Modes can reference other modes: - -```markdown -# Deep Security Audit Mode - -Combines: -- `security-first` mode — Security focus -- `deep-research` mode — Thorough analysis -- `review` mode — Critical perspective - -With modifications: -- Even more thorough than base modes -- Document every finding -- Include remediation steps -``` - -### Conditional Behavior - -```markdown -### Problem Solving - -**If problem is well-defined:** -- Jump straight to solution -- Implement immediately - -**If problem is vague:** -- Ask clarifying questions -- Propose multiple approaches -- Wait for direction -``` - -### Time-Based Behavior - -```markdown -### Communication - -**First message:** -- Explain mode activation -- Set expectations -- Confirm approach - -**Subsequent messages:** -- Follow mode strictly -- Minimal meta-commentary -``` - -## Testing Your Mode - -After creating a mode, test it: - -1. **Activate it**: `/mode your-mode` -2. **Try various commands**: `/feature`, `/fix`, `/review` -3. **Verify behavior changes**: Check communication style, output format -4. **Test edge cases**: Complex problems, simple problems -5. **Compare to default**: Is the difference clear? - -## Common Use Cases - -### Documentation Mode - -```markdown -# Documentation Mode - -## When to Use -- Writing docs -- Explaining code -- Creating tutorials - -### Communication -- Clear, simple language -- Define all terms -- Assume beginner audience -- Include examples for everything -``` - -### Code Review Mode - -```markdown -# Code Review Mode - -## When to Use -- Reviewing PRs -- Security audits -- Quality checks - -### Problem Solving -- Critical analysis -- Look for issues -- Suggest improvements -- Flag anti-patterns -``` - -### Teaching Mode - -```markdown -# Teaching Mode - -## When to Use -- Learning new tech -- Understanding patterns -- Mentoring - -### Communication -- Explain "why" not just "how" -- Provide context -- Use analogies -- Check understanding -``` - -## Next Steps - -- [Create Custom Commands](/claudekit/customization/creating-commands/) — Build workflow automation -- [Create Custom Skills](/claudekit/customization/creating-skills/) — Add knowledge modules -- [Configure CLAUDE.md](/claudekit/customization/claude-md/) — Set project standards - -## Examples to Study - -Check these built-in modes for inspiration: - -- `brainstorm` — Exploratory, question-driven -- `token-efficient` — Minimal output for cost savings -- `deep-research` — Thorough analysis with citations -- `implementation` — Code-focused execution diff --git a/website/src/content/docs/customization/creating-skills.md b/website/src/content/docs/customization/creating-skills.md index b85ae79..39f2c24 100644 --- a/website/src/content/docs/customization/creating-skills.md +++ b/website/src/content/docs/customization/creating-skills.md @@ -1,760 +1,194 @@ --- -title: Creating Custom Skills -description: Learn how to create custom skill modules to extend Claude's knowledge for your tech stack. +title: Creating Skills +description: How to create custom skills for Claude Kit. --- -# Creating Custom Skills +# Creating Skills -Skills are knowledge modules that give Claude expertise in specific technologies, frameworks, methodologies, or your project-specific patterns. This guide shows you how to create custom skills. +Skills are the core building block of Claude Kit. You can create custom skills for your project's specific patterns, frameworks, or workflows. -## What Are Skills? +## Skill Structure -Skills are focused knowledge modules that provide: - -- **Best practices** for languages, frameworks, tools -- **Code patterns** and examples -- **Common pitfalls** to avoid -- **Project-specific conventions** and APIs - -Skills are automatically loaded based on context and can be referenced explicitly in commands. - -## Skill File Structure - -Skills are `SKILL.md` files organized by category: +Each skill is a directory in `.claude/skills/` containing a `SKILL.md` file: ``` .claude/skills/ -├── languages/ -│ ├── python/SKILL.md -│ └── rust/SKILL.md -├── frameworks/ -│ ├── react/SKILL.md -│ └── svelte/SKILL.md -├── databases/ -│ └── mysql/SKILL.md -├── testing/ -│ └── rspec/SKILL.md -├── methodology/ -│ └── your-workflow/SKILL.md -└── custom/ - ├── your-api/SKILL.md - └── internal-tools/SKILL.md +└── my-skill/ + ├── SKILL.md # Skill definition (required) + └── resources/ # Optional bundled references + ├── patterns.md + └── examples.md ``` -## Skill Categories - -Organize skills into these standard categories: - -| Category | What Goes Here | Examples | -|----------|----------------|----------| -| `languages/` | Programming language best practices | python, rust, go | -| `frameworks/` | Web frameworks and libraries | svelte, rails, vue | -| `databases/` | Database-specific patterns | mysql, cassandra | -| `testing/` | Testing frameworks | rspec, mocha | -| `devops/` | Infrastructure and deployment | kubernetes, terraform | -| `frontend/` | Frontend tools and libraries | tailwind, alpine | -| `security/` | Security frameworks | owasp, security-headers | -| `api/` | API design and documentation | graphql, grpc | -| `methodology/` | Development methodologies | your-tdd, your-review-process | -| `custom/` | Project-specific knowledge | internal-api, company-standards | - -## Skill Template - -Here's the complete template for a skill file: +## SKILL.md Format ```markdown -# Skill Name +--- +name: my-skill +description: Use when [trigger conditions]. Activate for keywords like + "keyword1", "keyword2". Also trigger when [specific scenarios]. +--- -## Description - -Brief description of what this skill covers and when it's relevant. +# My Skill ## When to Use +- [Scenario 1] +- [Scenario 2] -- Context 1 where this skill applies -- Context 2 where this skill applies -- Context 3 where this skill applies +## When NOT to Use +- [Anti-scenario 1] --- ## Core Patterns -### Pattern 1 Name +### Pattern 1: [Name] -Description of the pattern. +[Explanation] -\`\`\`[language] -// Code example showing the pattern +\`\`\`typescript +// Code example \`\`\` -**When to use:** -- Scenario A -- Scenario B +### Pattern 2: [Name] -**Avoid:** -- Anti-pattern A -- Anti-pattern B - -### Pattern 2 Name - -Another pattern with examples. +[Explanation] ## Best Practices -1. **Practice Name** - - What to do - - Why it matters - - Example - -2. **Another Practice** - - Details - - Examples +- [Practice 1] +- [Practice 2] ## Common Pitfalls -- **Pitfall 1**: Description - - **Why it's bad**: Explanation - - **Solution**: How to avoid - -- **Pitfall 2**: Description - - **Why it's bad**: Explanation - - **Solution**: How to avoid - ---- +- [Pitfall 1] +- [Pitfall 2] ``` -## Skill Anatomy +## Frontmatter Fields -### 1. Header and Description +| Field | Required | Description | +|-------|----------|-------------| +| `name` | Yes | Skill identifier (kebab-case) | +| `description` | Yes | Trigger description — Claude reads this to decide when to activate | +| `argument-hint` | No | Hint for user-invocable skills (e.g., ``) | +| `user-invocable` | No | If `true`, users can invoke with `/skill-name` | +| `disable-model-invocation` | No | If `true`, only manual invocation works | + +## Writing Effective Descriptions + +The `description` field is critical — it determines when Claude activates your skill. Include: + +1. **Primary trigger**: "Use when [main scenario]" +2. **Keywords**: "Activate for keywords like X, Y, Z" +3. **Secondary triggers**: "Also trigger when [less obvious scenarios]" + +### Good Description + +```yaml +description: Use when implementing JWT tokens, OAuth2 flows, session + management, or role-based access control. Activate for keywords like + "login", "signup", "token refresh", "protected routes". Also trigger + when code handles password hashing or API key authentication. +``` + +### Bad Description + +```yaml +description: Authentication skill for handling auth stuff. +``` + +## Bundled Resources + +For complex skills, include reference documents in a `resources/` subdirectory: + +``` +.claude/skills/my-framework/ +├── SKILL.md +└── resources/ + ├── api-reference.md # Framework API docs + ├── migration-guide.md # Version migration patterns + └── examples.md # Code examples +``` + +Reference them from SKILL.md: ```markdown -# Svelte +See `resources/api-reference.md` for the full API surface. +``` -## Description +## Skill Types -Modern reactive framework for building web applications. Focuses on -compile-time optimization, minimal runtime, and reactive declarations. +### Rigid Skills + +Follow exactly — no adaptation. Used for methodologies where discipline matters: + +- TDD (red-green-refactor cycle) +- Systematic debugging (four-phase investigation) +- Verification before completion + +### Flexible Skills + +Adapt principles to context. Used for patterns that vary by project: + +- Language idioms +- Framework patterns +- Architecture guidelines + +## Example: Custom Deployment Skill + +```markdown +--- +name: deploy-to-fly +description: Use when deploying to Fly.io or configuring Fly.io + services. Activate for keywords like "fly deploy", "fly.toml", + "Fly.io", "fly machines", or any Fly.io-specific configuration. +--- + +# Deploy to Fly.io ## When to Use +- Deploying applications to Fly.io +- Configuring fly.toml +- Setting up Fly.io machines or volumes -- Building modern web applications -- Writing component-based UIs -- When Svelte is in the project's tech stack -``` - -Clear, concise overview of what the skill covers. - -### 2. Core Patterns - -```markdown -## Core Patterns - -### Reactive Declarations - -Svelte automatically tracks dependencies and re-runs reactive statements. - -\`\`\`svelte - - - -\`\`\` - -**When to use:** -- Derived values that depend on reactive state -- Side effects that should run on state changes -- Complex computed values - -**Avoid:** -- Over-using reactive statements for simple transformations -- Creating circular dependencies between reactive declarations -\`\`\` -``` - -Show actual code patterns users will write. - -### 3. Best Practices - -```markdown -## Best Practices - -1. **Keep Components Small** - - Aim for < 200 lines per component - - Extract reusable logic into modules - - Use composition over inheritance - - \`\`\`svelte - - - - - - \`\`\` - -2. **Use Stores for Shared State** - - Don't prop-drill through multiple levels - - Use writable stores for app-wide state - - Use derived stores for computed values - - \`\`\`javascript - // stores.js - import { writable, derived } from 'svelte/store'; - - export const users = writable([]); - export const activeUsers = derived( - users, - $users => $users.filter(u => u.active) - ); - \`\`\` -``` - -Actionable advice with examples. - -### 4. Common Pitfalls - -```markdown -## Common Pitfalls - -- **Mutating Arrays/Objects Directly** - - **Why it's bad**: Svelte can't detect mutations - - **Solution**: Use assignment to trigger reactivity - - \`\`\`javascript - // ❌ Wrong - won't trigger reactivity - items.push(newItem); - - // ✅ Right - triggers reactivity - items = [...items, newItem]; - \`\`\` - -- **Memory Leaks with Subscriptions** - - **Why it's bad**: Unsubscribed stores leak memory - - **Solution**: Use $ auto-subscription or onDestroy - - \`\`\`svelte - - \`\`\` -``` - -Real issues developers face with solutions. - -## Complete Example: Internal API Skill - -Here's a project-specific skill example: - -```markdown -# Internal API Standards - -## Description - -Best practices and conventions for working with our internal REST API. -Covers authentication, error handling, pagination, and response formats. - -## When to Use - -- Making API requests to internal services -- Building new API endpoints -- Reviewing API-related code +## When NOT to Use +- Deploying to other platforms (use devops skill instead) --- -## Core Patterns +## Deployment Checklist -### Authentication +1. Verify `fly.toml` exists and is configured +2. Check environment secrets are set: `fly secrets list` +3. Deploy: `fly deploy --strategy rolling` +4. Verify: `fly status` and `fly logs` -All API requests require JWT authentication. +## Common Patterns -\`\`\`typescript -import { apiClient } from '@/lib/api'; +### Multi-region deployment -// Client automatically includes auth token -const response = await apiClient.get('/users'); +\`\`\`toml +[env] + PRIMARY_REGION = "iad" -// Manual auth header (if needed) -const response = await fetch('/api/users', { - headers: { - 'Authorization': `Bearer ${getAuthToken()}`, - 'Content-Type': 'application/json' - } -}); -\`\`\` - -**Required headers:** -- `Authorization: Bearer {token}` -- `Content-Type: application/json` - -### Error Handling - -API returns structured errors following this format: - -\`\`\`typescript -interface APIError { - error: { - code: string; // Machine-readable error code - message: string; // Human-readable message - details?: object; // Additional context - field?: string; // Field that caused error (validation) - } -} - -// Example error response -{ - "error": { - "code": "VALIDATION_ERROR", - "message": "Email is required", - "field": "email" - } -} -\`\`\` - -**Handle errors consistently:** - -\`\`\`typescript -try { - const user = await apiClient.post('/users', data); -} catch (error) { - if (error.code === 'VALIDATION_ERROR') { - // Show field error - setFieldError(error.field, error.message); - } else { - // Show generic error - showNotification(error.message, 'error'); - } -} -\`\`\` - -### Pagination - -List endpoints support cursor-based pagination. - -\`\`\`typescript -interface PaginatedResponse { - data: T[]; - pagination: { - next_cursor: string | null; - has_more: boolean; - } -} - -// First page -const response = await apiClient.get('/users?limit=20'); - -// Next page -const response = await apiClient.get( - `/users?limit=20&cursor=${response.pagination.next_cursor}` -); -\`\`\` - -**Pagination parameters:** -- `limit`: Number of items (max: 100, default: 20) -- `cursor`: Cursor from previous response - -### Filtering and Sorting - -Use query parameters for filtering and sorting. - -\`\`\`typescript -// Filter by status -GET /users?status=active - -// Sort by field -GET /users?sort=created_at&order=desc - -// Multiple filters -GET /users?status=active&role=admin&sort=name - -// Search -GET /users?q=search+term -\`\`\` - -**Standard query parameters:** -- `status`: Filter by status field -- `q`: Full-text search -- `sort`: Field to sort by -- `order`: Sort direction (`asc` or `desc`) - ---- - -## Best Practices - -1. **Use the API Client** - - Don't make raw fetch calls - - API client handles auth, retries, errors - - Provides TypeScript types - - \`\`\`typescript - // ✅ Good - import { apiClient } from '@/lib/api'; - const users = await apiClient.get('/users'); - - // ❌ Avoid - const response = await fetch('/api/users'); - const users = await response.json(); - \`\`\` - -2. **Handle Loading States** - - Show loading indicators for async operations - - Handle errors gracefully - - Provide feedback on success - - \`\`\`typescript - const [loading, setLoading] = useState(false); - const [error, setError] = useState(null); - - async function loadUsers() { - setLoading(true); - setError(null); - try { - const users = await apiClient.get('/users'); - setUsers(users.data); - } catch (err) { - setError(err.message); - } finally { - setLoading(false); - } - } - \`\`\` - -3. **Validate Before Sending** - - Validate data client-side before API call - - Reduces unnecessary API requests - - Provides immediate feedback - - \`\`\`typescript - async function createUser(data) { - // Client-side validation - if (!data.email || !data.name) { - throw new Error('Email and name are required'); - } - - if (!isValidEmail(data.email)) { - throw new Error('Invalid email format'); - } - - // API call only if validation passes - return apiClient.post('/users', data); - } - \`\`\` - -4. **Use TypeScript Types** - - Import types from `@/types/api` - - Type your API responses - - Catch type errors at compile time - - \`\`\`typescript - import type { User, PaginatedResponse } from '@/types/api'; - - const response = await apiClient.get>('/users'); - // response.data is typed as User[] - \`\`\` - ---- - -## Common Pitfalls - -- **Not Handling 401 Responses** - - **Why it's bad**: Users get stuck with expired tokens - - **Solution**: API client auto-redirects to login on 401 - - \`\`\`typescript - // API client handles this automatically - // No manual 401 handling needed - \`\`\` - -- **Forgetting to Paginate** - - **Why it's bad**: Large responses slow down the app - - **Solution**: Always use pagination for list endpoints - - \`\`\`typescript - // ❌ Wrong - loads all users - const users = await apiClient.get('/users'); - - // ✅ Right - loads 20 users with pagination - const response = await apiClient.get('/users?limit=20'); - \`\`\` - -- **Hardcoding API URLs** - - **Why it's bad**: Breaks when environment changes - - **Solution**: Use environment-specific config - - \`\`\`typescript - // ❌ Wrong - fetch('https://api.example.com/users'); - - // ✅ Right - uses env-specific base URL - apiClient.get('/users'); - \`\`\` - -- **Not Handling Rate Limits** - - **Why it's bad**: Can hit rate limits on bulk operations - - **Solution**: API client includes retry with exponential backoff - - \`\`\`typescript - // API client handles 429 automatically - // Retries with exponential backoff - const users = await apiClient.get('/users'); - \`\`\` - ---- - -## Error Codes Reference - -| Code | Meaning | Action | -|------|---------|--------| -| `VALIDATION_ERROR` | Invalid input | Show field error | -| `NOT_FOUND` | Resource doesn't exist | Show 404 message | -| `UNAUTHORIZED` | Not authenticated | Redirect to login | -| `FORBIDDEN` | Insufficient permissions | Show permission error | -| `RATE_LIMITED` | Too many requests | Retry after delay | -| `SERVER_ERROR` | Internal error | Show generic error | - ---- - -## Quick Reference - -### Making Requests - -\`\`\`typescript -// GET -const users = await apiClient.get('/users'); - -// POST -const user = await apiClient.post('/users', { name: 'John' }); - -// PUT -const user = await apiClient.put('/users/123', { name: 'Jane' }); - -// PATCH -const user = await apiClient.patch('/users/123', { status: 'active' }); - -// DELETE -await apiClient.delete('/users/123'); -\`\`\` - -### With Query Parameters - -\`\`\`typescript -const users = await apiClient.get('/users', { - params: { - status: 'active', - limit: 20, - sort: 'name' - } -}); -\`\`\` - -### With Custom Headers - -\`\`\`typescript -const data = await apiClient.get('/export', { - headers: { - 'Accept': 'text/csv' - } -}); +[[services]] + internal_port = 8080 + protocol = "tcp" + auto_stop_machines = true + auto_start_machines = true + min_machines_running = 1 \`\`\` ``` -## Best Practices for Writing Skills +## Tips -### 1. Keep Skills Focused +- **Start small**: Begin with the core patterns, add detail as you learn what Claude needs +- **Be specific**: Vague skills produce vague results. Include exact code patterns. +- **Test the trigger**: After creating a skill, test that it activates on the right keywords +- **Update regularly**: Skills should evolve with your codebase -Each skill should cover ONE topic thoroughly: +## Related Pages -```markdown -# Good: Focused skills -- languages/python/SKILL.md -- testing/pytest/SKILL.md -- security/owasp/SKILL.md - -# Bad: Too broad -- everything-python/SKILL.md -``` - -### 2. Use Real Code Examples - -```markdown -# Good: Real, runnable code -\`\`\`python -@pytest.fixture -def user(): - return User(id=1, name="Test") - -def test_user_creation(user): - assert user.id == 1 -\`\`\` - -# Bad: Pseudo-code -\`\`\` -create a fixture -use the fixture in a test -\`\`\` -``` - -### 3. Show What NOT to Do - -```markdown -## Common Pitfalls - -- **Using == for null checks** - \`\`\`python - # ❌ Wrong - if value == None: - - # ✅ Right - if value is None: - \`\`\` -``` - -### 4. Link to Official Documentation - -```markdown -## Further Reading - -- [Official Svelte Tutorial](https://svelte.dev/tutorial) -- [Svelte API Reference](https://svelte.dev/docs) -- [Svelte Society Recipes](https://sveltesociety.dev/recipes) -``` - -### 5. Keep It Scannable - -Use clear headings, bullet points, and code blocks: - -```markdown -## Best Practices - -1. **Clear Heading** - - Bullet point - - Another point - -2. **Another Practice** - \`\`\`code - example - \`\`\` -``` - -## Skill Size Guidelines - -| Skill Complexity | Lines | Sections | -|------------------|-------|----------| -| Simple | 50-100 | 2-3 core patterns | -| Standard | 100-200 | 3-5 patterns + pitfalls | -| Comprehensive | 200-400 | 5+ patterns + examples | - -Aim for **100-200 lines** for most skills. - -## Testing Your Skill - -After creating a skill, test it: - -1. **Reference it**: Mention the technology in a command -2. **Verify knowledge**: Check that Claude applies the patterns -3. **Test edge cases**: See if pitfalls are avoided -4. **Check examples**: Ensure code examples are used - -## Common Skill Types - -### Language Skills - -Focus on syntax, idioms, and best practices: - -```markdown -# Go - -## Core Patterns - -### Error Handling -### Goroutines and Channels -### Interfaces -### Defer, Panic, Recover - -## Best Practices -## Common Pitfalls -``` - -### Framework Skills - -Focus on framework-specific patterns: - -```markdown -# Rails - -## Core Patterns - -### Models and ActiveRecord -### Controllers and RESTful Routes -### Views and Partials -### Background Jobs - -## Best Practices -## Common Pitfalls -``` - -### Methodology Skills - -Focus on processes and workflows: - -```markdown -# Code Review Process - -## Description -Our team's code review standards and checklist. - -## Core Patterns - -### Review Checklist -### Giving Feedback -### Receiving Feedback - -## Best Practices -``` - -## Organizing Custom Skills - -For project-specific knowledge, use `custom/`: - -``` -.claude/skills/custom/ -├── api-standards/SKILL.md # Your API conventions -├── deployment/SKILL.md # Deployment procedures -├── testing-standards/SKILL.md # Testing requirements -└── security-checklist/SKILL.md # Security review items -``` - -## Next Steps - -- [Create Custom Commands](/claudekit/customization/creating-commands/) — Build workflow automation -- [Create Custom Modes](/claudekit/customization/creating-modes/) — Define behavioral patterns -- [Configure CLAUDE.md](/claudekit/customization/claude-md/) — Set project standards - -## Examples to Study - -Check these built-in skills for inspiration: - -- `languages/python/SKILL.md` — Language best practices -- `testing/pytest/SKILL.md` — Testing framework patterns -- `methodology/test-driven-development/SKILL.md` — Development process -- `security/owasp/SKILL.md` — Security guidelines +- [Skills Reference](/claudekit/reference/skills/) — All 43 built-in skills +- [Creating Agents & Modes](/claudekit/customization/creating-agents-and-modes/) — Custom agents and modes diff --git a/website/src/content/docs/customization/overview.md b/website/src/content/docs/customization/overview.md deleted file mode 100644 index 4d20a30..0000000 --- a/website/src/content/docs/customization/overview.md +++ /dev/null @@ -1,236 +0,0 @@ ---- -title: Customization Overview -description: Learn how to customize Claude Kit with your own commands, modes, skills, and project settings. ---- - -# Customization Overview - -Claude Kit is designed to be fully customizable. You can create your own commands, modes, and skills, and configure Claude's behavior for your specific project needs. - -## What Can You Customize? - -### 1. Commands - -Create custom slash commands for your team's specific workflows: - -```bash -/deploy-staging # Your deployment workflow -/audit-deps # Custom dependency audit -/release-notes # Generate release notes your way -``` - -[Learn how to create commands →](/claudekit/customization/creating-commands/) - -### 2. Modes - -Define behavioral modes for different work contexts: - -```bash -/mode pair-programming # Your pair programming style -/mode documentation # Documentation-focused mode -/mode production-debug # Emergency debugging mode -``` - -[Learn how to create modes →](/claudekit/customization/creating-modes/) - -### 3. Skills - -Add knowledge modules for your tech stack: - -```bash -.claude/skills/ -├── languages/rust/ # Rust best practices -├── frameworks/svelte/ # Svelte patterns -└── custom/your-api/ # Your internal API docs -``` - -[Learn how to create skills →](/claudekit/customization/creating-skills/) - -### 4. CLAUDE.md Configuration - -Configure project-specific behavior, conventions, and agent overrides: - -- Tech stack and architecture -- Code conventions -- Testing standards -- Security requirements -- Agent behavior overrides - -[CLAUDE.md reference →](/claudekit/customization/claude-md/) - -## Customization Levels - -Claude Kit supports three levels of customization: - -| Level | What to Change | When to Use | -|-------|----------------|-------------| -| **Configuration** | Edit `CLAUDE.md` | Set project conventions, tech stack, standards | -| **Composition** | Add modes and skills | Extend behavior without coding | -| **Extension** | Create commands | Build custom workflows | - -## Quick Start Examples - -### Example 1: Add a Custom Command - -Create `.claude/commands/deploy.md`: - -```markdown -# /deploy - Deploy Application - -## Usage -/deploy [environment] - ---- - -Deploy to **$ARGUMENTS** environment: - -1. Run tests -2. Build production bundle -3. Deploy to environment -4. Verify deployment -``` - -[Full command creation guide →](/claudekit/customization/creating-commands/) - -### Example 2: Configure for Your Stack - -Edit `.claude/CLAUDE.md`: - -```markdown -## Tech Stack - -- **Backend**: Ruby on Rails -- **Frontend**: Vue.js -- **Database**: MySQL -- **Testing**: RSpec, Cypress -``` - -[Full CLAUDE.md guide →](/claudekit/customization/claude-md/) - -### Example 3: Add a Custom Skill - -Create `.claude/skills/custom/internal-api/SKILL.md`: - -```markdown -# Internal API Standards - -## Authentication -All endpoints require JWT bearer tokens... - -## Error Handling -Use standard error format... -``` - -[Full skill creation guide →](/claudekit/customization/creating-skills/) - -## File Structure - -Claude Kit customizations live in your `.claude` folder: - -``` -.claude/ -├── CLAUDE.md # Main configuration -├── commands/ # Custom commands -│ ├── deploy.md -│ └── your-command.md -├── modes/ # Custom modes -│ ├── your-mode.md -│ └── another-mode.md -└── skills/ # Custom skills - ├── custom/ - │ └── your-skill/ - │ └── SKILL.md - └── overrides/ - └── language/ - └── SKILL.md -``` - -## Best Practices - -### Start Small - -Don't try to customize everything at once: - -1. **First**: Configure `CLAUDE.md` for your project -2. **Then**: Add a mode or two for your common workflows -3. **Finally**: Create custom commands for repeated tasks - -### Document Your Customizations - -Add comments to your custom files explaining: - -- Why the customization exists -- When to use it -- What it does differently - -### Share Customizations - -Custom commands and modes are project-specific, so they should be: - -- Committed to version control -- Documented in your project README -- Shared with your team - -### Keep Skills Focused - -Each skill should: - -- Cover one specific topic -- Be 50-200 lines -- Include practical examples -- Reference official docs - -## Common Customization Patterns - -### Pattern 1: Strict TDD Workflow - -Add to `CLAUDE.md`: - -```markdown -## Tester Agent -- **TDD Required**: Always write tests first -- **Coverage Minimum**: 90% -- **Test Type**: Integration tests for all endpoints -``` - -### Pattern 2: Security-First Reviews - -Create `.claude/modes/security-audit.md`: - -```markdown -# Security Audit Mode - -Focus exclusively on security issues: -- Authentication/authorization -- Input validation -- XSS/CSRF protection -- Secrets management -``` - -### Pattern 3: Custom Git Workflow - -Create `.claude/commands/finish-feature.md`: - -```markdown -# /finish-feature - Complete Feature - -1. Squash commits -2. Update changelog -3. Create PR with template -4. Assign reviewers -``` - -## Next Steps - -Choose what to customize: - -- [Create Custom Commands](/claudekit/customization/creating-commands/) — Build workflow automation -- [Create Custom Modes](/claudekit/customization/creating-modes/) — Define behavioral patterns -- [Create Custom Skills](/claudekit/customization/creating-skills/) — Add knowledge modules -- [Configure CLAUDE.md](/claudekit/customization/claude-md/) — Set project standards - -## Getting Help - -- Check the [example commands](https://github.com/yourusername/claudekit/tree/main/.claude/commands) in the repo -- Look at [built-in modes](https://github.com/yourusername/claudekit/tree/main/.claude/modes) for patterns -- Review [existing skills](https://github.com/yourusername/claudekit/tree/main/.claude/skills) for structure diff --git a/website/src/content/docs/getting-started/configuration.md b/website/src/content/docs/getting-started/configuration.md index 45969b1..ff1d27f 100644 --- a/website/src/content/docs/getting-started/configuration.md +++ b/website/src/content/docs/getting-started/configuration.md @@ -5,50 +5,18 @@ description: How to customize Claude Kit for your project. # Configuration -Claude Kit is highly customizable. This guide covers all configuration options. +Claude Kit works out of the box, but customizing it for your project makes it significantly more effective. ## CLAUDE.md -The main configuration file is `.claude/CLAUDE.md`. This file defines: - -- Project context and architecture -- Code conventions -- Tech stack details -- Custom instructions - -### Basic Structure - -```markdown -# Project Name - -## Overview -Brief description of your project. - -## Tech Stack -- **Languages**: Python, TypeScript -- **Backend**: FastAPI -- **Frontend**: Next.js -- **Database**: PostgreSQL - -## Architecture -Describe your project structure. - -## Code Conventions -Define naming conventions, style guides, etc. - -## Custom Instructions -Any project-specific rules for Claude. -``` +The main configuration file is `.claude/CLAUDE.md`. This tells Claude about your project so skills can provide relevant guidance. ### Key Sections #### Tech Stack -Tell Claude what technologies you're using: - ```markdown ## Tech Stack - - **Languages**: Python 3.11, TypeScript 5.0 - **Backend Framework**: FastAPI with SQLAlchemy - **Frontend Framework**: Next.js 14 with App Router @@ -59,8 +27,6 @@ Tell Claude what technologies you're using: #### Code Conventions -Define your project's coding standards: - ```markdown ## Code Conventions @@ -71,16 +37,10 @@ Define your project's coding standards: | Functions | `snake_case` | `camelCase` | | Classes | `PascalCase` | `PascalCase` | | Constants | `UPPER_SNAKE` | `UPPER_SNAKE` | - -### Style -- Python: Follow PEP 8, use type hints -- TypeScript: Strict mode, no `any` types ``` #### Security Standards -Define security requirements: - ```markdown ## Security Standards @@ -96,106 +56,7 @@ Define security requirements: - Secrets via environment variables only ``` -## Environment-Specific Config - -### Development - -```markdown -## Development Environment - -\`\`\`bash -# Python -python -m venv venv -source venv/bin/activate -pip install -r requirements.txt - -# Node.js -pnpm install -pnpm dev -\`\`\` -``` - -### Testing - -```markdown -## Testing - -\`\`\`bash -# Python -pytest -v --cov=src - -# Node.js -pnpm test -pnpm test:coverage -\`\`\` - -### Coverage Requirements -- Minimum: 80% -- Critical paths: 95% -``` - -## Agent Behavior Overrides - -Customize how specific agents behave: - -```markdown -## Agent Behavior Overrides - -### Planner Agent -- Break tasks into 15-60 minute chunks -- Always identify testing requirements -- Flag external dependencies - -### Code-Reviewer Agent -- Enforce strict typing -- Security-first reviews -- Check for test coverage - -### Tester Agent -- Use pytest for Python, vitest for TypeScript -- Generate edge case tests -- Include error scenario tests -``` - -## Mode Configuration - -Set default modes for different situations: - -```markdown -## Behavioral Modes - -### Default Mode -Use `implementation` mode for coding tasks. - -### Review Mode Settings -- Depth: 4 (thorough) -- Personas: security, performance - -### Planning Mode Settings -- Task size: 15-60 minutes -- Include testing requirements -``` - -## Command Flags Defaults - -Set default flags for commands: - -```markdown -## Command Defaults - -### /feature -- Default mode: implementation -- Include tests: yes -- Include review: yes - -### /review -- Default persona: security -- Default depth: 3 -``` - -## Git Configuration - -Configure Git-related behavior: +#### Git Conventions ```markdown ## Git Conventions @@ -207,18 +68,86 @@ Configure Git-related behavior: ### Commit Messages Format: `type(scope): subject` - Types: feat, fix, docs, style, refactor, test, chore - -### PR Requirements -- Descriptive title and description -- Linked to issue -- All tests passing ``` -## Example Complete Configuration +## settings.json -Here's a complete CLAUDE.md example: +The `.claude/settings.json` file controls Claude Code permissions and hooks: + +```json +{ + "permissions": { + "allow": [ + "git status", "git diff", "git log", + "npm test", "npm run lint", + "pytest", "ruff check" + ] + } +} +``` + +### Auto-Linting Hooks + +Claude Kit includes PostToolUse hooks that auto-lint files after edits: + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [ + { + "type": "command", + "command": "ruff check --fix $FILE", + "match_files": "*.py" + } + ] + } + ] + } +} +``` + +## Agent Behavior Overrides + +Customize how specialized agents behave in your CLAUDE.md: + +```markdown +## Agent Behavior Overrides + +### Planner Agent +- Break tasks into 15-60 minute chunks +- Always identify testing requirements + +### Code-Reviewer Agent +- Enforce strict typing +- Security-first reviews +- Check for test coverage + +### Tester Agent +- Use pytest for Python, vitest for TypeScript +- Generate edge case tests +``` + +## Modes + +Set default modes or customize their behavior. Mode files live in `.claude/modes/`: + +| Mode | Best For | +|------|----------| +| `default` | General tasks | +| `brainstorm` | Design, ideation | +| `implementation` | Code-focused, minimal prose | +| `review` | Critical analysis | +| `token-efficient` | High-volume work, cost savings | +| `deep-research` | Investigation, audits | +| `orchestration` | Multi-agent coordination | + +Switch modes naturally: "switch to brainstorm mode" or "use implementation mode". + +## Example Complete Configuration ```markdown # My SaaS Project @@ -233,19 +162,16 @@ A B2B SaaS platform for project management. - **Payments**: Stripe ## Architecture -\`\`\` src/ ├── api/ # FastAPI routes ├── services/ # Business logic ├── models/ # SQLAlchemy models ├── frontend/ # Next.js app └── tests/ # Test files -\`\`\` ## Code Conventions - Python: PEP 8, type hints required - TypeScript: Strict mode, Zod for validation -- Files: snake_case for Python, kebab-case for TS ## Security - All inputs validated with Pydantic/Zod @@ -255,16 +181,14 @@ src/ ## Testing - Python: pytest with 80% coverage minimum - Frontend: vitest + Playwright -- Run: `pnpm test` or `pytest` ## Git - Branches: feature/*, fix/*, hotfix/* - Commits: conventional commits format -- PRs require review before merge ``` ## Next Steps -- [Commands Overview](/claudekit/commands/overview/) — Learn available commands -- [Creating Commands](/claudekit/customization/creating-commands/) — Make your own commands -- [Creating Modes](/claudekit/customization/creating-modes/) — Make custom modes +- [Workflows](/claudekit/workflows/planning-and-building/) — See how skills work together +- [Skills Reference](/claudekit/reference/skills/) — Browse all 43 skills +- [Creating Skills](/claudekit/customization/creating-skills/) — Build your own diff --git a/website/src/content/docs/getting-started/installation.md b/website/src/content/docs/getting-started/installation.md index ca7a2e5..7355ad5 100644 --- a/website/src/content/docs/getting-started/installation.md +++ b/website/src/content/docs/getting-started/installation.md @@ -14,8 +14,6 @@ Claude Kit installs in under 2 minutes. Choose your preferred method below. ## Method 1: Clone and Copy (Recommended) -The simplest way to get started: - ```bash # Clone Claude Kit git clone https://github.com/duthaho/claudekit.git @@ -32,16 +30,14 @@ claude ## Method 2: Download ZIP -If you prefer not to use Git: - 1. Go to [github.com/duthaho/claudekit](https://github.com/duthaho/claudekit) -2. Click **Code** → **Download ZIP** +2. Click **Code** > **Download ZIP** 3. Extract the ZIP file 4. Copy the `.claude` folder to your project root -## Method 3: Git Submodule (For Version Control) +## Method 3: Git Submodule -If you want to track Claude Kit updates: +Track Claude Kit updates via Git: ```bash # Add as submodule @@ -63,18 +59,12 @@ git submodule update --remote .claudekit ## Verify Installation -After installation, verify everything is working: - ```bash -# Start Claude Code in your project cd your-project claude - -# Try a simple command -> /help ``` -You should see the Claude Kit help output listing available commands. +Skills trigger automatically based on your conversation. Try asking Claude to brainstorm a feature or debug an error — the relevant skills will activate. ## Folder Structure @@ -84,26 +74,27 @@ After installation, your project should have: your-project/ ├── .claude/ │ ├── CLAUDE.md # Project instructions -│ ├── commands/ # Slash commands -│ │ ├── feature.md -│ │ ├── fix.md +│ ├── agents/ # 20 specialized subagents +│ │ ├── code-reviewer.md +│ │ ├── debugger.md │ │ └── ... -│ ├── modes/ # Behavioral modes +│ ├── modes/ # 7 behavioral modes │ │ ├── brainstorm.md │ │ ├── implementation.md │ │ └── ... -│ ├── skills/ # Knowledge modules +│ ├── skills/ # 43 knowledge modules +│ │ ├── brainstorming/ +│ │ ├── testing/ │ │ ├── languages/ -│ │ ├── frameworks/ -│ │ ├── methodology/ │ │ └── ... +│ ├── mcp/ # MCP server configs │ └── settings.json # Claude Code settings └── ... (your project files) ``` ## Troubleshooting -### Commands not recognized +### Skills not triggering Make sure the `.claude` folder is in your project root (same level as `package.json` or `pyproject.toml`). @@ -127,7 +118,5 @@ claude ## Next Steps -Now that Claude Kit is installed: - -1. [Quick Start](/claudekit/getting-started/quick-start/) — Run your first command -2. [Configuration](/claudekit/getting-started/configuration/) — Customize for your project +1. [Configuration](/claudekit/getting-started/configuration/) — Customize for your project +2. [Workflows](/claudekit/workflows/planning-and-building/) — See how skills work together diff --git a/website/src/content/docs/getting-started/introduction.md b/website/src/content/docs/getting-started/introduction.md index 8e85fe5..60c5c67 100644 --- a/website/src/content/docs/getting-started/introduction.md +++ b/website/src/content/docs/getting-started/introduction.md @@ -1,94 +1,65 @@ --- title: Introduction -description: Learn what Claude Kit is and how it can accelerate your development workflow. +description: Learn what Claude Kit is and how it accelerates your development workflow. --- # Introduction to Claude Kit -Claude Kit is an open-source toolkit that transforms Claude Code into a production-ready AI development team. It provides pre-built commands, intelligent modes, and battle-tested skills that accelerate your development workflow. +Claude Kit is an open-source toolkit that transforms Claude Code into a production-ready AI development team. It provides auto-triggered skills, specialized agents, and intelligent modes that accelerate your development workflow. ## What is Claude Kit? -Claude Kit is a collection of: +Claude Kit is a `.claude` folder you add to your project containing: -- **27+ Commands** — Slash commands like `/feature`, `/fix`, `/review` that automate development workflows -- **7 Modes** — Behavioral configurations that optimize Claude for specific tasks (brainstorming, implementation, review, etc.) -- **34+ Skills** — Pre-built knowledge modules for languages, frameworks, testing, security, and development methodologies +- **43 Skills** — Knowledge modules that auto-trigger based on what you're doing (debugging, planning, testing, etc.) +- **20 Agents** — Specialized subagents for focused tasks (code review, security audit, database design, etc.) +- **7 Modes** — Behavioral configurations that optimize Claude for specific task types -All of this lives in a `.claude` folder that you add to your project, giving Claude Code the context and structure it needs to be truly productive. +Skills activate automatically based on keywords in your conversation. No commands to memorize — just describe what you want to do. ## Why Claude Kit? ### The Problem with Raw Claude Code -While Claude Code is powerful, using it without structure leads to common issues: - | Problem | Symptom | |---------|---------| | **Context Spirals** | Token budgets run out, Claude loses track of what it was doing | | **Inconsistent Output** | Quality varies wildly between sessions | -| **Manual Workflows** | You copy the same prompts between projects | | **No Structure** | Every session starts from scratch | +| **Missing Expertise** | Claude doesn't know your team's patterns and standards | ### How Claude Kit Helps -Claude Kit solves these problems with: +1. **Auto-Triggered Skills** — Say "fix this bug" and systematic-debugging activates. Say "plan this" and brainstorming kicks in. +2. **Specialized Agents** — Dispatch focused subagents for code review, testing, security audits, and more. +3. **Consistent Quality** — Built-in TDD enforcement, verification before completion, and code review workflows. +4. **Full Customization** — Add your own skills, agents, and modes. -1. **Structured Workflows** — Commands like `/feature` orchestrate multi-phase development automatically -2. **Context Control** — Modes and skills give Claude exactly the context it needs -3. **Consistent Quality** — Built-in code review, testing standards, and security checks -4. **Full Customization** — Add your own commands, modes, and skills +## How Skills Work -## Key Features +Skills are the core of Claude Kit. They trigger automatically based on keywords: -### Commands +``` +You: "I need to add user authentication to our app" + ↓ triggers: brainstorming, authentication, backend-frameworks -Commands automate common development tasks: +You: "There's a TypeError in the UserService" + ↓ triggers: systematic-debugging, root-cause-tracing -```bash -/feature "add user authentication" # Full feature workflow -/fix "TypeError in UserService" # Smart debugging -/review src/auth/ # Code review -/ship "feat: add auth" # Git commit + PR +You: "Let's write tests for the API endpoints" + ↓ triggers: testing, test-driven-development ``` -### Modes - -Modes change Claude's behavior for different task types: - -```bash -/mode brainstorm # Creative exploration, more questions -/mode implementation # Code-focused, minimal prose -/mode review # Critical analysis, finds issues -``` - -### Skills - -Skills provide pre-built knowledge for: - -- **Languages**: Python, TypeScript, JavaScript -- **Frameworks**: React, Next.js, FastAPI, Django -- **Testing**: pytest, vitest, Playwright -- **Methodologies**: TDD, systematic debugging, code review +No slash commands needed — Claude reads your intent and activates the right skills. ## Who is Claude Kit For? -Claude Kit is designed for: - - **Solo developers** who want to ship faster - **Small teams (1-3 developers)** working on multi-stack projects - **Anyone using Claude Code** who wants more structure and consistency ## Next Steps -Ready to get started? - 1. [Install Claude Kit](/claudekit/getting-started/installation/) — Add it to your project -2. [Quick Start](/claudekit/getting-started/quick-start/) — Your first command in 2 minutes -3. [Configuration](/claudekit/getting-started/configuration/) — Customize for your project - -Or dive into the features: - -- [Commands Reference](/claudekit/commands/overview/) — All 27+ commands -- [Modes Reference](/claudekit/modes/overview/) — All 7 behavioral modes -- [Skills Reference](/claudekit/skills/overview/) — All 34+ skill modules +2. [Configuration](/claudekit/getting-started/configuration/) — Customize for your project +3. [Skills Reference](/claudekit/reference/skills/) — Browse all 43 skills diff --git a/website/src/content/docs/getting-started/quick-start.md b/website/src/content/docs/getting-started/quick-start.md deleted file mode 100644 index f73aaca..0000000 --- a/website/src/content/docs/getting-started/quick-start.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -title: Quick Start -description: Get up and running with Claude Kit in 2 minutes. ---- - -# Quick Start - -This guide will have you using Claude Kit in under 2 minutes. - -## Step 1: Start Claude Code - -Open your terminal in a project with Claude Kit installed: - -```bash -cd your-project -claude -``` - -## Step 2: Try Your First Command - -Let's use the `/help` command to see what's available: - -```bash -> /help -``` - -This shows all available commands organized by category. - -## Step 3: Plan a Feature - -Try the `/plan` command to break down a task: - -```bash -> /plan "add a user profile page" -``` - -Claude will: -1. Analyze the requirement -2. Break it into actionable tasks -3. Create a structured implementation plan - -## Step 4: Implement with `/feature` - -Ready to build something? Use the full feature workflow: - -```bash -> /feature "add password reset with email verification" -``` - -This orchestrates: -1. **Planning** — Requirements analysis and task breakdown -2. **Implementation** — Code generation with best practices -3. **Testing** — Unit and integration tests -4. **Review** — Self-review checklist - -## Step 5: Switch Modes - -Change how Claude behaves with modes: - -```bash -> /mode brainstorm -``` - -Now Claude will: -- Ask more clarifying questions -- Present multiple alternatives -- Explore trade-offs before converging - -Other useful modes: - -```bash -> /mode implementation # Code-focused, minimal prose -> /mode token-efficient # Compressed output, saves tokens -> /mode review # Critical analysis mode -``` - -## Common Workflows - -### Bug Fixing - -```bash -> /fix "TypeError: Cannot read property 'email' of undefined in UserService.ts:45" -``` - -Claude will analyze the error, find the root cause, implement a fix, and add a regression test. - -### Code Review - -```bash -> /review src/auth/ -``` - -Get a comprehensive review covering: -- Code quality -- Security vulnerabilities -- Performance issues -- Maintainability - -### Ship Changes - -```bash -> /ship "feat: add user authentication" -``` - -Creates a git commit with proper message formatting and optionally opens a PR. - -### Research - -```bash -> /research "best practices for JWT authentication in Node.js" -``` - -Claude researches the topic and provides a comprehensive summary with recommendations. - -## Tips for Getting Started - -### 1. Start with Planning - -Before writing code, use `/plan` or `/brainstorm` to think through the approach: - -```bash -> /brainstorm "how should we handle file uploads?" -``` - -### 2. Use the Right Mode - -Match the mode to your task: - -| Task | Mode | -|------|------| -| Exploring options | `brainstorm` | -| Writing code | `implementation` | -| Reviewing code | `review` | -| Researching | `deep-research` | -| High-volume work | `token-efficient` | - -### 3. Leverage Flags - -Commands support flags for customization: - -```bash -> /feature --skip-tests "add logging utility" -> /review --persona=security src/auth/ -> /plan --depth=5 "implement payment flow" -``` - -### 4. Check Command Help - -Get details on any command: - -```bash -> /help feature -> /help fix -``` - -## Next Steps - -You're ready to use Claude Kit! Here's where to go next: - -- [Configuration](/claudekit/getting-started/configuration/) — Customize Claude Kit for your project -- [Commands Overview](/claudekit/commands/overview/) — See all 27+ commands -- [Modes Overview](/claudekit/modes/overview/) — Learn about all 7 modes -- [Customization](/claudekit/customization/overview/) — Create your own commands diff --git a/website/src/content/docs/index.mdx b/website/src/content/docs/index.mdx index 5b42ee9..057782f 100644 --- a/website/src/content/docs/index.mdx +++ b/website/src/content/docs/index.mdx @@ -1,9 +1,9 @@ --- title: Claude Kit -description: The open-source AI dev toolkit for Claude Code. Ship faster with 27+ commands, 7 modes, and 34+ skills. Free forever. +description: The open-source AI dev toolkit for Claude Code. 43 skills, 20 agents, 7 modes — structure that makes Claude Code production-ready. Free forever. template: splash hero: - tagline: The open-source AI dev toolkit for Claude Code. Ship faster with 27+ commands, 7 modes, and 34+ skills. Free forever. + tagline: The open-source AI dev toolkit for Claude Code. 43 skills, 20 agents, 7 modes — structure that makes Claude Code production-ready. Free forever. image: dark: ../../assets/hero-dark.svg light: ../../assets/hero-light.svg @@ -22,20 +22,20 @@ import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components'; ## Ship Faster. For Free. -Claude Kit transforms Claude Code into a production-ready AI development team. Pre-built commands, intelligent modes, and battle-tested skills — all open source. +Claude Kit transforms Claude Code into a production-ready AI development team. Pre-built skills, specialized agents, and intelligent modes — all open source. - - From `/feature` to `/ship`, automate your entire development workflow with battle-tested commands. + + Auto-triggered knowledge for Python, TypeScript, React, FastAPI, TDD, debugging, security, and more. Claude knows your stack without being told. + + + Specialized subagents for code review, testing, database design, security auditing, UI/UX, and more — each with focused expertise. - Switch between brainstorm, implementation, review, and more. Each mode optimizes Claude's behavior for your task. + Switch between brainstorm, implementation, review, deep research, and more. Each mode optimizes Claude's behavior for your task. - - Pre-built knowledge for Python, TypeScript, React, FastAPI, testing, security, and more. - - - Real-time docs, persistent memory, browser testing, and more via Model Context Protocol. + + Real-time docs via Context7, persistent memory, browser testing, and structured reasoning via Model Context Protocol. @@ -52,12 +52,13 @@ git clone https://github.com/duthaho/claudekit.git # Copy the kit to your project cp -r claudekit/.claude your-project/ -# Start using commands +# Start using it cd your-project claude -> /feature "add user authentication" ``` +Skills trigger automatically based on what you're doing. Ask Claude to brainstorm a feature, write a plan, debug an error, or review code — the right skills activate without any commands needed. + --- ## Why Claude Kit? @@ -68,71 +69,70 @@ Working with Claude Code is powerful, but raw Claude has limitations: - **Context Spirals** — Token budgets run out, context gets lost mid-task - **Inconsistent Output** — Quality varies between sessions -- **Manual Workflows** — Same prompts copied between projects - **No Structure** — Every session starts from scratch +- **Missing Expertise** — Claude doesn't know your team's patterns and standards ### The Solution Claude Kit provides the structure, patterns, and automation that makes Claude Code production-ready: - - Commands like `/feature` orchestrate multi-phase development: planning → implementation → testing → review → ship. + + Say "fix this bug" and the systematic-debugging skill activates. Say "plan this feature" and brainstorming + writing-plans kick in. No commands to memorize. - - Modes and skills give Claude the exact context it needs. No more explaining your stack every session. + + Delegate code review, security audits, testing, and documentation to focused subagents that work in parallel. - Built-in code review, testing standards, and security checks ensure every output meets your standards. + Built-in TDD enforcement, verification before completion, and code review workflows ensure every output meets your standards. - Add your own commands, modes, and skills. Claude Kit is a template, not a black box. + Add your own skills, agents, and modes. Claude Kit is a template, not a black box. --- -## Featured Commands +## How It Works + +Claude Kit uses three layers that work together: -[View all commands →](/claudekit/commands/overview/) - --- -## Modes for Every Task +## Development Workflows -| Mode | Best For | Description | -|------|----------|-------------| -| **Default** | General tasks | Balanced behavior | -| **Brainstorm** | Design, ideation | Explores alternatives, asks questions | -| **Token-Efficient** | High-volume work | Compressed output, 30-70% savings | -| **Implementation** | Coding | Jump straight to code | -| **Review** | Quality checks | Critical analysis, finds issues | -| **Deep Research** | Investigation | Thorough analysis with citations | +Claude Kit connects skills and agents into complete workflows: -[Learn about modes →](/claudekit/modes/overview/) +| Workflow | What Happens | +|----------|-------------| +| **Planning & Building** | Brainstorm requirements, write implementation plans, execute with subagents | +| **Testing & Debugging** | TDD enforcement, systematic debugging, root cause tracing, verification | +| **Reviewing & Shipping** | Code review, git workflows, PR creation, changelog generation | + +[Explore workflows →](/claudekit/workflows/planning-and-building/) --- @@ -145,18 +145,18 @@ Claude Kit provides the structure, patterns, and automation that makes Claude Co href="/claudekit/getting-started/installation/" /> diff --git a/website/src/content/docs/mcp/context7.md b/website/src/content/docs/mcp/context7.md deleted file mode 100644 index d8ae96e..0000000 --- a/website/src/content/docs/mcp/context7.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Context7 -description: Real-time library documentation lookup with Context7 MCP server. ---- - -# Context7 - -Context7 provides up-to-date documentation for libraries and frameworks, ensuring Claude has accurate API references instead of outdated training data. - -## Configuration - -```json -{ - "mcpServers": { - "context7": { - "command": "npx", - "args": ["-y", "@upstash/context7-mcp"] - } - } -} -``` - -## Available Tools - -### resolve-library-id - -Finds the Context7-compatible library ID for documentation lookup. - -**Parameters:** -- `libraryName` — Library name to search for - -**Example:** -``` -resolve-library-id("react") -→ Returns: "/facebook/react" -``` - -### get-library-docs - -Fetches documentation for a specific library. - -**Parameters:** -- `context7CompatibleLibraryID` — Library ID from resolve-library-id -- `topic` (optional) — Focus area (e.g., "hooks", "routing") -- `mode` — `code` for API references, `info` for concepts -- `page` — Pagination (1-10) - -**Example:** -``` -get-library-docs("/facebook/react", topic="hooks", mode="code") -→ Returns: Current React hooks documentation with examples -``` - -## Use Cases - -### Research Libraries - -``` -/research Next.js App Router -``` -Context7 fetches current Next.js documentation for accurate analysis. - -### Feature Development - -``` -/feature Add authentication with NextAuth -``` -Context7 provides current NextAuth API for correct implementation. - -### Debugging Library Issues - -``` -/fix "useEffect cleanup not working" -``` -Context7 retrieves correct useEffect patterns from React docs. - -## Command Integration - -| Command | How Context7 Helps | -|---------|-------------------| -| `/feature` | Accurate library APIs for implementation | -| `/research` | Current documentation for analysis | -| `/fix` | Correct patterns for debugging library issues | -| `/plan` | Accurate estimates based on real API complexity | - -## Best Practices - -### Specify Topics - -For focused results, use the `topic` parameter: -``` -get-library-docs("/vercel/next.js", topic="app-router") -``` - -### Use Correct Mode - -- `mode="code"` — API references, code examples -- `mode="info"` — Conceptual guides, architecture - -### Handle Pagination - -If context is insufficient, try additional pages: -``` -get-library-docs(..., page=2) -``` - -## Troubleshooting - -### Library Not Found - -If `resolve-library-id` returns no results: -- Check spelling -- Try alternative names (e.g., "nextjs" vs "next.js") -- Some libraries may not be indexed - -### Outdated Results - -Context7 indexes popular libraries. Less common libraries may have delayed updates. - -## Resources - -- [Context7 Documentation](https://context7.com) -- [Upstash Context7 MCP](https://github.com/upstash/context7-mcp) diff --git a/website/src/content/docs/mcp/filesystem.md b/website/src/content/docs/mcp/filesystem.md deleted file mode 100644 index 5e2faab..0000000 --- a/website/src/content/docs/mcp/filesystem.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -title: Filesystem -description: Secure file operations with access controls. ---- - -# Filesystem - -Filesystem MCP enables secure file operations with configurable access boundaries. It complements Claude Code's built-in file handling with additional capabilities. - -## Configuration - -```json -{ - "mcpServers": { - "filesystem": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] - } - } -} -``` - -The last argument (`.`) specifies the allowed directory. Claude can only access files within this directory. - -### Access Control Examples - -```json -// Allow entire project -"args": ["-y", "@modelcontextprotocol/server-filesystem", "."] - -// Allow only src directory -"args": ["-y", "@modelcontextprotocol/server-filesystem", "./src"] - -// Allow multiple directories -"args": ["-y", "@modelcontextprotocol/server-filesystem", "./src", "./tests"] -``` - -## Available Tools - -### Reading - -| Tool | Description | -|------|-------------| -| `read_file` | Read file contents | -| `read_multiple_files` | Read multiple files at once | -| `get_file_info` | Get file metadata (size, modified, etc.) | - -### Writing - -| Tool | Description | -|------|-------------| -| `write_file` | Write content to file | -| `edit_file` | Make targeted edits to file | - -### Directory Operations - -| Tool | Description | -|------|-------------| -| `list_directory` | List directory contents | -| `directory_tree` | Get full directory tree | -| `create_directory` | Create new directory | - -### File Management - -| Tool | Description | -|------|-------------| -| `move_file` | Move or rename files | -| `search_files` | Search for files by pattern | - -## Use Cases - -### Project Indexing - -``` -/index -``` -Filesystem: -1. Uses `directory_tree` to scan project -2. Uses `list_directory` for detailed info -3. Uses `get_file_info` for file metadata - -### Bulk Operations - -``` -/refactor Move utilities to shared folder -``` -Filesystem: -1. Uses `search_files` to find utility files -2. Uses `move_file` to relocate them -3. Uses `read_file` to update imports - -### Test File Management - -``` -/test Generate tests for auth service -``` -Filesystem: -1. Uses `directory_tree` to find test directories -2. Uses `search_files` to find existing tests -3. Uses `write_file` to create new test files - -## Command Integration - -| Command | How Filesystem Helps | -|---------|---------------------| -| `/index` | Scans project structure | -| `/feature` | Creates new files in correct locations | -| `/test` | Manages test file creation | -| `/refactor` | Moves and reorganizes files | - -## Example Workflow - -### Scanning Project - -```javascript -// Get project structure -directory_tree(".") -→ Returns hierarchical view of all files - -// Get specific directory contents -list_directory("./src/services") -→ Returns files with metadata - -// Search for patterns -search_files("*.test.ts") -→ Returns all test files -``` - -### File Operations - -```javascript -// Read file -read_file("./src/auth/service.ts") -→ Returns file contents - -// Write new file -write_file("./src/auth/types.ts", "export interface User {...}") -→ Creates new file - -// Move file -move_file("./src/utils/helper.ts", "./src/shared/helper.ts") -→ Relocates file -``` - -## Security - -### Access Boundaries - -Filesystem respects the configured directory boundaries: -- Cannot read files outside allowed directories -- Cannot write to system directories -- Cannot access parent directories with `../` - -### Best Practices - -1. **Limit scope** — Only allow directories needed for the task -2. **Use project root** — `.` is usually sufficient -3. **Avoid sensitive paths** — Don't allow access to credentials or secrets - -## Comparison with Built-in Tools - -| Feature | Built-in | Filesystem MCP | -|---------|----------|----------------| -| Read files | ✓ | ✓ | -| Write files | ✓ | ✓ | -| Directory tree | Limited | Full tree view | -| File search | Via Glob | Pattern search | -| Bulk operations | Sequential | Batch capable | -| Access control | Permission-based | Directory-based | - -## Troubleshooting - -### Permission Denied - -If operations fail: -1. Check allowed directory in configuration -2. Verify file permissions -3. Ensure path is within allowed scope - -### File Not Found - -If search returns empty: -1. Verify file exists -2. Check file extension in pattern -3. Confirm path is relative to allowed directory - -### Path Issues - -Always use forward slashes and relative paths: -- "./src/file.ts" not ".\src\file.ts" -- Avoid absolute paths - -## Resources - -- [MCP Filesystem Server](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem) -- [File System Security Best Practices](https://owasp.org/www-community/vulnerabilities/Path_Traversal) diff --git a/website/src/content/docs/mcp/integration.md b/website/src/content/docs/mcp/integration.md deleted file mode 100644 index c5a8b9e..0000000 --- a/website/src/content/docs/mcp/integration.md +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: Command Integration -description: How MCP servers enhance Claude Kit commands and modes. ---- - -# Command Integration - -MCP servers are automatically used by Claude Kit commands and modes. This guide shows which servers enhance each command and how they work together. - -## Commands + MCP Servers - -### Development Commands - -| Command | MCP Servers | Enhancement | -|---------|-------------|-------------| -| `/feature` | Context7, Sequential, Memory, Filesystem, Playwright | Full development workflow with docs, planning, persistence | -| `/fix` | Sequential, Memory, Playwright, Context7, Filesystem | Systematic debugging with browser testing | -| `/test` | Playwright, Filesystem, Context7, Memory | E2E tests, file management, testing patterns | -| `/review` | Playwright, Memory, Sequential, Filesystem | Visual review, consistent standards | - -### Planning Commands - -| Command | MCP Servers | Enhancement | -|---------|-------------|-------------| -| `/plan` | Sequential, Memory, Context7, Filesystem | Structured breakdown, persistent decisions | -| `/brainstorm` | Sequential, Memory, Context7 | Organized exploration, design persistence | -| `/research` | Context7, Sequential, Memory | Real-time docs, thorough analysis | - -### Utility Commands - -| Command | MCP Servers | Enhancement | -|---------|-------------|-------------| -| `/index` | Filesystem, Memory | Project scanning, structure persistence | - -## Modes + MCP Servers - -| Mode | Primary MCP | Best For | -|------|-------------|----------| -| **brainstorm** | Sequential + Memory | Design sessions with persistent ideas | -| **deep-research** | Sequential + Context7 | Thorough technical investigation | -| **implementation** | Filesystem + Context7 | Focused coding with accurate docs | -| **review** | Playwright + Memory | UI review with consistent standards | -| **orchestration** | All 5 | Complex multi-step parallel work | - -## Example Workflows - -### Full Feature Development - -```bash -/feature Add user profile with avatar upload -``` - -**MCP Flow:** -1. **Context7** — Fetches React file upload documentation -2. **Sequential** — Plans component structure step-by-step -3. **Memory** — Recalls UI patterns from previous features -4. **Filesystem** — Creates files in correct locations -5. **Playwright** — Tests upload flow in browser - -### Complex Debugging - -```bash -/fix Authentication fails intermittently on mobile -``` - -**MCP Flow:** -1. **Memory** — Recalls auth architecture from previous sessions -2. **Sequential** — Analyzes race conditions systematically -3. **Playwright** — Tests on mobile device emulation -4. **Context7** — Checks session handling best practices - -### Research & Planning - -```bash -/research --mode=deep-research JWT vs Session authentication -``` - -**MCP Flow:** -1. **Sequential** — Structures comparison step-by-step -2. **Context7** — Fetches current JWT and session library docs -3. **Memory** — Stores findings for future reference - -### Project Indexing - -```bash -/index -``` - -**MCP Flow:** -1. **Filesystem** — Scans project with `directory_tree` -2. **Memory** — Stores structure as knowledge graph - -## Server Synergy - -### Context7 + Memory - -**Pattern:** Research → Store → Recall - -``` -Session 1: /research React Server Components -→ Context7 fetches RSC documentation -→ Memory stores key patterns - -Session 2: /feature Add data fetching -→ Memory recalls RSC patterns -→ Implementation uses correct approach -``` - -### Sequential + Memory - -**Pattern:** Analyze → Decide → Remember - -``` -/brainstorm Database migration strategy -→ Sequential explores options step-by-step -→ Memory stores final decision -→ Future sessions recall the decision -``` - -### Playwright + Context7 - -**Pattern:** Test → Verify → Document - -``` -/test E2E checkout flow -→ Playwright automates browser testing -→ Context7 provides testing library docs -→ Tests use correct assertions -``` - -### Filesystem + Memory - -**Pattern:** Scan → Store → Navigate - -``` -/index -→ Filesystem scans project structure -→ Memory creates project knowledge graph -→ Future commands know where files are -``` - -## Configuration Tips - -### Platform Note - -Configuration differs by platform: -- **Linux/macOS**: Use `"command": "npx"` directly -- **Windows**: Use `"command": "cmd"` with `"/c", "npx"` in args - -Examples below show Linux/macOS syntax. For Windows, see [MCP Overview](/claudekit/mcp/overview/). - -### Minimal Setup - -For basic usage, Context7 and Sequential are most impactful: - -```json -{ - "mcpServers": { - "context7": { - "command": "npx", - "args": ["-y", "@upstash/context7-mcp"] - }, - "sequential": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"] - } - } -} -``` - -### Full Setup - -For complete Claude Kit integration, use all 5 servers: - -```json -{ - "mcpServers": { - "context7": { - "command": "npx", - "args": ["-y", "@upstash/context7-mcp"] - }, - "sequential": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"] - }, - "playwright": { - "command": "npx", - "args": ["-y", "@playwright/mcp"] - }, - "memory": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-memory"] - }, - "filesystem": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] - } - } -} -``` - -## Performance Notes - -### First Run - -First run downloads npm packages (one-time). Subsequent starts are faster. - -### Startup Order - -Servers start in parallel. All should be ready within seconds. - -### Resource Usage - -Each server runs as a separate process. Total overhead is minimal but consider disabling unused servers for resource-constrained environments. - -## Next Steps - -- [MCP Overview](/claudekit/mcp/overview/) — Setup and configuration -- [Commands Overview](/claudekit/commands/overview/) — All available commands -- [Modes Overview](/claudekit/modes/overview/) — Behavioral modes diff --git a/website/src/content/docs/mcp/memory.md b/website/src/content/docs/mcp/memory.md deleted file mode 100644 index c406806..0000000 --- a/website/src/content/docs/mcp/memory.md +++ /dev/null @@ -1,197 +0,0 @@ ---- -title: Memory -description: Persistent knowledge graph for context across sessions. ---- - -# Memory - -Memory MCP maintains a persistent knowledge graph across sessions, enabling Claude to remember decisions, patterns, and preferences over time. - -## Configuration - -```json -{ - "mcpServers": { - "memory": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-memory"] - } - } -} -``` - -## Core Concepts - -### Entities - -Named items in the knowledge graph (e.g., "AuthService", "UserModel"). - -### Observations - -Facts about entities (e.g., "uses JWT tokens", "requires database"). - -### Relations - -Connections between entities (e.g., "AuthService" → "uses" → "UserRepository"). - -## Available Tools - -### Entity Management - -| Tool | Description | -|------|-------------| -| `create_entities` | Create new entities | -| `delete_entities` | Remove entities | -| `open_nodes` | Open specific entities by name | -| `search_nodes` | Search for entities | - -### Observations - -| Tool | Description | -|------|-------------| -| `add_observations` | Add facts to entities | -| `delete_observations` | Remove observations | - -### Relations - -| Tool | Description | -|------|-------------| -| `create_relations` | Link entities together | -| `delete_relations` | Remove links | - -### Graph Operations - -| Tool | Description | -|------|-------------| -| `read_graph` | Read entire knowledge graph | - -## Use Cases - -### Project Architecture - -``` -/index -``` -Memory stores: -- Entity: "src/api" — "Contains REST endpoints" -- Entity: "src/services" — "Business logic layer" -- Relation: "api" → "depends on" → "services" - -### Design Decisions - -``` -/brainstorm Authentication strategy -``` -Memory stores: -- Entity: "AuthDecision" -- Observation: "Chose JWT over sessions for scalability" -- Observation: "User prefers stateless auth" - -### Bug Patterns - -``` -/fix Race condition in checkout -``` -Memory stores: -- Entity: "CheckoutBug" -- Observation: "Caused by async state update" -- Observation: "Fixed with mutex lock" - -## Command Integration - -| Command | How Memory Helps | -|---------|-----------------| -| `/brainstorm` | Remembers design decisions | -| `/plan` | Recalls previous task patterns | -| `/fix` | Stores bug patterns for future reference | -| `/index` | Persists project structure | - -## Example Workflow - -### Storing Design Decisions - -**Session 1:** -``` -/brainstorm Authentication for mobile app -→ Decision: Use OAuth with refresh tokens -→ Memory stores this decision -``` - -**Session 2:** -``` -/feature Add logout functionality -→ Memory recalls: "Uses OAuth with refresh tokens" -→ Claude knows to invalidate refresh token -``` - -### Building Project Knowledge - -**Over time:** -``` -create_entities(["AuthService", "UserRepository", "TokenManager"]) - -add_observations("AuthService", [ - "Handles OAuth flow", - "Uses refresh tokens", - "Integrates with Google/GitHub" -]) - -create_relations([ - {"from": "AuthService", "to": "TokenManager", "type": "uses"}, - {"from": "AuthService", "to": "UserRepository", "type": "queries"} -]) -``` - -**Later query:** -``` -search_nodes("auth") -→ Returns full context about authentication architecture -``` - -## Best Practices - -### Use Descriptive Names - -Entity names should be clear and consistent: -- "AuthService" not "AS" -- "PaymentFlow" not "pmt" - -### Add Context to Observations - -Include why, not just what: -- "Uses JWT because stateless scales better" -- "Chose Postgres for ACID compliance" - -### Create Meaningful Relations - -Relations should express real dependencies: -- "depends on", "uses", "calls", "creates" - -### Review Regularly - -Use `read_graph` periodically to review stored knowledge and prune outdated information. - -## Data Persistence - -Memory data is stored locally and persists between sessions. The knowledge graph grows over time as you work with Claude Kit. - -## Troubleshooting - -### Graph Getting Large - -If the graph becomes unwieldy: -1. Use `search_nodes` to find specific entities -2. Delete outdated entities with `delete_entities` -3. Remove stale observations - -### Missing Context - -If Claude doesn't recall something: -- Check if entity exists with `search_nodes` -- Observations may not have been stored -- Entity names may differ - -## Resources - -- [MCP Memory Server](https://github.com/modelcontextprotocol/servers/tree/main/src/memory) -- [Knowledge Graph Concepts](https://en.wikipedia.org/wiki/Knowledge_graph) diff --git a/website/src/content/docs/mcp/overview.md b/website/src/content/docs/mcp/overview.md deleted file mode 100644 index 67f0380..0000000 --- a/website/src/content/docs/mcp/overview.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: MCP Integrations -description: Extend Claude Kit with Model Context Protocol servers for enhanced capabilities. ---- - -# MCP Integrations - -Model Context Protocol (MCP) servers extend Claude Kit with powerful capabilities like real-time documentation, persistent memory, and browser automation. - -## What is MCP? - -MCP (Model Context Protocol) is an open standard that allows AI assistants to connect with external tools and data sources. Claude Kit includes pre-configured MCP servers that enhance your development workflow. - -## Available Servers - -| Server | Package | Purpose | -|--------|---------|---------| -| **Context7** | `@upstash/context7-mcp` | Real-time library documentation | -| **Sequential** | `@modelcontextprotocol/server-sequential-thinking` | Structured problem-solving | -| **Playwright** | `@playwright/mcp` | Browser automation | -| **Memory** | `@modelcontextprotocol/server-memory` | Persistent knowledge graph | -| **Filesystem** | `@modelcontextprotocol/server-filesystem` | Secure file operations | - -## Quick Setup - -### 1. Create Configuration - -Create a `.mcp.json` file in your project root. Choose your platform: - -#### Linux / macOS - -```json -{ - "mcpServers": { - "context7": { - "command": "npx", - "args": ["-y", "@upstash/context7-mcp"] - }, - "sequential": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"] - }, - "playwright": { - "command": "npx", - "args": ["-y", "@playwright/mcp"] - }, - "memory": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-memory"] - }, - "filesystem": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] - } - } -} -``` - -#### Windows - -Windows requires the `cmd /c` wrapper: - -```json -{ - "mcpServers": { - "context7": { - "command": "cmd", - "args": ["/c", "npx", "-y", "@upstash/context7-mcp"] - }, - "sequential": { - "command": "cmd", - "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-sequential-thinking"] - }, - "playwright": { - "command": "cmd", - "args": ["/c", "npx", "-y", "@playwright/mcp"] - }, - "memory": { - "command": "cmd", - "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-memory"] - }, - "filesystem": { - "command": "cmd", - "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "."] - } - } -} -``` - -### 2. Prerequisites - -- Node.js 18+ -- npx available in PATH - -### 3. Verify Installation - -Start a new Claude Code session. MCP servers will load automatically. Test with: - -``` -Ask Claude about React hooks using Context7 -``` - -## Benefits - -### Real-Time Documentation -Context7 fetches current library documentation, eliminating outdated API references from training data. - -### Structured Reasoning -Sequential Thinking enables step-by-step analysis with confidence tracking for complex debugging and planning. - -### Browser Testing -Playwright provides cross-browser automation for E2E testing without separate test infrastructure. - -### Persistent Context -Memory server maintains knowledge across sessions, remembering your patterns and preferences. - -### Safe File Operations -Filesystem server provides controlled file access with security boundaries. - -## How It Works - -MCP servers are **automatically used** when configured. Claude Kit commands and modes include explicit guidance for optimal MCP usage. - -For example, when you run `/research react hooks`: -1. Context7 fetches current React documentation -2. Sequential Thinking structures the analysis -3. Memory stores findings for future reference - -## Next Steps - -- [Context7](/claudekit/mcp/context7/) — Library documentation lookup -- [Sequential Thinking](/claudekit/mcp/sequential/) — Structured reasoning -- [Playwright](/claudekit/mcp/playwright/) — Browser automation -- [Memory](/claudekit/mcp/memory/) — Persistent knowledge -- [Filesystem](/claudekit/mcp/filesystem/) — File operations -- [Command Integration](/claudekit/mcp/integration/) — How MCP enhances commands diff --git a/website/src/content/docs/mcp/playwright.md b/website/src/content/docs/mcp/playwright.md deleted file mode 100644 index 63682cf..0000000 --- a/website/src/content/docs/mcp/playwright.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Playwright -description: Browser automation for testing and web interaction. ---- - -# Playwright - -Playwright MCP provides browser automation using accessibility tree for fast, LLM-friendly interaction. Built by Microsoft, it enables cross-browser testing without vision models. - -## Configuration - -```json -{ - "mcpServers": { - "playwright": { - "command": "npx", - "args": ["-y", "@playwright/mcp"] - } - } -} -``` - -### Command-Line Options - -| Option | Description | Example | -|--------|-------------|---------| -| `--browser` | Browser to use | `chrome`, `firefox`, `webkit`, `msedge` | -| `--headless` | Run without UI | Flag only | -| `--viewport-size` | Window size | `1280x720` | -| `--device` | Device emulation | `iPhone 15`, `Pixel 7` | - -**Example with options:** -```json -{ - "playwright": { - "command": "npx", - "args": ["-y", "@playwright/mcp", "--browser", "chrome", "--headless"] - } -} -``` - -## Available Tools - -### Navigation - -| Tool | Description | -|------|-------------| -| `browser_navigate` | Go to a URL | -| `browser_go_back` | Navigate back | -| `browser_go_forward` | Navigate forward | -| `browser_wait` | Wait for page load | - -### Interaction - -| Tool | Description | -|------|-------------| -| `browser_click` | Click element | -| `browser_type` | Type text | -| `browser_fill` | Fill input field | -| `browser_select_option` | Select dropdown option | -| `browser_press_key` | Press keyboard key | - -### Content - -| Tool | Description | -|------|-------------| -| `browser_snapshot` | Get accessibility tree | -| `browser_take_screenshot` | Capture screenshot | -| `browser_get_text` | Get element text | - -### Tabs - -| Tool | Description | -|------|-------------| -| `browser_tab_list` | List open tabs | -| `browser_tab_new` | Open new tab | -| `browser_tab_select` | Switch to tab | -| `browser_tab_close` | Close tab | - -## Use Cases - -### E2E Testing - -``` -/test e2e Login flow should redirect to dashboard -``` -Playwright: -1. Navigates to login page -2. Fills credentials -3. Clicks submit -4. Verifies dashboard redirect - -### UI Review - -``` -/review Visual regression on mobile -``` -Playwright: -1. Opens page with device emulation -2. Takes screenshots -3. Compares with expected layout - -### Form Testing - -``` -/test Form validation for user registration -``` -Playwright: -1. Fills form with various inputs -2. Tests validation messages -3. Verifies submission behavior - -## Command Integration - -| Command | How Playwright Helps | -|---------|---------------------| -| `/test` | E2E browser tests | -| `/fix` | Reproduce UI bugs in browser | -| `/review` | Visual verification of changes | -| `/feature` | Test new UI features | - -## Example Workflow - -### Testing Login Flow - -```javascript -// Playwright MCP workflow -browser_navigate("https://app.example.com/login") -browser_fill("#email", "test@example.com") -browser_fill("#password", "password123") -browser_click("#login-button") -browser_wait() // Wait for navigation -browser_take_screenshot("after-login.png") -``` - -### Mobile Testing - -```javascript -// With device emulation (--device "iPhone 15") -browser_navigate("https://app.example.com") -browser_snapshot() // Get accessibility tree -browser_take_screenshot("mobile-view.png") -``` - -## Key Features - -### Accessibility Tree - -Playwright uses the accessibility tree instead of pixels: -- **Faster** — No image processing needed -- **LLM-friendly** — Structured element data -- **Cross-browser** — Works identically everywhere - -### Device Emulation - -Test on different devices without physical hardware: -- iPhone, iPad, Pixel, Galaxy -- Custom viewport sizes -- Touch vs mouse input - -### Profile Management - -Playwright can maintain browser state across sessions for authenticated testing. - -## Best Practices - -### Use Headless Mode - -For automated testing, use `--headless` to run without UI overhead. - -### Wait for Elements - -Always use `browser_wait` or wait for specific elements before interaction. - -### Accessibility First - -Use accessibility tree (`browser_snapshot`) to understand page structure before clicking. - -## Troubleshooting - -### Element Not Found - -If clicking fails: -1. Use `browser_snapshot` to see available elements -2. Check if element needs scrolling -3. Wait for dynamic content to load - -### Browser Not Starting - -- Ensure browser is installed -- Check Node.js version (18+) -- Try different browser with `--browser` - -## Resources - -- [Playwright MCP](https://github.com/microsoft/playwright-mcp) -- [Playwright Documentation](https://playwright.dev) -- [Device Descriptors](https://playwright.dev/docs/emulation#devices) diff --git a/website/src/content/docs/mcp/sequential.md b/website/src/content/docs/mcp/sequential.md deleted file mode 100644 index b1920ba..0000000 --- a/website/src/content/docs/mcp/sequential.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Sequential Thinking -description: Structured problem-solving with step-by-step reasoning. ---- - -# Sequential Thinking - -Sequential Thinking provides structured reasoning tools for complex problem-solving, enabling step-by-step analysis with confidence tracking and revision capabilities. - -## Configuration - -```json -{ - "mcpServers": { - "sequential": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"] - } - } -} -``` - -## Available Tools - -### sequentialthinking - -Dynamic problem-solving through structured thought sequences. - -**Parameters:** - -| Parameter | Description | -|-----------|-------------| -| `thought` | Current thinking step | -| `thoughtNumber` | Current step number (1, 2, 3...) | -| `totalThoughts` | Estimated total steps needed | -| `nextThoughtNeeded` | Whether more steps are needed | -| `isRevision` | If this revises previous thinking | -| `revisesThought` | Which thought is being reconsidered | -| `branchFromThought` | Branching point for alternative paths | -| `needsMoreThoughts` | If more analysis is needed | - -## Use Cases - -### Complex Debugging - -``` -/fix Intermittent authentication failures -``` -Sequential Thinking: -1. Defines the question clearly -2. Gathers evidence systematically -3. Forms hypotheses with probabilities -4. Tests most likely cause first -5. Documents conclusion with confidence - -### Architecture Decisions - -``` -/brainstorm Database migration strategy -``` -Sequential Thinking: -1. Explores options step-by-step -2. Tracks trade-offs for each approach -3. Revises conclusions based on feedback -4. Builds confidence incrementally - -### Root Cause Analysis - -``` -/research Why is the build slow? -``` -Sequential Thinking: -1. Breaks problem into investigation steps -2. Documents evidence at each step -3. Adjusts hypothesis as facts emerge -4. Provides confidence-scored conclusion - -## Command Integration - -| Command | How Sequential Thinking Helps | -|---------|------------------------------| -| `/fix` | Systematic root cause analysis | -| `/plan` | Structured task decomposition | -| `/brainstorm` | Organized design exploration | -| `/research` | Step-by-step investigation | - -## Mode Integration - -| Mode | Integration | -|------|-------------| -| `deep-research` | Primary tool for thorough analysis | -| `brainstorm` | Structures creative exploration | -| `review` | Systematic code examination | - -## Example Workflow - -### Debugging Session - -**Thought 1:** Define the problem -``` -"What is causing authentication to fail intermittently for some users?" -→ Confidence: N/A (question definition) -``` - -**Thought 2:** Gather evidence -``` -"Checking logs shows failures occur during peak hours, -primarily for users with special characters in passwords." -→ Confidence: 7/10 -``` - -**Thought 3:** Form hypothesis -``` -"Hypothesis A: URL encoding issue with special characters. -Evidence: Failure pattern matches special char passwords. -Probability: 80%" -→ Confidence: 8/10 -``` - -**Thought 4:** Test hypothesis -``` -"Tested with password 'test@123' - fails. -Tested with 'test123' - works. -Hypothesis confirmed." -→ Confidence: 9/10 -``` - -**Thought 5:** Conclusion -``` -"Root cause: URL encoding mangles special characters. -Fix: Use base64 encoding instead. -Confidence: 9/10" -→ nextThoughtNeeded: false -``` - -## Best Practices - -### Start with Clear Questions - -Define what you're investigating before gathering evidence. - -### Track Confidence - -Explicitly state confidence levels to identify when more investigation is needed. - -### Allow Revisions - -Use `isRevision` and `revisesThought` to refine understanding as new information emerges. - -### Branch When Needed - -Use `branchFromThought` to explore alternative hypotheses without losing the main thread. - -## Resources - -- [MCP Sequential Thinking](https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking) -- [Sequential Thinking Skill](/claudekit/skills/methodology/sequential-thinking/) diff --git a/website/src/content/docs/modes/brainstorm.md b/website/src/content/docs/modes/brainstorm.md deleted file mode 100644 index e705b5c..0000000 --- a/website/src/content/docs/modes/brainstorm.md +++ /dev/null @@ -1,498 +0,0 @@ ---- -title: Brainstorm Mode -description: Creative exploration mode for design and ideation ---- - -# Brainstorm Mode - -## Overview - -Brainstorm mode optimizes for creative exploration, divergent thinking, and design discussions. It emphasizes asking questions, presenting alternatives, and thoroughly exploring possibilities before committing to solutions. - -Use this mode when the path forward isn't clear and you need to explore the problem space. - -## When to Use - -Brainstorm mode is ideal for: - -- **Initial feature exploration** - Understanding requirements and possibilities -- **Architecture decisions** - Evaluating different structural approaches -- **Problem definition** - Clarifying what you're actually trying to solve -- **Design sessions** - Creating mockups, APIs, data models -- **When stuck** - Getting unstuck by exploring new angles - -## Behavior Changes - -### Communication Style - -**Question-first approach:** -- Ask clarifying questions before concluding -- Present multiple alternatives with trade-offs -- Explore edge cases verbally -- Use "what if" scenarios to probe possibilities - -**Example:** -``` -Before we implement authentication, I have some questions to help -us choose the best approach: - -1. User base: Are you expecting 100 users or 100,000? -2. Auth methods: Just email/password, or OAuth (Google, GitHub)? -3. Sessions: Stateful server sessions or stateless JWT? -4. MFA: Is two-factor authentication needed now or later? -5. Password reset: Email-based reset flow needed? - -Based on your answers, I can recommend the most suitable approach. -``` - -### Problem-Solving Approach - -- **Divergent thinking first** - Generate many options before narrowing -- **Delay convergence** - Don't jump to solutions immediately -- **Question assumptions** - Challenge requirements to find better solutions -- **Map trade-offs explicitly** - Show pros/cons of each option - -### Output Format - -- Structured comparisons and decision matrices -- Pro/con lists for alternatives -- Visual diagrams (ASCII art, Mermaid) -- Open questions sections -- Recommendation with reasoning - -## Examples - -### Feature Design - -**Request:** -```bash -/brainstorm "notification system" -``` - -**Brainstorm Mode Response:** -```markdown -Let me explore different approaches for a notification system. - -## Clarifying Questions - -Before we design this, I need to understand: - -1. **Delivery channels**: Email only, or also push/SMS/in-app? -2. **Volume**: How many notifications per day/user? -3. **Real-time needs**: Must they arrive instantly or is eventual delivery OK? -4. **User preferences**: Can users customize what notifications they receive? -5. **Priority levels**: Do some notifications need to override "do not disturb"? - -## Architectural Options - -### Option A: Simple Database Polling -``` -User requests → API checks DB → Returns unread notifications -``` -**Pros:** -- Simple to implement -- No infrastructure complexity -- Easy to debug - -**Cons:** -- Not real-time -- Doesn't scale to high volumes -- Inefficient for many concurrent users - -**Best for:** Low volume, non-real-time needs - ---- - -### Option B: Queue-Based System -``` -Event → Queue → Worker → Notification Service → User -``` -**Pros:** -- Handles high volume -- Retries on failure -- Decoupled components - -**Cons:** -- More infrastructure (queue system) -- Higher complexity -- Delayed delivery possible - -**Best for:** High volume, reliability critical - ---- - -### Option C: WebSocket Real-Time -``` -Event → Notification Service → WebSocket → User -``` -**Pros:** -- Instant delivery -- Great UX -- Efficient for active users - -**Cons:** -- Complex client code -- Requires persistent connections -- More server resources - -**Best for:** Real-time requirements, active users - ---- - -## Hybrid Recommendation - -For most applications, I'd suggest **combining approaches**: - -1. **WebSocket** for users actively online (instant) -2. **Queue-based** for background processing (reliable) -3. **Database polling** as fallback (simple) - -This gives you: -- Real-time when possible -- Reliability when needed -- Simplicity as baseline - -## Trade-off Matrix - -| Requirement | Option A | Option B | Option C | Hybrid | -|-------------|----------|----------|----------|--------| -| Real-time | ❌ | ⚠️ | ✅ | ✅ | -| High volume | ❌ | ✅ | ⚠️ | ✅ | -| Simplicity | ✅ | ❌ | ❌ | ⚠️ | -| Reliability | ⚠️ | ✅ | ⚠️ | ✅ | -| Cost | $ | $$ | $$$ | $$ | - -## Next Steps - -Which approach resonates with your needs? Or should we explore: -- Notification content templates? -- User preference management? -- Delivery failure handling? -- Analytics and tracking? -``` - -### API Design - -**Request:** -```bash -/brainstorm "REST API for blog posts" -``` - -**Brainstorm Mode Response:** -```markdown -Let's design the blog post API. A few questions first: - -**Access control:** -- Public read access, or authentication required? -- Who can create/edit/delete posts? - -**Features:** -- Just CRUD, or also drafts/publishing workflow? -- Comments on posts? -- Tags/categories? - -## Design Options - -### Option 1: Simple RESTful -``` -GET /posts # List all posts -GET /posts/:id # Get single post -POST /posts # Create post -PUT /posts/:id # Update post -DELETE /posts/:id # Delete post -``` - -**Pros:** -- Standard REST conventions -- Easy to understand -- Widely supported - -**Cons:** -- No draft/publish workflow -- Limited filtering - ---- - -### Option 2: Rich Resource Model -``` -GET /posts?status=published&tag=tech -GET /posts/:id -POST /posts -PATCH /posts/:id -DELETE /posts/:id -POST /posts/:id/publish -POST /posts/:id/unpublish -GET /posts/:id/revisions -``` - -**Pros:** -- Supports workflow -- Rich filtering -- Version history - -**Cons:** -- More complex -- More endpoints to maintain - ---- - -### Option 3: GraphQL Alternative -``` -query { - posts(status: PUBLISHED, tag: "tech") { - id, title, content, author { name } - } -} - -mutation { - createPost(input: {...}) { id } - publishPost(id: "123") { publishedAt } -} -``` - -**Pros:** -- Flexible querying -- No over-fetching -- Strong typing - -**Cons:** -- Different paradigm -- More upfront setup -- Caching more complex - -## Recommendation - -For a blog, I'd suggest **Option 2** (Rich REST) because: - -1. **Workflow support** - Drafts vs published is common need -2. **Filtering** - Users expect to filter by tag/category -3. **Familiarity** - REST is well-understood -4. **Incremental** - Can start simple and add endpoints - -## Sample Implementation - -Would you like me to: -1. Implement Option 2? -2. Explore the data model? -3. Design the authentication layer? -4. Something else? -``` - -### Problem Definition - -**Request:** -```bash -/brainstorm "users complain app is slow" -``` - -**Brainstorm Mode Response:** -```markdown -Let's break down this performance issue systematically. - -## Clarifying Questions - -To narrow down the problem: - -**When:** -- Slow all the time or at specific times? -- Started recently or always been slow? -- After a specific deployment? - -**Where:** -- Which pages/features feel slow? -- Mobile app, web app, or both? -- Specific user segments affected? - -**What:** -- What feels slow: page load, interactions, or data fetching? -- Error messages shown? -- How slow (seconds)? - -## Potential Root Causes - -### 1. Frontend Performance -- Large JavaScript bundles -- Unoptimized images -- Too many network requests -- No caching strategy - -### 2. Backend Performance -- Slow database queries (N+1 problems) -- No pagination on large datasets -- Blocking API calls -- Memory leaks - -### 3. Network Issues -- Large payload sizes -- No CDN usage -- Poor geographical distribution -- HTTP/1.1 instead of HTTP/2 - -### 4. Scaling Issues -- Single server under load -- Database connection pool exhausted -- No caching layer -- Synchronous processing - -## Investigation Approaches - -### Approach A: User-Centric -1. Identify most common user flows -2. Measure each step with timing -3. Find slowest step -4. Optimize that first - -**Best for:** Clear user complaints about specific features - ---- - -### Approach B: Data-Driven -1. Add performance monitoring (New Relic, DataDog) -2. Collect metrics for 24 hours -3. Analyze slow transactions -4. Prioritize by frequency × impact - -**Best for:** Unclear where slowness occurs - ---- - -### Approach C: Bottom-Up Audit -1. Profile database queries -2. Check API response times -3. Analyze bundle sizes -4. Review server metrics - -**Best for:** Suspected technical debt - -## Quick Wins to Try First - -Before deep investigation: - -1. **Enable caching** - - Browser caching headers - - CDN for static assets - - Redis for API responses - -2. **Optimize queries** - - Add indexes for common queries - - Implement pagination - - Use query explain plans - -3. **Reduce payload** - - Compress responses (gzip) - - Remove unused fields - - Lazy load images - -## My Recommendation - -I'd suggest a **hybrid approach**: - -1. Add basic performance monitoring (1 hour) -2. Measure top 3 user flows (2 hours) -3. Quick win optimizations (4 hours) -4. Review data and decide next steps - -This gives you: -- Quick improvements for users -- Data to make informed decisions -- Foundation for ongoing monitoring - -What additional context can you share to help narrow this down? -``` - -## Tips for Using Brainstorm Mode - -### Get the Most Value - -1. **Start with brainstorm, end with implementation** - ```bash - /mode brainstorm - /brainstorm "authentication approach" - # Make decisions based on exploration - - /mode implementation - /feature "implement OAuth2 with JWT" - # Execute the chosen approach - ``` - -2. **Use for unfamiliar territory** - - New technologies - - Complex domains - - Architecture decisions - -3. **Share context progressively** - - Answer questions one by one - - Add constraints as you think of them - - Claude will refine recommendations - -### When to Switch Out - -Switch from brainstorm mode when: -- You've made your decision -- Alternatives are clear -- Ready to implement -- Need faster responses - -### Combining with Other Modes - -```bash -# Brainstorm architecture, then research deeply -/brainstorm --mode=brainstorm "microservices vs monolith" -/research --mode=deep-research "microservices implementation patterns" - -# Brainstorm design, then implement efficiently -/brainstorm --mode=brainstorm "database schema" -/feature --mode=implementation "create schema from design" -``` - -## Interactive Brainstorming - -For interactive sessions with follow-up questions: - -```bash -/brainstorm "feature name" -``` - -Claude will ask one question at a time, validate your response, and progressively refine the exploration. - -## Mode Activation - -```bash -# Session-wide brainstorm mode -/mode brainstorm - -# Single command with brainstorm -/plan --mode=brainstorm "complex feature" -/feature --mode=brainstorm "new system" -``` - -## Comparison with Other Modes - -| Aspect | Brainstorm | Default | Deep Research | -|--------|------------|---------|---------------| -| Questions asked | Many | Some | Some | -| Alternatives shown | Always | Sometimes | Multiple with evidence | -| Decision timing | Delayed | Normal | After thorough analysis | -| Code output | Minimal | Balanced | Minimal | -| Best for | Design | Implementation | Investigation | - -## Configuration - -Brainstorm mode can be customized in `.claude/modes/brainstorm.md`: - -- Number of alternatives to show -- Question verbosity -- When to converge on solution -- Output format preferences - -## Related Modes - -- **Deep Research Mode**: For evidence-based exploration -- **Default Mode**: For balanced exploration + implementation -- **Review Mode**: For critical analysis of existing designs - -## Related Documentation - -- [Modes Overview](/claudekit/modes/overview) -- [Planning Workflow](/claudekit/guides/planning) -- [Decision Making](/claudekit/guides/decisions) diff --git a/website/src/content/docs/modes/deep-research.md b/website/src/content/docs/modes/deep-research.md deleted file mode 100644 index ecbe541..0000000 --- a/website/src/content/docs/modes/deep-research.md +++ /dev/null @@ -1,921 +0,0 @@ ---- -title: Deep Research Mode -description: Thorough investigation mode with evidence and citations ---- - -# Deep Research Mode - -## Overview - -Deep research mode prioritizes comprehensive investigation over speed. It emphasizes evidence gathering, cross-referencing, citations, and acknowledging uncertainty. Use when accuracy and depth matter more than efficiency. - -This mode produces structured reports with confidence levels, sources, and explicit acknowledgment of limitations. - -## When to Use - -Deep research mode is ideal for: - -- **Technology evaluation** - Comparing frameworks, libraries, approaches -- **Architecture research** - Investigating patterns and best practices -- **Security audits** - Finding vulnerabilities and assessing risk -- **Performance analysis** - Identifying bottlenecks and optimization opportunities -- **Complex debugging** - Root cause analysis of difficult bugs -- **Due diligence** - Thorough assessment before major decisions - -## Behavior Changes - -### Communication Style - -**Evidence-based:** -- Cite sources and evidence for claims -- Acknowledge uncertainty explicitly -- Present confidence levels for conclusions -- Include caveats and limitations -- Cross-reference multiple sources - -**Example:** -```markdown -## Research: Authentication Approaches - -### Finding 1: JWT vs Session Tokens (Confidence: 9/10) - -**Evidence:** -- Code analysis: src/auth/jwt.ts (line 45-78) -- Documentation: docs/auth-spec.md -- Industry practice: OWASP guidelines - -**Analysis:** -Current implementation uses JWTs stored in localStorage. This is -vulnerable to XSS attacks (OWASP A7:2017). - -Sessions with httpOnly cookies provide better XSS protection but -require server state management. - -**Recommendation:** Switch to httpOnly cookies unless you have -specific stateless requirements. - -### Gaps & Limitations -- Couldn't determine actual XSS risk without security audit -- No data on session volume to assess state management cost -- Need to validate CORS configuration for cookie approach -``` - -### Problem-Solving Approach - -- **Exhaustive exploration** - Check all relevant sources -- **Multiple verification passes** - Cross-check findings -- **Document assumptions** - Make reasoning transparent -- **Assess confidence** - How sure are we? - -### Output Format - -- Structured research reports -- Evidence sections with sources -- Confidence indicators (1-10 or High/Medium/Low) -- Explicit gaps and limitations -- Methodology explanation - -## Research Process - -### Phase 1: Scope Definition - -Before diving in, clarify: -- What specific questions need answering? -- What would constitute a successful answer? -- What constraints or context matter? - -### Phase 2: Information Gathering - -Systematically collect: -- **Codebase search** - Grep for relevant patterns, functions, configs -- **Documentation** - READMEs, comments, specifications -- **Dependencies** - package.json, requirements.txt, imports -- **Issue tracking** - Known bugs, feature requests -- **Web research** - Official docs, best practices, security advisories - -### Phase 3: Analysis - -Process the findings: -- Cross-reference findings across sources -- Identify patterns and contradictions -- Note reliability of each source -- Assess confidence levels -- Document uncertainties - -### Phase 4: Synthesis - -Draw conclusions: -- Present findings with evidence -- State confidence levels clearly -- Acknowledge what's unknown -- Provide actionable recommendations - -## Examples - -### Technology Evaluation - -**Request:** -```bash -/research --mode=deep-research "should we use GraphQL vs REST?" -``` - -**Deep Research Response:** -```markdown -## Research: GraphQL vs REST for Our API - -### Methodology -- Analyzed current REST API: 12 endpoints, 4 resources -- Reviewed client usage patterns in frontend code -- Checked team experience with both technologies -- Researched complexity and maintenance requirements - ---- - -### Finding 1: Client Usage Patterns (Confidence: 8/10) - -**Evidence:** -- `src/frontend/api/users.ts`: 8 REST calls, 5 fetch full objects - unnecessarily (lines 23, 45, 67, 89, 123) -- Network tab analysis: 40% of data fetched is unused -- Average payload: 2.3KB, estimated needed: 1.1KB - -**Analysis:** -Over-fetching is significant. GraphQL would allow clients to request -only needed fields, reducing bandwidth by ~50%. - -**Confidence note:** Based on static analysis. Real usage may vary. - ---- - -### Finding 2: Team Expertise (Confidence: 10/10) - -**Evidence:** -- Team survey: 3/3 developers experienced with REST -- Team survey: 0/3 developers experienced with GraphQL -- package.json: No GraphQL dependencies - -**Analysis:** -Adopting GraphQL requires learning curve. Estimate: -- Initial learning: 2-3 weeks per developer -- Production-ready: 1-2 months -- Expertise: 6+ months - ---- - -### Finding 3: Maintenance Complexity (Confidence: 7/10) - -**Evidence:** -- REST: 12 endpoints, ~300 lines route code -- GraphQL (estimated): 1 endpoint, ~400 lines schema + resolvers -- Industry reports: GraphQL schemas grow faster than REST APIs - -**Analysis:** -GraphQL adds upfront complexity but may reduce long-term endpoint -proliferation. - -**Caveat:** Projection based on typical patterns, not our specific -growth trajectory. - ---- - -### Finding 4: Tooling & Ecosystem (Confidence: 9/10) - -**Evidence:** -- REST: Swagger UI, well-supported testing tools -- GraphQL: GraphiQL, Apollo DevTools, strong TypeScript support -- Current stack: Already using TypeScript - -**Analysis:** -Both have mature tooling. GraphQL TypeScript integration could improve -type safety across frontend/backend boundary. - ---- - -### Comparison Matrix - -| Criterion | REST | GraphQL | Winner | -|-----------|------|---------|--------| -| Team familiarity | ✅ High | ❌ None | REST | -| Over-fetching | ❌ Significant | ✅ Eliminated | GraphQL | -| Type safety | ⚠️ Manual | ✅ Automatic | GraphQL | -| Learning curve | ✅ Minimal | ❌ 2-3 months | REST | -| Long-term maintenance | ⚠️ Endpoint sprawl | ✅ Schema evolution | GraphQL | -| Caching | ✅ HTTP caching | ⚠️ Complex | REST | - ---- - -### Conclusions - -**Recommendation: Stick with REST for now** (Confidence: 7/10) - -**Reasoning:** -1. **Short-term constraints**: No GraphQL expertise, 2-3 month learning - curve is significant for 3-person team -2. **Over-fetching is solvable**: Can add field filtering to REST - (e.g., `?fields=id,name`) for ~80% of benefit -3. **Type safety gains**: Can achieve with TypeScript + OpenAPI codegen - -**When to reconsider GraphQL:** -- Team grows beyond 5 developers -- API complexity exceeds 30+ endpoints -- Mobile app launches (bandwidth critical) -- Frontend team becomes GraphQL-experienced - ---- - -### Gaps & Limitations - -**What we don't know:** -- Actual bandwidth costs (no production metrics) -- Client device diversity (mobile vs desktop ratio) -- Future feature requirements (may favor GraphQL) -- Whether competitors use GraphQL (market expectation) - -**What would change the recommendation:** -- If 50%+ traffic is mobile (bandwidth matters more) -- If hiring GraphQL experts (removes learning curve issue) -- If building public API (GraphQL great for external developers) - ---- - -### Sources - -**Codebase:** -- `src/frontend/api/users.ts` (client usage patterns) -- `src/api/routes/` (current REST implementation) -- `package.json` (current dependencies) - -**Team:** -- Developer survey (2024-01-15) - -**External:** -- OWASP API Security Project -- GraphQL Best Practices (graphql.org) -- "REST vs GraphQL" (2023, Thoughtworks) -``` - -### Security Audit - -**Request:** -```bash -/research --depth=5 --persona=security src/auth/ -``` - -**Deep Research Response:** -```markdown -## Security Audit: Authentication Module - -### Methodology -- Code review: All files in src/auth/ -- Dependency analysis: Known vulnerabilities -- Pattern matching: Common security anti-patterns -- Standards check: OWASP Top 10 compliance - ---- - -### Critical Findings 🔴 - -#### Finding 1: Hardcoded Secret (Confidence: 10/10) - -**Location:** `src/auth/jwt.ts:12` - -**Evidence:** -```typescript -const JWT_SECRET = "mysecretkey123"; // Line 12 -``` - -**Risk:** CRITICAL -- Secret is in version control -- Anyone with repo access can forge tokens -- All tokens compromised if code leaks - -**Exploitation:** -```typescript -// Attacker can create valid tokens -const forgedToken = jwt.sign({ userId: 'admin' }, 'mysecretkey123'); -``` - -**Fix:** -```typescript -const JWT_SECRET = process.env.JWT_SECRET; -if (!JWT_SECRET) throw new Error('JWT_SECRET required'); -``` - -**References:** -- OWASP A2:2021 - Cryptographic Failures -- CWE-798: Use of Hard-coded Credentials - ---- - -#### Finding 2: No Rate Limiting (Confidence: 9/10) - -**Location:** `src/api/auth.ts:45-67` (login endpoint) - -**Evidence:** -- No rate limiting middleware -- No failed attempt tracking -- Can attempt login indefinitely - -**Risk:** HIGH -- Brute force attacks viable -- No account lockout -- No monitoring of suspicious activity - -**Test:** -```bash -# Can send unlimited login attempts -for i in {1..10000}; do - curl -X POST /auth/login -d '{"user":"admin","pass":"test'$i'"}' -done -``` - -**Fix:** -```typescript -import rateLimit from 'express-rate-limit'; - -const loginLimiter = rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 5, // 5 attempts - message: 'Too many login attempts' -}); - -router.post('/login', loginLimiter, loginHandler); -``` - -**References:** -- OWASP: Authentication Cheat Sheet -- CWE-307: Improper Restriction of Excessive Authentication Attempts - ---- - -### Important Findings 🟠 - -#### Finding 3: Weak Password Requirements (Confidence: 8/10) - -**Location:** `src/auth/validation.ts:23` - -**Evidence:** -```typescript -const passwordValid = password.length >= 6; // Too weak -``` - -**Risk:** MEDIUM -- 6 characters easily brute-forced -- No complexity requirements -- Common passwords allowed - -**Current weakness:** -- 6 chars, lowercase only = 26^6 = 308M combinations -- Cracked in ~1 hour with modern GPU - -**Recommendation:** -- Minimum 12 characters -- Require: uppercase, lowercase, number, symbol -- Check against common password list - -**Fix:** -```typescript -import { passwordStrength } from 'check-password-strength'; - -function validatePassword(password: string): boolean { - const strength = passwordStrength(password); - return strength.value === 'Strong' || strength.value === 'Medium'; -} -``` - ---- - -### Minor Findings 🟡 - -#### Finding 4: No HTTPS Enforcement (Confidence: 6/10) - -**Location:** `src/server.ts:15` - -**Evidence:** -```typescript -app.listen(3000); // HTTP only, no HTTPS redirect -``` - -**Risk:** LOW (if behind reverse proxy), MEDIUM (if exposed) -- Credentials sent in cleartext if HTTP used -- Session tokens interceptable - -**Note:** Risk is LOW if Nginx/Cloudflare handles HTTPS termination. - -**Verification needed:** -- Check if reverse proxy handles HTTPS -- Check production deployment config - ---- - -### Positive Findings ✅ - -**Good practices observed:** -- ✅ Passwords are hashed (bcrypt, src/auth/password.ts:34) -- ✅ JWT tokens expire (1 hour, src/auth/jwt.ts:45) -- ✅ CORS configured (src/middleware/cors.ts) -- ✅ SQL injection protected (using parameterized queries) - ---- - -### Risk Summary - -| Severity | Count | Must Fix Before Production | -|----------|-------|----------------------------| -| 🔴 Critical | 2 | Yes - Immediate | -| 🟠 Important | 1 | Yes - Within 1 week | -| 🟡 Minor | 1 | Should fix | - -**Overall Risk: HIGH** - Not production-ready in current state. - ---- - -### Remediation Plan - -**Phase 1: Critical (Today)** -1. Move JWT_SECRET to environment variable -2. Add rate limiting to login endpoint -3. Deploy to staging and verify - -**Phase 2: Important (This Week)** -4. Strengthen password requirements -5. Add password breach checking (haveibeenpwned API) -6. Implement account lockout after failed attempts - -**Phase 3: Minor (Next Sprint)** -7. Enforce HTTPS or verify reverse proxy config -8. Add security headers (helmet.js) -9. Set up security monitoring - ---- - -### Gaps & Limitations - -**Not Assessed:** -- Session storage security (needs Redis config review) -- Frontend XSS vulnerabilities (outside src/auth/) -- Infrastructure security (firewall, network segmentation) -- Third-party auth (OAuth, if any) - -**Assumptions:** -- Assuming production uses HTTPS (needs verification) -- Assuming rate limiting not at reverse proxy level -- Assuming single-server deployment (clustering affects session handling) - -**Recommended Follow-ups:** -- Full application security audit (not just auth) -- Penetration testing -- Security logging and monitoring setup - ---- - -### Sources - -**Code Reviewed:** -- All files in `src/auth/` (8 files, 450 lines) -- `src/api/auth.ts` (API endpoints) -- `src/middleware/` (security middleware) -- `package.json` (dependencies) - -**Standards:** -- OWASP Top 10 (2021) -- OWASP Authentication Cheat Sheet -- CWE Top 25 Most Dangerous Weaknesses - -**Tools:** -- Manual code review -- Pattern matching for common vulnerabilities -- npm audit (dependency check) -``` - -### Performance Investigation - -**Request:** -```bash -/research --mode=deep-research "why is /api/posts so slow?" -``` - -**Deep Research Response:** -```markdown -## Performance Investigation: /api/posts Endpoint - -### Methodology -1. Code analysis: Trace request flow -2. Database query analysis: Check execution plans -3. Network analysis: Payload sizes -4. Profiling: Identify bottlenecks - ---- - -### Finding 1: N+1 Query Problem (Confidence: 10/10) - -**Location:** `src/services/post-service.ts:45-67` - -**Evidence:** -```typescript -// Line 45: Fetches all posts -const posts = await db.posts.findAll(); - -// Lines 50-55: Loop fetches author for each post -for (const post of posts) { - post.author = await db.users.findById(post.authorId); // N queries! -} -``` - -**Database logs:** -```sql -SELECT * FROM posts; -- 1 query -SELECT * FROM users WHERE id = 1; -- Query 1 of N -SELECT * FROM users WHERE id = 2; -- Query 2 of N -SELECT * FROM users WHERE id = 3; -- Query 3 of N --- ... 100 more queries for 100 posts -``` - -**Impact:** -- 100 posts = 101 database queries -- Each query: ~10ms -- Total time: ~1,010ms just for queries -- **Actual measurement:** 1,247ms total (from logs) - -**Fix:** -```typescript -// Single query with JOIN -const posts = await db.posts.findAll({ - include: [{ model: db.users, as: 'author' }] -}); -// Now: 1 query instead of 101 -// Expected time: ~50ms -``` - -**Expected improvement: 95% faster** (1,247ms → 50ms) - -**Confidence: 10/10** - Classic N+1 problem, well-documented fix - ---- - -### Finding 2: Large Payload Size (Confidence: 9/10) - -**Location:** `src/api/posts.ts:23` - -**Evidence:** -```typescript -// Returns everything, no pagination -res.json(posts); // All 100 posts at once -``` - -**Measurements:** -- Average post with author: 2.3KB -- 100 posts: 230KB response -- Network time: ~400ms on 3G connection - -**Analysis:** -Most clients only show 10 posts at a time. We're sending 10x needed data. - -**Fix:** -```typescript -// Add pagination -const limit = parseInt(req.query.limit) || 10; -const offset = parseInt(req.query.offset) || 0; - -const posts = await db.posts.findAll({ - limit, - offset, - include: [{ model: db.users, as: 'author' }] -}); - -res.json({ - posts, - total: await db.posts.count(), - limit, - offset -}); -``` - -**Expected improvement:** 230KB → 23KB (90% reduction) - -**Confidence: 9/10** - Measured in browser network tab - ---- - -### Finding 3: No Caching (Confidence: 7/10) - -**Location:** `src/api/posts.ts` (missing cache layer) - -**Evidence:** -- No Cache-Control headers -- No Redis/Memcached integration -- Every request hits database - -**Analysis:** -Posts don't change frequently (checked git history: 2-3 updates/hour). -Could cache for 5 minutes. - -**Potential improvement:** -```typescript -// Add Redis caching -const cacheKey = `posts:${limit}:${offset}`; -let posts = await redis.get(cacheKey); - -if (!posts) { - posts = await db.posts.findAll({...}); - await redis.setex(cacheKey, 300, JSON.stringify(posts)); // 5 min -} -``` - -**Expected improvement:** -- Cache hit: ~5ms (vs 50ms from DB) -- 90% cache hit rate (estimated) = 45ms average improvement - -**Confidence: 7/10** - Based on typical cache hit rates, needs measurement - ---- - -### Finding 4: Missing Database Indexes (Confidence: 8/10) - -**Evidence:** -```sql -EXPLAIN SELECT * FROM posts WHERE authorId = 5; -``` - -**Result:** -``` -Seq Scan on posts (cost=0.00..180.00 rows=10 width=100) - Filter: (authorId = 5) -``` - -**Analysis:** -Sequential scan of entire table. With index, would be index lookup. - -**Fix:** -```sql -CREATE INDEX idx_posts_author_id ON posts(authorId); -``` - -**Expected improvement:** Large dataset improvement -- Current: O(n) - scans all rows -- With index: O(log n) - fast lookup - -**Confidence: 8/10** - EXPLAIN shows no index, but impact depends on -table size (currently only 100 rows, so minimal impact now) - ---- - -### Performance Summary - -| Issue | Current Impact | Fix Impact | Priority | -|-------|----------------|------------|----------| -| N+1 queries | 1,200ms | -1,150ms (95%) | 🔴 Critical | -| Large payload | 400ms | -360ms (90%) | 🟠 Important | -| No caching | 50ms | -45ms (90%) | 🟡 Nice-to-have | -| No index | Minimal (100 rows) | Future-proofing | 🟡 Nice-to-have | - -**Total current time:** ~1,650ms -**After fixes:** ~90ms -**Expected improvement:** 94% faster - ---- - -### Recommended Fix Order - -**Phase 1: Quick Win (Today - 30 minutes)** -```typescript -// Fix N+1 problem -const posts = await db.posts.findAll({ - include: [{ model: db.users, as: 'author' }], - limit: 10, - offset: 0 -}); -``` -**Impact:** 95% improvement immediately - -**Phase 2: Pagination (This Week - 2 hours)** -- Add limit/offset parameters -- Add total count -- Update frontend to paginate - -**Impact:** Better UX + smaller payloads - -**Phase 3: Caching (Next Sprint - 1 day)** -- Set up Redis -- Add caching layer -- Add cache invalidation on updates - -**Impact:** Further 90% improvement on repeated requests - -**Phase 4: Indexes (Next Sprint - 30 minutes)** -- Add database indexes -- Monitor query performance - -**Impact:** Future-proofing for scale - ---- - -### Gaps & Limitations - -**What we measured:** -- ✅ Database query time (from logs) -- ✅ Payload size (from network tab) -- ✅ Query plans (EXPLAIN) - -**What we didn't measure:** -- ❌ Real user experience (RUM) -- ❌ Server CPU/memory during load -- ❌ Performance under concurrent requests -- ❌ 95th/99th percentile response times - -**Assumptions:** -- Assuming single-server deployment -- Assuming 3G network (400ms for 230KB) -- Assuming 90% cache hit rate (typical, but unverified) - -**Recommended follow-ups:** -- Add APM tool (New Relic, DataDog) -- Load testing (100+ concurrent users) -- Real user monitoring -- Database slow query log analysis - ---- - -### Sources - -**Code:** -- `src/services/post-service.ts` (logic) -- `src/api/posts.ts` (endpoint) -- Database logs (query times) - -**Measurements:** -- Browser DevTools Network tab (payload sizes) -- PostgreSQL EXPLAIN (query plans) -- Application logs (request timing) - -**References:** -- "N+1 Query Problem" (guides.rubyonrails.org) -- "Database Indexing Best Practices" (use-the-index-luke.com) -``` - -## Depth Levels - -Control thoroughness with the `--depth` flag: - -| Level | Behavior | Use Case | -|-------|----------|----------| -| 1 | Quick scan, surface findings | Initial triage | -| 2 | Standard analysis | Regular research | -| 3 | Thorough investigation | Most deep research | -| 4 | Comprehensive with cross-references | Important decisions | -| 5 | Exhaustive, leave no stone unturned | Critical audits | - -**Example:** -```bash -/research --depth=5 "authentication approach" -``` - -## Tips for Using Deep Research Mode - -### When It Provides Most Value - -1. **Before major decisions** - - Framework selection - - Architecture changes - - Security implementations - -2. **When bugs are mysterious** - - Intermittent issues - - Complex interactions - - Performance problems - -3. **For audits and reviews** - - Security audits - - Performance reviews - - Code quality assessments - -### Maximize Research Quality - -**Provide context:** -```bash -# Less effective -/research "GraphQL" - -# More effective -/research "GraphQL vs REST for our 12-endpoint API serving mobile apps" -``` - -**Ask specific questions:** -```bash -# Vague -/research "improve performance" - -# Specific -/research "why is /api/posts taking 1.5s? Database logs show 101 queries." -``` - -**Share constraints:** -```bash -/research --mode=deep-research "authentication approach for 3-person team -with no GraphQL experience, expecting 10K users" -``` - -### Combine with Sequential Thinking - -For complex problems: - -```bash -/research --mode=deep-research --sequential "migrate from MongoDB to -PostgreSQL while maintaining zero downtime" -``` - -This activates both deep research AND step-by-step reasoning. - -## Mode Activation - -```bash -# Session-wide deep research -/mode deep-research - -# Single command -/research --mode=deep-research [topic] -/fix --mode=deep-research --depth=5 [error] - -# With persona for focused research -/review --mode=deep-research --persona=security src/auth/ -``` - -## Output Structure Template - -Deep research outputs typically follow this structure: - -```markdown -## Research: [Topic] - -### Methodology -[How we researched this] - ---- - -### Finding 1: [Title] (Confidence: X/10) -**Evidence:** [Sources, locations, measurements] -**Analysis:** [What this means] -**Impact:** [How significant] - -### Finding 2: [Title] (Confidence: X/10) -[Same structure] - ---- - -### Conclusions -- [Conclusion 1] (Confidence: X/10) -- [Recommendation with reasoning] - ---- - -### Gaps & Limitations -- [What we don't know] -- [What would change the recommendation] - ---- - -### Sources -- [Source 1] -- [Source 2] -``` - -## When NOT to Use - -Avoid deep research mode for: - -- **Simple, well-understood tasks** - Overkill -- **Time-sensitive fixes** - Too slow -- **Repetitive operations** - Use token-efficient instead -- **Clear, obvious solutions** - Use implementation mode - -## Comparison with Other Modes - -| Aspect | Deep Research | Brainstorm | Default | -|--------|---------------|------------|---------| -| Thoroughness | Exhaustive | Exploratory | Standard | -| Evidence | Required | Optional | Sometimes | -| Confidence levels | Always | No | No | -| Sources cited | Yes | No | No | -| Speed | Slow | Medium | Fast | -| Token usage | High | High | Medium | - -## Configuration - -Deep research mode is customizable in `.claude/modes/deep-research.md`: - -- Default depth level -- Confidence threshold -- Required evidence types -- Report structure - -## Related Modes - -- **Review Mode**: For critical analysis (less evidence-focused) -- **Brainstorm Mode**: For exploration (less evidence-focused) -- **Default Mode**: For balanced research without deep investigation - -## Related Documentation - -- [Research Command](/claudekit/commands/research) -- [Sequential Thinking Skill](/claudekit/skills/sequential-thinking) -- [Security Audits](/claudekit/guides/security) diff --git a/website/src/content/docs/modes/default.md b/website/src/content/docs/modes/default.md deleted file mode 100644 index bdd1b4c..0000000 --- a/website/src/content/docs/modes/default.md +++ /dev/null @@ -1,242 +0,0 @@ ---- -title: Default Mode -description: Standard balanced mode for general development tasks ---- - -# Default Mode - -## Overview - -Default mode provides balanced behavior that works well for most development tasks. It offers a good mix of thoroughness and efficiency without optimizing for any specific use case. - -This is the baseline mode that Claude uses unless you explicitly specify another mode. All other modes modify this standard behavior in specific ways. - -## When to Use - -Default mode is suitable for: - -- General development tasks -- When you're unsure which mode to use -- Mixed-complexity work -- Learning the system -- Balanced code + explanation needs - -## Behavior Changes - -### Communication Style - -**Standard responses:** -- Clear and concise without being terse -- Explanations where helpful, not excessive -- Balanced between action and discussion -- Standard code comments - -**Example:** -``` -I'll help you implement user authentication. This will involve creating -a service for handling login/logout and integrating with your existing -user model. - -Here's the authentication service: - -[code with standard comments] - -This implementation uses JWT tokens for stateless authentication. -The tokens expire after 24 hours and include the user ID in the payload. -``` - -### Problem-Solving Approach - -- Balanced analysis depth -- Standard verification steps -- Normal iteration cycles -- Ask clarifying questions when needed -- Make reasonable defaults for minor decisions - -### Output Format - -- Full code blocks with context -- Helpful explanations (not exhaustive) -- Standard documentation level -- File paths clearly marked -- Test output when relevant - -## Examples - -### Feature Implementation - -**Request:** -```bash -/feature "add password reset functionality" -``` - -**Default Mode Response:** -```markdown -I'll implement password reset functionality with email verification. - -## Implementation Plan -1. Create password reset token model -2. Add reset request endpoint -3. Send reset email -4. Create password update endpoint -5. Add tests - -## Files to Create/Modify -- `src/models/password-reset-token.ts` (new) -- `src/services/auth-service.ts` (modify) -- `src/api/auth.ts` (modify) -- `src/services/email-service.ts` (modify) -- Tests for each component - -Let me start with the token model: - -[code] - -This model stores password reset tokens with a 1-hour expiration. -The token is hashed for security. - -Next, the auth service methods: - -[code] -``` - -### Bug Fix - -**Request:** -```bash -/fix "users can't upload images > 5MB" -``` - -**Default Mode Response:** -```markdown -The issue is in the file upload middleware. The default limit is set -to 5MB. I'll increase it to 50MB and add proper error handling. - -Here's the fix: - -[code] - -This change: -1. Increases the limit to 50MB -2. Adds validation for file type -3. Returns a clear error message if limit exceeded - -Test with: `curl -F "file=@large-image.jpg" http://localhost:3000/upload` -``` - -### Code Review - -**Request:** -```bash -/review src/services/payment-service.ts -``` - -**Default Mode Response:** -```markdown -## Code Review: payment-service.ts - -### Issues Found - -**Critical:** -1. Line 45: API key is logged in error handler - - Risk: Exposes sensitive data in logs - - Fix: Remove API key from error message - -**Important:** -2. Line 78: No timeout on payment API call - - Risk: Can hang indefinitely - - Fix: Add 30-second timeout - -**Minor:** -3. Line 12: Magic number for retry attempts - - Fix: Extract to constant `MAX_RETRIES = 3` - -### Positive Notes -- Good error handling overall -- Tests cover main flows -- Clear function names - -### Recommendation -Fix critical issue before merge. Consider addressing important issue. -``` - -## Tips for Using Default Mode - -### When It Works Best - -Default mode shines when: -- You want a single mode for everything -- Task complexity is medium -- You prefer consistency over optimization -- You're collaborating with others who expect standard responses - -### When to Switch - -Consider switching from default mode when: -- **To Brainstorm**: You need to explore alternatives -- **To Token-Efficient**: You're doing repetitive tasks -- **To Implementation**: You have a clear plan to execute -- **To Deep Research**: You need thorough investigation -- **To Review**: You're doing code review specifically - -### Combining with Flags - -Even in default mode, you can use flags for specific behaviors: - -```bash -# Default mode but with security focus -/review --persona=security src/auth/ - -# Default mode but save output -/plan --save=plans/feature.md "new feature" - -# Default mode but more thorough -/fix --depth=4 "complex error" -``` - -## Mode Activation - -Default mode is active automatically. You don't need to activate it. - -To explicitly return to default mode after using another: - -```bash -/mode default -``` - -Or use it for a single command: - -```bash -/feature --mode=default "description" -``` - -## Comparison with Other Modes - -| Aspect | Default | vs Brainstorm | vs Token-Efficient | vs Implementation | -|--------|---------|---------------|-------------------|-------------------| -| Explanation level | Moderate | High | Minimal | Low | -| Code output | Balanced | Less code, more discussion | Mostly code | Mostly code | -| Questions asked | When needed | Frequently | Rarely | Rarely | -| Decision making | Balanced | Presents options | Makes defaults | Makes defaults | -| Best for | General use | Exploration | High volume | Execution | - -## Configuration - -Default mode behavior is defined in `.claude/modes/default.md`. You can customize: - -- Response verbosity -- Comment density -- When to ask questions -- Output formatting - -## Related Modes - -- **Brainstorm Mode**: Use when you need more exploration -- **Implementation Mode**: Use when you need less discussion -- **Token-Efficient Mode**: Use when you need faster responses - -## Related Documentation - -- [Modes Overview](/claudekit/modes/overview) -- [Commands Reference](/claudekit/commands/overview) -- [Switching Modes](/claudekit/guides/workflow) diff --git a/website/src/content/docs/modes/implementation.md b/website/src/content/docs/modes/implementation.md deleted file mode 100644 index ece3ffd..0000000 --- a/website/src/content/docs/modes/implementation.md +++ /dev/null @@ -1,512 +0,0 @@ ---- -title: Implementation Mode -description: Code-focused execution mode for clear, well-defined tasks ---- - -# Implementation Mode - -## Overview - -Implementation mode is optimized for executing clear plans with minimal discussion. It focuses on code generation, progress updates, and rapid iteration when the design is already decided. - -This mode produces mostly code with brief status updates, making it ideal for translating plans into working software efficiently. - -## When to Use - -Implementation mode is ideal for: - -- **Executing approved plans** - When design is complete and it's time to build -- **Clear, well-defined tasks** - Requirements are unambiguous -- **Repetitive code generation** - Similar files/components -- **Following established patterns** - Using existing code style -- **Batch file operations** - Creating many similar files - -## Behavior Changes - -### Communication Style - -**Action-oriented:** -- Minimal prose and explanations -- Progress indicators and status updates -- Skip discussion unless blocked -- Flag issues immediately and continue - -**Standard Mode Example:** -```markdown -I'll implement the user profile feature. This will involve creating -a new ProfileService, adding API endpoints, and creating the frontend -component. Let me walk you through each part: - -First, I'll create the service layer that handles profile data... - -[code with detailed explanations] - -This service encapsulates all profile-related business logic and -provides a clean interface for the API layer to consume... -``` - -**Implementation Mode Example:** -```markdown -Creating user profile feature: - -[1/4] ProfileService -[2/4] API endpoints -[3/4] Frontend component -[4/4] Tests - -Files created: -- src/services/profile-service.ts -- src/api/profile.ts -- src/components/Profile.tsx -- src/services/profile-service.test.ts - -✓ All tests passing -``` - -### Problem-Solving Approach - -- **Execute, don't deliberate** - Make it work, don't discuss it -- **Follow established patterns** - Use existing code style -- **Make reasonable defaults** - Don't ask about minor decisions -- **Flag blockers immediately** - Stop for critical issues only - -### Output Format - -- Code blocks with minimal wrapping text -- File paths clearly marked -- Progress indicators (`[1/5]`, `[2/5]`, etc.) -- Checkmarks for completion (`✓`) -- Minimal inline comments (code should be self-documenting) - -## Examples - -### Feature Implementation - -**Request:** -```bash -/feature --mode=implementation "add user avatar upload" -``` - -**Implementation Mode Response:** -```markdown -[1/5] Creating upload service - -`src/services/upload-service.ts`: -```typescript -import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'; -import { randomUUID } from 'crypto'; - -export class UploadService { - private s3: S3Client; - - constructor() { - this.s3 = new S3Client({ region: process.env.AWS_REGION }); - } - - async uploadAvatar(file: Express.Multer.File, userId: string): Promise { - const key = `avatars/${userId}/${randomUUID()}.${file.mimetype.split('/')[1]}`; - - await this.s3.send(new PutObjectCommand({ - Bucket: process.env.S3_BUCKET, - Key: key, - Body: file.buffer, - ContentType: file.mimetype, - })); - - return `https://${process.env.S3_BUCKET}.s3.amazonaws.com/${key}`; - } -} -``` - -[2/5] Adding upload middleware - -`src/middleware/upload.ts`: -```typescript -import multer from 'multer'; - -export const avatarUpload = multer({ - storage: multer.memoryStorage(), - limits: { fileSize: 5 * 1024 * 1024 }, - fileFilter: (req, file, cb) => { - if (file.mimetype.startsWith('image/')) { - cb(null, true); - } else { - cb(new Error('Images only')); - } - }, -}); -``` - -[3/5] Creating API endpoint - -`src/api/users.ts` (added): -```typescript -router.post( - '/avatar', - authenticate, - avatarUpload.single('avatar'), - async (req, res) => { - const url = await uploadService.uploadAvatar(req.file!, req.user.id); - await userService.updateAvatar(req.user.id, url); - res.json({ avatarUrl: url }); - } -); -``` - -[4/5] Updating user service - -`src/services/user-service.ts` (added method): -```typescript -async updateAvatar(userId: string, avatarUrl: string): Promise { - await db.users.update({ id: userId }, { avatarUrl }); -} -``` - -[5/5] Adding tests - -`src/services/upload-service.test.ts`: -```typescript -describe('UploadService', () => { - it('uploads avatar to S3', async () => { - const file = createMockFile('test.jpg'); - const url = await uploadService.uploadAvatar(file, 'user-123'); - expect(url).toMatch(/avatars\/user-123\/.*\.jpg/); - }); -}); -``` - -Running tests... ✓ 5 passing - -Done. Test with: -```bash -curl -F "avatar=@profile.jpg" http://localhost:3000/api/users/avatar -``` -``` - -### Plan Execution - -**Request:** -```bash -/execute-plan --mode=implementation plans/auth-refactor.md -``` - -**Implementation Mode Response:** -```markdown -Executing auth refactor plan... - -[1/8] Extract JWT config → src/config/jwt.ts ✓ -[2/8] Create TokenService → src/services/token-service.ts ✓ -[3/8] Update AuthService to use TokenService ✓ -[4/8] Add refresh token support ✓ -[5/8] Update login endpoint ✓ -[6/8] Add token refresh endpoint ✓ -[7/8] Update tests ✓ -[8/8] Update documentation ✓ - -Changed files: -- src/config/jwt.ts (new) -- src/services/token-service.ts (new) -- src/services/auth-service.ts (modified) -- src/api/auth.ts (modified) -- docs/auth.md (updated) - -Tests: 24 passing -Lint: Clean - -Ready to commit: -```bash -git add . -git commit -m "refactor(auth): extract token handling to service" -``` -``` - -### Batch File Generation - -**Request:** -```bash -/test --mode=implementation src/services/*.ts -``` - -**Implementation Mode Response:** -```markdown -Generating tests for 12 services... - -[1/12] user-service.test.ts ✓ -[2/12] auth-service.test.ts ✓ -[3/12] payment-service.test.ts ✓ -[4/12] email-service.test.ts ✓ -[5/12] notification-service.test.ts ✓ -[6/12] profile-service.test.ts ✓ -[7/12] upload-service.test.ts ✓ -[8/12] analytics-service.test.ts ✓ -[9/12] webhook-service.test.ts ✓ -[10/12] cache-service.test.ts ✓ -[11/12] queue-service.test.ts ✓ -[12/12] search-service.test.ts ✓ - -Created 12 test files, 87 tests total. - -Run: `npm test` -``` - -## Decision Making in Implementation Mode - -When encountering choices during implementation: - -| Situation | Behavior | Example | -|-----------|----------|---------| -| **Style choice** | Follow existing patterns | Use same naming as other files | -| **Missing detail** | Use reasonable default | Default to camelCase if unclear | -| **Ambiguity** | Flag and continue with assumption | ⚠️ Assumed JSON format, confirm if needed | -| **Blocker** | Stop and report immediately | 🛑 Missing API credentials required | - -### Flagging Format - -When making assumptions: - -```markdown -⚠️ Assumed: User avatars stored in S3 bucket 'app-avatars' -Continuing with this assumption. Update S3_BUCKET env var if different. -``` - -When blocked: - -```markdown -🛑 Blocked: Missing Stripe API key -Required for payment integration. Add STRIPE_SECRET_KEY to .env -Cannot proceed with payment service without this. -``` - -## Progress Tracking Patterns - -### Simple Task -```markdown -Creating auth middleware... -✓ Done - -Test: curl -H "Authorization: Bearer token" /api/protected -``` - -### Multi-Step Task -```markdown -[1/3] Database migration -[2/3] Service layer -[3/3] API endpoints - -✓ Complete -``` - -### Complex Feature -```markdown -User dashboard feature: - -Backend: - [1/4] Database schema ✓ - [2/4] Services ✓ - [3/4] API endpoints ✓ - [4/4] Tests ✓ - -Frontend: - [1/3] Components ✓ - [2/3] State management ✓ - [3/3] Integration ✓ - -✓ All done. Run: npm run dev -``` - -## Tips for Using Implementation Mode - -### When It Works Best - -1. **After planning/brainstorming** - ```bash - /mode brainstorm - /brainstorm "dashboard layout" - # Make decisions - - /mode implementation - /feature "implement dashboard with sidebar and cards" - # Execute quickly - ``` - -2. **With clear specifications** - - Detailed requirements - - Approved designs - - Existing patterns to follow - -3. **For experienced developers** - - You know the codebase - - Understand the tech stack - - Don't need explanations - -### When to Switch Out - -Switch from implementation mode when: -- **Blocked or confused** → Switch to Default or Brainstorm -- **Need explanation** → Switch to Default -- **Complex decision needed** → Switch to Brainstorm -- **Review needed** → Switch to Review mode - -### Combining with Other Modes - -```bash -# Brainstorm → Implement → Review -/mode brainstorm -/brainstorm "feature design" - -/mode implementation -/feature "implement design" - -/mode review -/review src/new-feature/ -``` - -### Maximum Efficiency - -Combine with token-efficient format: - -```bash -/execute-plan --mode=implementation --format=ultra plan.md -``` - -This gives you: -- Fast execution (implementation mode) -- Minimal tokens (ultra format) -- Maximum speed for clear plans - -## Typical Workflows - -### TDD Workflow - -```bash -/mode implementation - -/test "user login endpoint" -# Generates failing tests - -# Implement until tests pass -/fix "make login tests pass" - -✓ Tests passing -``` - -### Migration/Refactor - -```bash -/mode implementation - -# Execute refactor plan step by step -[1/10] Extract function ✓ -[2/10] Update imports ✓ -[3/10] Rename variables ✓ -... -[10/10] Update tests ✓ - -✓ Refactor complete -``` - -### Feature Branch - -```bash -/mode implementation - -/feature "user settings page" -# Implement feature - -/test "user settings" -# Add tests - -/review "src/settings/" -# Quick review - -/ship "feat: add user settings page" -# Commit and push -``` - -## Mode Activation - -```bash -# Session-wide implementation mode -/mode implementation - -# All commands now execute without discussion -/feature "feature 1" -/feature "feature 2" -/fix "bug 1" - -# Single command override -/feature --mode=implementation "specific feature" -``` - -## Output Examples - -### Minimal (Standard) -```markdown -Created UserService -Created UserController -Created tests - -✓ Done -``` - -### With Progress (Multi-step) -```markdown -[1/5] Model -[2/5] Service -[3/5] Controller -[4/5] Routes -[5/5] Tests - -✓ Complete - 5 files created -``` - -### With Assumptions (Ambiguous case) -```markdown -[1/3] Database schema -⚠️ Assumed: PostgreSQL (saw pg in package.json) - -[2/3] Repository -[3/3] Tests - -✓ Done -``` - -### With Blocker (Stopped) -```markdown -[1/4] Config -[2/4] Service - -🛑 Blocked: Missing API_KEY environment variable -Add to .env file and rerun. -``` - -## Comparison with Other Modes - -| Aspect | Implementation | Token-Efficient | Default | -|--------|---------------|-----------------|---------| -| Explanation | Minimal | None | Moderate | -| Progress updates | Yes | No | Sometimes | -| Code output | High | Highest | Balanced | -| Decision making | Auto (reasonable defaults) | Auto (fastest path) | Asks when unclear | -| Best for | Executing plans | High volume | General use | - -## Configuration - -Implementation mode behavior is defined in `.claude/modes/implementation.md`: - -- Progress indicator format -- Comment verbosity -- When to flag assumptions -- Default choices for common decisions - -## Related Modes - -- **Token-Efficient Mode**: Even more concise output -- **Default Mode**: More explanation and discussion -- **Review Mode**: Switch to this after implementation - -## Related Documentation - -- [Execute Plan Command](/claudekit/commands/execute-plan) -- [TDD Workflow](/claudekit/guides/tdd) -- [Batch Operations](/claudekit/guides/batch) diff --git a/website/src/content/docs/modes/orchestration.md b/website/src/content/docs/modes/orchestration.md deleted file mode 100644 index bdba355..0000000 --- a/website/src/content/docs/modes/orchestration.md +++ /dev/null @@ -1,1042 +0,0 @@ ---- -title: Orchestration Mode -description: Multi-agent coordination mode for complex parallel tasks ---- - -# Orchestration Mode - -## Overview - -Orchestration mode is designed for managing complex tasks that benefit from parallel execution, task delegation, and result aggregation. It optimizes for efficiency through intelligent parallelization and multi-agent coordination. - -This mode produces task breakdowns, agent assignments, progress tracking, and synthesized results from parallel work streams. - -## When to Use - -Orchestration mode is ideal for: - -- **Large-scale refactoring** - Changes across many files -- **Multi-file changes** - Coordinated updates to related files -- **Complex feature implementation** - Features spanning multiple areas -- **Parallelizable tasks** - Independent work that can run simultaneously -- **Multi-concern coordination** - Security + performance + features together - -## Behavior Changes - -### Communication Style - -**Coordination-focused:** -- Clear task delegation and assignments -- Progress aggregation across parallel work -- Coordination updates and checkpoints -- Final synthesis of results - -**Example:** -```markdown -## Orchestration Plan: Authentication Refactor - -### Phase 1: Parallel Analysis -Spawning 3 analysis agents... - -Agent #1: Security audit of current auth -Agent #2: Performance analysis of auth endpoints -Agent #3: Research modern auth patterns - -[Agents running in parallel...] - -Agent #1 complete: Found 3 security issues -Agent #2 complete: Identified 2 bottlenecks -Agent #3 complete: Recommended OAuth2 + JWT refresh - -### Phase 2: Synthesis -Combining findings across all agents... - -[Synthesized recommendations] - -### Phase 3: Parallel Implementation -Spawning 4 implementation agents... -[Implementation proceeds] -``` - -### Problem-Solving Approach - -- **Identify parallelizable work** - What can run simultaneously? -- **Delegate to specialized agents** - Right agent for each task -- **Aggregate results** - Combine findings intelligently -- **Resolve conflicts** - Handle overlapping changes - -### Output Format - -- Task decomposition with dependencies -- Agent assignments and status -- Progress tracking across all agents -- Quality gates between phases -- Consolidated final results - -## Orchestration Process - -### Phase 1: Analysis & Decomposition - -Break down the work: - -```markdown -## Task Decomposition: Multi-Tenant Feature - -### Total Work -Add tenant isolation to all services and endpoints - -### Parallelizable Tasks (Can run simultaneously) -1. Database schema changes (3 tables) -2. Service layer updates (5 services) -3. API endpoint modifications (8 endpoints) -4. Frontend tenant selector (1 component) -5. Test generation (all above) - -### Sequential Tasks (Must run in order) -6. Integration testing (after all above) -7. Migration script (after schema) -8. Documentation (final) - -### Estimated Time -- Parallel (tasks 1-5): 4 hours wall time, 15 hours total work -- Sequential (tasks 6-8): 3 hours -- **Total: 7 hours wall time vs 18 hours sequential** -``` - -### Phase 2: Delegation - -Assign to specialized agents: - -```markdown -## Agent Assignments - -| Task | Agent Type | Status | ETA | -|------|------------|--------|-----| -| DB schema | database-expert | 🔄 Running | 1h | -| User service | code-writer | 🔄 Running | 2h | -| Auth service | code-writer | 🔄 Running | 2h | -| Payment service | code-writer | 🔄 Running | 2h | -| API endpoints | api-specialist | 🔄 Running | 2h | -| Frontend | frontend-dev | 🔄 Running | 3h | -| Tests | tester | ⏸️ Waiting | After code | - -Parallel work: 6 agents active -``` - -### Phase 3: Progress Tracking - -Monitor and aggregate: - -```markdown -## Progress Update - -### Phase 1: Parallel Implementation (4h estimated) - -[████████████░░░░░░░░] 60% complete (2.4h elapsed) - -**Completed:** -- ✅ DB schema (1h actual) -- ✅ User service (2h actual) -- ✅ Auth service (1.8h actual) - -**In Progress:** -- 🔄 Payment service (60% done, 30m remaining) -- 🔄 API endpoints (75% done, 20m remaining) -- 🔄 Frontend (40% done, 1.5h remaining) - -**Blocked:** -- ⏸️ Tests (waiting for code completion) - -**Issues:** -- ⚠️ Minor conflict: User & Auth services both modified db config - Resolution: Auth service deferred to User service implementation -``` - -### Phase 4: Quality Gates - -Verify before proceeding: - -```markdown -## Quality Gate: Phase 1 → Phase 2 - -### Completion Check -- [x] All 6 parallel agents complete -- [x] No critical blockers -- [x] All code committed - -### Conflict Check -- [x] No file conflicts (1 resolved during execution) -- [x] Logical consistency verified -- [x] API contracts aligned - -### Quality Check -- [x] Unit tests pass for all services -- [ ] Integration tests pass (⚠️ 2 failures) -- [x] Lint clean -- [x] Type checks pass - -**Action Required:** Fix 2 integration test failures before Phase 2 - -Spawning debugger agent to fix test failures... -✅ Tests now passing - -**Gate Status: PASSED** ✅ -Proceeding to Phase 2... -``` - -### Phase 5: Synthesis - -Combine results: - -```markdown -## Results Summary - -### Completed Work - -**Database (1 agent, 1h)** -- Created `tenants` table -- Added `tenant_id` to users, posts, payments -- Created indexes for tenant queries - -**Services (3 agents, 2h avg)** -- User service: Tenant filtering on all queries -- Auth service: Tenant validation on login -- Payment service: Tenant isolation for transactions - -**API Layer (1 agent, 2h)** -- 8 endpoints updated with tenant middleware -- Tenant extracted from JWT token -- All queries scoped to tenant - -**Frontend (1 agent, 3h)** -- Tenant selector component -- Tenant context provider -- All API calls include tenant header - -**Tests (1 agent, 2h)** -- 45 new tests across all layers -- Tenant isolation verified -- Cross-tenant access blocked - -### Total Impact -- 15 files modified -- 1,247 lines added -- 234 lines removed -- 45 tests added -- All tests passing ✅ - -### Time Savings -- Sequential execution: ~18 hours -- Parallel execution: ~7 hours -- **Time saved: 11 hours (61% faster)** -``` - -## Parallelization Patterns - -### Pattern 1: Independent File Modifications - -**Good for parallel:** -```markdown -Task: Update all service files -- services/user-service.ts -- services/auth-service.ts -- services/payment-service.ts - -Each file is independent → Spawn 3 agents -``` - -**Orchestration:** -```bash -/spawn "Update user-service.ts with tenant support" -/spawn "Update auth-service.ts with tenant support" -/spawn "Update payment-service.ts with tenant support" - -# Wait for completion -/spawn --collect - -# Proceed with integration -``` - -### Pattern 2: Research & Analysis - -**Good for parallel:** -```markdown -Task: Evaluate authentication options - -Research streams: -- Security analysis of current system -- Performance benchmarks -- Competitor analysis -- Industry best practices - -All independent → Spawn 4 research agents -``` - -**Orchestration:** -```bash -/spawn "Security audit current auth system" -/spawn "Performance analysis auth endpoints" -/spawn "Research OAuth2 implementation patterns" -/spawn "Survey competitor auth approaches" - -/spawn --collect -# Synthesize findings into recommendation -``` - -### Pattern 3: Test Generation - -**Good for parallel:** -```markdown -Task: Generate tests for 10 services - -Each service's tests are independent → 10 parallel agents -``` - -**Orchestration:** -```bash -/mode orchestration -/test src/services/*.ts - -# Internally orchestrates: -# - Spawn agent per service file -# - Generate tests in parallel -# - Aggregate results -# - Report combined status -``` - -### Pattern 4: Phased Implementation - -**Complex dependencies:** -```markdown -Phase 1: Foundation (parallel) -- Database migrations -- Core models -- Base services - -Phase 2: Features (parallel, depends on Phase 1) -- API endpoints -- Business logic -- Validation - -Phase 3: Integration (sequential, depends on Phase 2) -- End-to-end tests -- Documentation -- Deployment -``` - -**Orchestration:** -```bash -# Phase 1 -/spawn "Database migration" -/spawn "Core models" -/spawn "Base services" -/spawn --collect - -# Quality gate: Verify Phase 1 - -# Phase 2 -/spawn "API endpoints" -/spawn "Business logic" -/spawn "Validation layer" -/spawn --collect - -# Quality gate: Verify Phase 2 - -# Phase 3 (sequential) -/test "E2E tests" -/doc "API documentation" -``` - -## Parallelization Decision Matrix - -| Condition | Parallelize? | Reason | -|-----------|--------------|--------| -| No shared files | ✅ Yes | No conflicts possible | -| Independent modules | ✅ Yes | No logical dependencies | -| Research tasks | ✅ Yes | Can aggregate findings | -| Test generation | ✅ Yes | Tests are independent | -| Shared dependencies | ❌ No | Coordination overhead | -| Order matters | ❌ No | Sequential dependency | -| Single source of truth | ❌ No | Risk of conflicts | -| Database migrations | ❌ No | Must be sequential | - -## Examples - -### Large-Scale Refactoring - -**Request:** -```bash -/feature --mode=orchestration "rename User to Account throughout codebase" -``` - -**Orchestration Mode Response:** -```markdown -## Orchestration Plan: User → Account Rename - -### Analysis -Found 47 files referencing "User" across: -- Models: 3 files -- Services: 8 files -- API: 12 endpoints -- Frontend: 18 components -- Tests: 6 test files - -### Task Decomposition - -**Phase 1: Safe Parallel Renames** -No dependencies between these: - -Group A - Backend (3 agents) -1. Models: User.ts, UserProfile.ts, UserSettings.ts -2. Services: user-service.ts, user-auth.ts, user-validation.ts -3. Repositories: user-repo.ts, user-cache.ts - -Group B - API (2 agents) -4. Routes: user-routes.ts, user-admin.ts -5. Controllers: user-controller.ts, user-auth-controller.ts - -Group C - Frontend (3 agents) -6. Components: UserProfile.tsx, UserSettings.tsx, UserCard.tsx -7. Hooks: useUser.ts, useUserAuth.ts -8. State: user-store.ts, user-actions.ts - -Group D - Tests (2 agents) -9. Backend tests: user-service.test.ts, user-repo.test.ts -10. Frontend tests: UserProfile.test.tsx, useUser.test.ts - -**Total: 10 parallel agents** - -**Phase 2: Integration & Verification** -Sequential (after Phase 1): -11. Database migration -12. Update imports across codebase -13. Run all tests -14. Fix any issues - ---- - -### Execution - -**Phase 1: Parallel Rename (Estimated: 2h wall time, 8h work)** - -[Agent Status] -Group A (Backend): - Agent #1 (Models): 🔄 Running... - Agent #2 (Services): 🔄 Running... - Agent #3 (Repos): 🔄 Running... - -Group B (API): - Agent #4 (Routes): 🔄 Running... - Agent #5 (Controllers): 🔄 Running... - -Group C (Frontend): - Agent #6 (Components): 🔄 Running... - Agent #7 (Hooks): 🔄 Running... - Agent #8 (State): 🔄 Running... - -Group D (Tests): - Agent #9 (Backend tests): 🔄 Running... - Agent #10 (Frontend tests): 🔄 Running... - ---- - -**[30 minutes later]** - -[Progress: 40%] - -Group A (Backend): - Agent #1: ✅ Complete (3 files, 45 renames) - Agent #2: 🔄 70% (4/6 files) - Agent #3: ✅ Complete (2 files, 23 renames) - -Group B (API): - Agent #4: ✅ Complete (2 files, 34 renames) - Agent #5: 🔄 85% (1 file remaining) - -Group C (Frontend): - Agent #6: 🔄 60% (2/3 files) - Agent #7: ✅ Complete (2 files, 56 renames) - Agent #8: ✅ Complete (2 files, 41 renames) - -Group D (Tests): - Agent #9: 🔄 50% (1/2 files) - Agent #10: 🔄 65% (UserProfile.test done) - ---- - -**[2 hours later]** - -Phase 1 Complete ✅ - -**Results:** -- 47 files modified -- 423 "User" → "Account" renames -- 0 conflicts (agents worked on separate files) -- All unit tests passing in modified files - ---- - -### Quality Gate 1: Phase 1 Verification - -**Checklist:** -- [x] All agents completed -- [x] No file conflicts -- [x] All files compile -- [x] Unit tests pass - -⚠️ Warning: Found 23 import statements still using old paths -Need import update phase - -**Proceeding to Phase 2...** - ---- - -**Phase 2: Integration (Sequential - 1h)** - -[1/4] Database migration -```sql -ALTER TABLE users RENAME TO accounts; -ALTER TABLE user_profiles RENAME TO account_profiles; --- ... more migrations -``` -✅ Migration successful - -[2/4] Updating imports across codebase -Scanning for import statements... -Found 156 imports to update -Updating... ✅ Done - -[3/4] Running full test suite -``` -npm run test -``` -⚠️ 3 integration tests failing - -[4/4] Fixing integration tests -Analyzing failures... -- auth.integration.test.ts: References old "User" model -- api.integration.test.ts: Old endpoint paths -- e2e.test.ts: Old component selectors - -Fixing... ✅ All tests passing - ---- - -### Final Results - -**Summary:** -- ✅ 47 files renamed successfully -- ✅ 423 code references updated -- ✅ 156 import statements updated -- ✅ Database migration complete -- ✅ All tests passing (234 tests) - -**Time Breakdown:** -- Phase 1 (parallel): 2h wall time (8h work) -- Phase 2 (sequential): 1h -- **Total: 3h wall time vs 9h sequential** -- **Time saved: 6 hours (67% faster)** - -**Changed Files:** -- Backend: 13 files -- Frontend: 18 files -- Tests: 6 files -- Config: 3 files -- Database: 1 migration -- Documentation: 6 files - -Ready to commit: -```bash -git add . -git commit -m "refactor: rename User to Account throughout codebase" -``` -``` - -### Multi-Concern Feature - -**Request:** -```bash -/feature --mode=orchestration "add file upload with virus scanning and optimization" -``` - -**Orchestration Mode Response:** -```markdown -## Orchestration Plan: File Upload Feature - -### Requirements Analysis -- File upload API -- Virus scanning (security) -- Image optimization (performance) -- Progress tracking (UX) -- Storage (infrastructure) - -### Parallel Workstreams - -**Stream 1: Security (Agent #1)** -- Integrate ClamAV for virus scanning -- Set up scanning service -- Add quarantine handling - -**Stream 2: Performance (Agent #2)** -- Image optimization (Sharp.js) -- Thumbnail generation -- Format conversion - -**Stream 3: Infrastructure (Agent #3)** -- S3 integration -- CDN configuration -- Storage policies - -**Stream 4: API (Agent #4)** -- Upload endpoints -- Progress tracking -- Error handling - -**Stream 5: Frontend (Agent #5)** -- Upload component -- Progress bar -- Preview functionality - -**Stream 6: Tests (Agent #6 - waits for above)** -- Integration tests -- Security tests -- Performance tests - ---- - -### Execution - -**Spawning 5 parallel agents...** - -Agent #1 (Security): 🔄 Implementing virus scanning... -Agent #2 (Performance): 🔄 Implementing image optimization... -Agent #3 (Infrastructure): 🔄 Setting up S3... -Agent #4 (API): 🔄 Creating endpoints... -Agent #5 (Frontend): 🔄 Building upload component... - ---- - -**[Progress Updates]** - -**After 1 hour:** - -Agent #1: ✅ Virus scanning complete -- ClamAV integrated -- Async scanning queue -- Quarantine handling - -Agent #2: ✅ Image optimization complete -- Sharp.js integrated -- Generates 3 sizes (thumb, medium, full) -- WebP conversion - -Agent #3: ✅ S3 setup complete -- Bucket configured -- CloudFront CDN -- Lifecycle policies - -Agent #4: 🔄 API 80% complete -- Upload endpoint done -- Progress tracking done -- ⏳ Error handling in progress - -Agent #5: 🔄 Frontend 60% complete -- Upload component done -- ⏳ Progress bar in progress -- ⏳ Preview pending - ---- - -**[After 2 hours: All Complete]** - -### Quality Gate: Integration Check - -**Integration points:** -1. API ↔ Security: ✅ Compatible -2. API ↔ Performance: ✅ Compatible -3. API ↔ Infrastructure: ✅ Compatible -4. Frontend ↔ API: ⚠️ Minor mismatch - -**Issue found:** -- Frontend expects progress in % (0-100) -- API returns bytes transferred -- **Resolution:** API updated to include percentage - -✅ Integration verified - ---- - -**Spawning Test Agent...** - -Agent #6 (Tests): 🔄 Generating tests... - -Tests created: -- Unit tests: 24 tests ✅ -- Integration tests: 12 tests ✅ -- Security tests: 8 tests ✅ -- Performance tests: 4 tests ✅ - -Total: 48 tests, all passing ✅ - ---- - -### Final Results - -**Feature Complete:** - -**Security (Agent #1):** -- ✅ Virus scanning on all uploads -- ✅ Quarantine for infected files -- ✅ Security logging - -**Performance (Agent #2):** -- ✅ Image optimization (60% size reduction) -- ✅ Multiple sizes generated -- ✅ WebP format support - -**Infrastructure (Agent #3):** -- ✅ S3 storage configured -- ✅ CDN for fast delivery -- ✅ Auto-cleanup old files - -**API (Agent #4):** -- ✅ POST /upload endpoint -- ✅ Real-time progress tracking -- ✅ Comprehensive error handling - -**Frontend (Agent #5):** -- ✅ Drag-and-drop upload -- ✅ Progress bar -- ✅ Image preview - -**Tests (Agent #6):** -- ✅ 48 tests covering all features -- ✅ Security scenarios tested -- ✅ Performance verified - -**Time Saved:** -- Sequential estimate: 10 hours -- Parallel actual: 2.5 hours -- **Saved: 7.5 hours (75% faster)** - -Ready for review! -``` - -### Research Synthesis - -**Request:** -```bash -/research --mode=orchestration "best state management for our React app" -``` - -**Orchestration Mode Response:** -```markdown -## Orchestration: State Management Research - -### Research Strategy - -Spawning 4 parallel research agents: - -Agent #1: Analyze current state management usage -Agent #2: Research Redux vs Zustand vs Jotai -Agent #3: Evaluate performance implications -Agent #4: Check team experience and learning curve - ---- - -**[Agents Running...]** - -Agent #1 (Current Analysis): 🔄 Analyzing codebase... -Agent #2 (Library Research): 🔄 Researching options... -Agent #3 (Performance): 🔄 Benchmarking... -Agent #4 (Team Assessment): 🔄 Surveying team... - ---- - -**[Results Collection]** - -### Agent #1: Current State Analysis - -**Findings:** -- 18 components using local useState -- 4 components prop-drilling 3+ levels -- No global state management -- Pain points: Cart state shared across 6 components - -**Complexity: LOW** -Current needs are simple, no complex state logic yet. - ---- - -### Agent #2: Library Research - -**Options Compared:** - -**Redux Toolkit** -- Industry standard, mature -- DevTools excellent -- Learning curve: High -- Boilerplate: Medium (with toolkit) -- Bundle size: 13KB - -**Zustand** -- Minimal API, simple -- Hooks-based -- Learning curve: Low -- Boilerplate: Minimal -- Bundle size: 3KB - -**Jotai** -- Atomic state management -- Recoil-like but simpler -- Learning curve: Medium -- Boilerplate: Minimal -- Bundle size: 5KB - ---- - -### Agent #3: Performance Analysis - -**Benchmark Results:** - -| Library | Render Time | Re-renders | Bundle Impact | -|---------|-------------|------------|---------------| -| Redux | 12ms | Optimized | +13KB | -| Zustand | 8ms | Very good | +3KB | -| Jotai | 9ms | Excellent | +5KB | - -**Recommendation:** All performant enough for our scale - ---- - -### Agent #4: Team Assessment - -**Team Survey Results:** -- Team size: 3 developers -- Redux experience: 1 developer -- Zustand experience: 0 developers -- React experience: All developers - -**Time to productivity estimate:** -- Redux: 1 week learning + 2 weeks proficiency -- Zustand: 1 day learning + 3 days proficiency -- Jotai: 2 days learning + 1 week proficiency - ---- - -### Synthesis: Orchestrator Analysis - -**Combining all findings:** - -**Current Needs (Agent #1):** -- Simple state sharing -- 6 components need cart state -- No complex async logic yet - -**Technical Fit (Agent #2):** -- Redux: Overpowered for current needs -- Zustand: Perfect fit for simple state -- Jotai: Good fit, slightly more complex - -**Performance (Agent #3):** -- All options performant -- Zustand has smallest bundle -- Not a differentiator - -**Team Fit (Agent #4):** -- Zustand fastest to learn -- Redux has more resources but longer ramp-up -- Jotai middle ground - -**Decision Matrix:** - -| Criteria | Weight | Redux | Zustand | Jotai | -|----------|--------|-------|---------|-------| -| Current needs fit | 30% | 6/10 | 10/10 | 9/10 | -| Learning curve | 25% | 5/10 | 10/10 | 7/10 | -| Performance | 20% | 8/10 | 10/10 | 9/10 | -| Scalability | 15% | 10/10 | 7/10 | 8/10 | -| Ecosystem | 10% | 10/10 | 6/10 | 6/10 | -| **TOTAL** | | **7.15** | **9.25** | **8.15** | - ---- - -### Recommendation: Zustand - -**Reasoning:** -1. **Perfect fit for current needs** (Agent #1 + Agent #2) - - Simple API for simple state - - No boilerplate overhead - -2. **Team can be productive immediately** (Agent #4) - - 1 day to learn vs 1 week for Redux - - Hooks-based (team already knows React hooks) - -3. **Best performance/size ratio** (Agent #3) - - 3KB vs 13KB (Redux) - - Fastest in benchmarks - -4. **Future flexibility** - - Can coexist with other solutions - - Easy to migrate from if needs grow - -**Caveats:** -- If app grows to Reddit-scale complexity, revisit Redux -- For now, Zustand is optimal choice - -**Next Steps:** -1. Prototype cart state with Zustand (2 hours) -2. Team review (1 hour) -3. If approved, refactor prop-drilling components (4 hours) - ---- - -**Research Time:** -- Parallel research: 1 hour -- Synthesis: 15 minutes -- **Total: 1.25 hours vs ~4 hours sequential** -``` - -## Spawn Command Integration - -The `/spawn` command is orchestration mode's primary tool: - -```bash -# Spawn background task -/spawn "research authentication patterns" - -# Check status -/spawn --list -# Output: -# Task #1: "research authentication patterns" [Running] 45% complete - -# Collect results -/spawn --collect -# Output: -# Task #1 complete. Results: [findings] - -# Spawn multiple -/spawn "analyze security" -/spawn "analyze performance" -/spawn "analyze UX" - -/spawn --collect # Waits for all, returns synthesized results -``` - -## Quality Gates - -Between parallel phases, orchestration mode enforces quality gates: - -```markdown -## Quality Gate: Phase 1 → Phase 2 - -### Completion Check -- [x] All agents completed -- [x] No critical errors -- [ ] All tests passing ← ⚠️ FAILED - -**Action:** Cannot proceed to Phase 2 until tests pass - -Spawning debugger agent... -✅ Tests fixed - -**Gate: PASSED** ✅ -Proceeding to Phase 2... -``` - -## Mode Activation - -```bash -# Session-wide orchestration -/mode orchestration - -# Single command -/feature --mode=orchestration "complex feature" -/plan --mode=orchestration "large refactor" - -# Explicit spawn usage -/spawn "task 1" -/spawn "task 2" -/spawn --collect -``` - -## Tips for Effective Orchestration - -### Identify Good Candidates - -**Good for orchestration:** -- Independent file modifications -- Research across different areas -- Test generation for multiple modules -- Parallel implementation streams - -**Bad for orchestration:** -- Single-file changes -- Highly coupled modifications -- Sequential dependencies -- Simple tasks - -### Structure Dependencies - -```markdown -# Clear parallel vs sequential -Phase 1 (Parallel): -- Database schema -- Service interfaces -- API contracts - -Phase 2 (Parallel, depends on Phase 1): -- Service implementations -- API implementations -- Frontend - -Phase 3 (Sequential, depends on Phase 2): -- Integration tests -- Documentation -``` - -### Monitor and Adjust - -```bash -# Check progress mid-execution -/spawn --list - -# If one agent is blocked, can spawn helper -/spawn "help debug agent #3 database connection issue" -``` - -## Comparison with Other Modes - -| Aspect | Orchestration | Implementation | Default | -|--------|---------------|----------------|---------| -| Task coordination | Primary focus | Single-threaded | Single-threaded | -| Parallelization | Automatic | No | No | -| Progress tracking | Detailed | Simple | None | -| Best for | Complex multi-part work | Clear single tasks | General use | - -## Configuration - -Orchestration mode is customizable in `.claude/modes/orchestration.md`: - -- Max parallel agents -- Quality gate strictness -- Progress update frequency -- Synthesis strategies - -## Related Modes - -- **Implementation Mode**: For single-threaded execution -- **Review Mode**: Can orchestrate multi-persona reviews -- **Deep Research Mode**: Can orchestrate multi-angle research - -## Related Commands - -- `/spawn` - Launch parallel tasks -- `/execute-plan` - Can use orchestration for parallel execution -- `/feature` - Complex features benefit from orchestration - -## Related Documentation - -- [Spawn Command](/claudekit/commands/spawn) -- [Parallel Agents Skill](/claudekit/skills/dispatching-parallel-agents) -- [Complex Workflows](/claudekit/guides/complex-workflows) diff --git a/website/src/content/docs/modes/overview.md b/website/src/content/docs/modes/overview.md deleted file mode 100644 index bbc6dec..0000000 --- a/website/src/content/docs/modes/overview.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Modes Overview -description: Understanding Claude Kit behavioral modes ---- - -# Behavioral Modes - -Modes adjust Claude's communication style, output format, and problem-solving approach. Choose the right mode for your task to optimize efficiency and results. - -## Quick Reference - -| Mode | Best For | Token Usage | Output Style | -|------|----------|-------------|--------------| -| [Default](/claudekit/modes/default) | General development tasks | Standard | Balanced explanation + code | -| [Brainstorm](/claudekit/modes/brainstorm) | Design, ideation, exploration | Higher | Questions, alternatives, comparisons | -| [Token-Efficient](/claudekit/modes/token-efficient) | High-volume, simple tasks | 30-70% less | Minimal prose, code-focused | -| [Deep Research](/claudekit/modes/deep-research) | Investigation, audits | Higher | Structured reports, citations | -| [Implementation](/claudekit/modes/implementation) | Executing clear plans | Lower | Code blocks, minimal explanation | -| [Review](/claudekit/modes/review) | Code review, QA | Standard | Categorized findings, actionable feedback | -| [Orchestration](/claudekit/modes/orchestration) | Complex multi-task coordination | Variable | Task delegation, progress tracking | - -## Mode Selection Guide - -### By Development Phase - -```mermaid -graph LR - A[New Feature] --> B[Brainstorm Mode] - B --> C[Plan Created] - C --> D[Implementation Mode] - D --> E[Code Complete] - E --> F[Review Mode] - F --> G[Ship] -``` - -### By Task Type - -| Task | Recommended Mode | Alternative | -|------|------------------|-------------| -| "How should I structure this?" | Brainstorm | Default | -| "Implement this feature" | Implementation | Default | -| "Fix this bug" | Default | Deep Research (if complex) | -| "Review this PR" | Review | Default + --persona=security | -| "Research this approach" | Deep Research | Brainstorm | -| "Generate 10 similar files" | Token-Efficient | Implementation | -| "Coordinate multi-file refactor" | Orchestration | Default | - -### By Team Experience - -| Experience Level | Recommended Modes | -|------------------|-------------------| -| Junior developers | Default, Brainstorm (for learning) | -| Senior developers | Token-Efficient, Implementation (for speed) | -| Mixed teams | Default, Review (for knowledge sharing) | - -## Switching Modes - -### Session-Wide Mode Change - -```bash -/mode brainstorm # All subsequent commands use brainstorm mode -/mode token-efficient # Switch to token-efficient for the session -/mode default # Return to standard behavior -``` - -### Single Command Override - -```bash -/plan --mode=brainstorm "new feature" -/fix --format=concise "error message" -/review --mode=review --persona=security src/auth/ -``` - -### Mode Combinations - -Some modes work well together via flags: - -```bash -# Deep research with concise output -/research --mode=deep-research --format=concise [topic] - -# Implementation with checkpoints -/execute-plan --mode=implementation --checkpoint [file] - -# Brainstorm with saved output -/brainstorm --mode=brainstorm --save=plans/design.md [topic] -``` - -## Understanding Mode Behavior - -Each mode modifies three key aspects: - -### 1. Communication Style -- **Verbose modes** (Brainstorm, Deep Research): More questions, explanations, alternatives -- **Concise modes** (Token-Efficient, Implementation): Direct answers, minimal prose -- **Balanced modes** (Default, Review): Clear but not excessive - -### 2. Problem-Solving Approach -- **Exploratory** (Brainstorm, Deep Research): Consider many options, delay decisions -- **Decisive** (Implementation, Token-Efficient): Make reasonable defaults, execute -- **Critical** (Review): Question assumptions, find issues - -### 3. Output Format -- **Structured reports** (Deep Research, Review): Categorized, formatted findings -- **Code-focused** (Implementation, Token-Efficient): Minimal text, maximum code -- **Discussion-oriented** (Brainstorm, Default): Balanced code and explanation - -## Mode Feature Matrix - -| Feature | Default | Brainstorm | Token-Efficient | Deep Research | Implementation | Review | Orchestration | -|---------|---------|------------|-----------------|---------------|----------------|--------|---------------| -| Ask clarifying questions | Sometimes | Frequently | Rarely | Sometimes | Rarely | Sometimes | Sometimes | -| Present alternatives | Sometimes | Always | No | Sometimes | No | Sometimes | No | -| Detailed explanations | Yes | Yes | No | Yes | No | Yes | Moderate | -| Code comments | Standard | Verbose | Minimal | Standard | Minimal | Standard | Standard | -| Progress updates | No | No | No | Yes | Yes | No | Yes | -| Confidence levels | No | No | No | Yes | No | No | No | -| File citations | No | No | No | Yes | No | Yes | No | -| Task parallelization | No | No | No | No | No | No | Yes | - -## Best Practices - -### Start Broad, Then Focus -```bash -# 1. Explore options -/brainstorm "authentication approach" - -# 2. Plan implementation -/plan --mode=default "implement OAuth2" - -# 3. Execute efficiently -/execute-plan --mode=implementation plan.md - -# 4. Review thoroughly -/review --mode=review src/auth/ -``` - -### Match Mode to Iteration -- **First iteration**: Use Brainstorm or Default to explore -- **Subsequent iterations**: Use Implementation or Token-Efficient for speed -- **Final iteration**: Use Review to catch issues - -### Know When to Switch -- Stuck on implementation? → Switch to Brainstorm -- Plan is clear? → Switch to Implementation -- Need to save costs? → Switch to Token-Efficient -- Complex bug? → Switch to Deep Research - -## Common Patterns - -### Feature Development -```bash -/mode brainstorm -/brainstorm "user profile feature" -# Explore options, make decisions - -/mode implementation -/feature "user profile with avatar upload" -# Execute the plan - -/mode review -/review src/features/profile/ -# Quality check before merge -``` - -### Bug Investigation -```bash -/mode deep-research -/fix --depth=5 "memory leak in worker process" -# Thorough investigation - -/mode implementation -# Apply the fix - -/mode review -/review --persona=performance src/workers/ -# Verify fix and performance -``` - -### Batch Operations -```bash -/mode token-efficient -/test --format=ultra src/services/*.ts -# Generate tests for all services efficiently -``` - -## Custom Mode Configuration - -Advanced users can customize mode behavior in `.claude/modes/`. Each mode is defined in a markdown file that specifies: - -- Communication patterns -- Output formats -- Problem-solving approaches -- Activation conditions - -See individual mode pages for detailed behavior specifications. - -## Related Documentation - -- [Commands Reference](/claudekit/commands/overview) - Using modes with commands -- [Flags & Options](/claudekit/advanced/flags) - Mode-related flags -- [Token Optimization](/claudekit/optimization/token-efficient) - Cost-saving strategies diff --git a/website/src/content/docs/modes/review.md b/website/src/content/docs/modes/review.md deleted file mode 100644 index 7059cc1..0000000 --- a/website/src/content/docs/modes/review.md +++ /dev/null @@ -1,984 +0,0 @@ ---- -title: Review Mode -description: Critical analysis mode for code review and quality assessment ---- - -# Review Mode - -## Overview - -Review mode optimizes for critical analysis, finding issues, and providing actionable feedback. It emphasizes thorough examination, categorized findings, and constructive suggestions for improvement. - -This mode produces structured reviews with severity levels, specific line references, and clear recommendations. - -## When to Use - -Review mode is ideal for: - -- **Code reviews** - Pull request reviews, pre-merge checks -- **Security audits** - Finding vulnerabilities and security issues -- **Performance reviews** - Identifying optimization opportunities -- **Pre-merge checks** - Final quality gate before merging -- **Quality assessments** - Evaluating code quality and maintainability -- **Architecture reviews** - Assessing structural decisions - -## Behavior Changes - -### Communication Style - -**Direct and constructive:** -- Direct feedback without sugar-coating -- Prioritized findings (critical first) -- Constructive criticism with solutions -- Specific, actionable suggestions -- Line-specific comments - -**Example:** -```markdown -## Code Review: user-service.ts - -### Critical Issues 🔴 - -**Issue 1: SQL Injection Vulnerability (Line 45)** -- **Problem:** User input concatenated directly into SQL query -- **Risk:** Attackers can execute arbitrary SQL commands -- **Fix:** - ```typescript - // Before (UNSAFE) - const query = `SELECT * FROM users WHERE email = '${email}'`; - - // After (SAFE) - const query = 'SELECT * FROM users WHERE email = $1'; - const result = await db.query(query, [email]); - ``` - -### Verdict -❌ Block merge - 1 critical issue must be fixed -``` - -### Problem-Solving Approach - -- **Look for issues first** - Critical eye, not just validation -- **Question assumptions** - Challenge design decisions -- **Check edge cases** - What could go wrong? -- **Verify against standards** - Compliance with best practices - -### Output Format - -- Categorized findings by severity -- Severity levels (Critical, Important, Minor, Nitpick) -- Line-specific comments -- Code examples for fixes -- Merge decision at end - -## Severity Levels - -| Level | Icon | Description | Action Required | -|-------|------|-------------|-----------------| -| **Critical** | 🔴 | Bugs, security issues, data loss risks | Must fix before merge | -| **Important** | 🟠 | Code smells, performance issues, bad practices | Should fix before merge | -| **Minor** | 🟡 | Style issues, naming, minor improvements | Consider fixing | -| **Nitpick** | ⚪ | Personal preferences, minor style | Optional | - -## Review Categories - -Review mode examines code across multiple dimensions: - -| Category | Focus Areas | -|----------|-------------| -| **Correctness** | Does it work? Handle edge cases? Proper error handling? | -| **Security** | Vulnerabilities? Input validation? Auth/authz? Data exposure? | -| **Performance** | Efficiency? Scalability? N+1 queries? Resource usage? | -| **Maintainability** | Readability? Complexity? Documentation? Testability? | -| **Testing** | Test coverage? Test quality? Edge cases tested? | -| **Standards** | Style guide compliance? Best practices? Conventions? | - -## Examples - -### Code Review - -**Request:** -```bash -/review --mode=review src/services/payment-service.ts -``` - -**Review Mode Response:** -```markdown -## Code Review: payment-service.ts - -### Summary -Payment service with Stripe integration. Found 2 critical, 3 important, -and 4 minor issues. Not ready for production. - ---- - -### Critical Issues 🔴 - -**1. API Key in Logs (Line 45)** -```typescript -// Line 45 - UNSAFE -logger.error(`Payment failed for key ${stripeKey}`, error); -``` - -**Problem:** Stripe API key exposed in application logs - -**Risk:** -- Anyone with log access gets full payment system access -- Key could leak via log aggregation services -- Violates PCI compliance - -**Fix:** -```typescript -logger.error('Payment failed', { - error: error.message, - customerId: payment.customerId, - // Never log the API key -}); -``` - ---- - -**2. No Timeout on API Calls (Line 78)** -```typescript -// Line 78 - PROBLEMATIC -const result = await stripe.charges.create(chargeData); -``` - -**Problem:** External API call with no timeout - -**Risk:** -- Can hang indefinitely if Stripe is down -- Blocks server resources -- Poor user experience - -**Fix:** -```typescript -const result = await Promise.race([ - stripe.charges.create(chargeData), - new Promise((_, reject) => - setTimeout(() => reject(new Error('Timeout')), 30000) - ) -]); -``` - -Or use axios with timeout config. - ---- - -### Important Issues 🟠 - -**3. No Retry Logic (Line 78)** - -**Problem:** Single attempt at payment, no retries on transient failures - -**Impact:** -- Network blips cause failed payments -- Stripe rate limits not handled -- Lost revenue - -**Suggestion:** -```typescript -import retry from 'async-retry'; - -const result = await retry( - async () => stripe.charges.create(chargeData), - { - retries: 3, - minTimeout: 1000, - onRetry: (err, attempt) => { - logger.warn(`Payment retry ${attempt}`, { error: err.message }); - } - } -); -``` - ---- - -**4. Magic Numbers (Line 12, 34, 67)** -```typescript -if (amount < 50) throw new Error('Minimum $0.50'); // Line 12 -await delay(1000); // Line 34 -const fee = amount * 0.029 + 30; // Line 67 -``` - -**Problem:** Hardcoded values with no explanation - -**Fix:** Extract to named constants -```typescript -const MIN_CHARGE_CENTS = 50; -const RETRY_DELAY_MS = 1000; -const STRIPE_FEE_PERCENT = 0.029; -const STRIPE_FEE_FIXED_CENTS = 30; - -if (amount < MIN_CHARGE_CENTS) { - throw new Error(`Minimum charge: $${MIN_CHARGE_CENTS / 100}`); -} -``` - ---- - -**5. Insufficient Error Handling (Line 89)** -```typescript -} catch (error) { - throw new Error('Payment failed'); -} -``` - -**Problem:** Generic error loses valuable context - -**Impact:** -- Can't distinguish card decline vs network error vs server error -- Makes debugging difficult -- Poor user experience (unhelpful error message) - -**Fix:** -```typescript -} catch (error) { - if (error.type === 'StripeCardError') { - throw new PaymentError('Card declined', { - code: error.code, - message: error.message - }); - } else if (error.type === 'StripeRateLimitError') { - throw new PaymentError('Too many requests', { retry: true }); - } else { - logger.error('Payment processing error', error); - throw new PaymentError('Payment system unavailable'); - } -} -``` - ---- - -### Minor Issues 🟡 - -**6. Missing JSDoc (All public methods)** -- Public API should be documented -- Add JSDoc with param descriptions, return types, examples - -**7. Inconsistent Naming (Line 23 vs 56)** -```typescript -const chargeData = {...}; // Line 23 -const paymentData = {...}; // Line 56 (same thing) -``` -Pick one convention and stick to it. - -**8. Console.log Still Present (Line 101)** -```typescript -console.log('Debug payment:', payment); -``` -Remove debug logging or use proper logger. - -**9. No Input Validation (Line 15)** -```typescript -async createCharge(amount: number, customerId: string) { - // No validation that amount is positive, customerId is valid format -} -``` - -Add validation: -```typescript -if (amount <= 0) throw new Error('Amount must be positive'); -if (!customerId.startsWith('cus_')) throw new Error('Invalid customer ID'); -``` - ---- - -### Positive Notes ✅ - -**Good practices observed:** -- ✅ Using async/await consistently -- ✅ TypeScript types defined -- ✅ Error handling structure present (just needs improvement) -- ✅ Modular function design -- ✅ Test file exists - ---- - -### Test Coverage Review - -Checked `payment-service.test.ts`: - -**Coverage:** -- ✅ Successful payment flow tested -- ✅ Card decline tested -- ❌ Network errors not tested -- ❌ Timeout scenarios not tested -- ❌ Retry logic not tested (doesn't exist yet) - -**Recommendation:** Add tests for error scenarios once retry/timeout logic added. - ---- - -### Security Checklist - -- [x] Input validation - Mostly missing -- [x] API key handling - ⚠️ Logged in errors (critical issue #1) -- [x] Error messages - ⚠️ Too generic (important issue #5) -- [x] Rate limiting - ❌ Not implemented -- [x] PCI compliance - ⚠️ Key logging violates this - ---- - -### Performance Checklist - -- [x] Async/await used - ✅ Yes -- [x] N+1 queries - ✅ N/A (external API) -- [x] Caching - ❌ Could cache customer data -- [x] Timeout handling - ❌ Missing (critical issue #2) - ---- - -### Verdict - -**❌ Block Merge** - -**Issues requiring fixes:** -- 🔴 2 Critical issues (API key logging, no timeout) -- 🟠 3 Important issues (no retry, magic numbers, poor error handling) - -**Estimated fix time:** 3-4 hours - -**Recommended next steps:** -1. Fix critical issues immediately (1 hour) -2. Add timeout and retry logic (2 hours) -3. Extract constants and improve errors (1 hour) -4. Add missing tests (2 hours) -5. Re-review after fixes - ---- - -### Comparison to Standards - -Checked against: -- ✅ TypeScript style guide - Mostly compliant -- ⚠️ Error handling patterns - Needs improvement -- ❌ Security best practices - Violates (key logging) -- ⚠️ PCI DSS requirements - Non-compliant (key logging) -``` - -### Security-Focused Review - -**Request:** -```bash -/review --mode=review --persona=security src/api/auth.ts -``` - -**Review Mode Response:** -```markdown -## Security Review: auth.ts - -Persona: Security Auditor -Standards: OWASP Top 10 (2021), CWE Top 25 - ---- - -### Critical Security Issues 🔴 - -**1. Hardcoded JWT Secret (Line 8)** -```typescript -const JWT_SECRET = 'my-secret-key-123'; -``` - -**Vulnerability:** CWE-798 (Hardcoded Credentials) -**OWASP:** A07:2021 – Identification and Authentication Failures - -**Risk:** -- Secret in source control = everyone has it -- Can forge any JWT token -- Complete authentication bypass - -**Exploitation:** -```bash -# Attacker can create admin token -jwt.sign({ userId: 1, role: 'admin' }, 'my-secret-key-123') -``` - -**Fix:** -```typescript -const JWT_SECRET = process.env.JWT_SECRET; -if (!JWT_SECRET) { - throw new Error('JWT_SECRET environment variable required'); -} -``` - ---- - -**2. No Rate Limiting on Login (Line 45)** - -**Vulnerability:** CWE-307 (Improper Authentication Attempts) -**OWASP:** A07:2021 – Identification and Authentication Failures - -**Risk:** -- Brute force attacks viable -- Credential stuffing attacks -- No account lockout - -**Exploitation:** -```bash -# Attacker can try unlimited passwords -for pwd in $(cat passwords.txt); do - curl -X POST /login -d "{\"password\":\"$pwd\"}" -done -``` - -**Fix:** -```typescript -import rateLimit from 'express-rate-limit'; - -const loginLimiter = rateLimit({ - windowMs: 15 * 60 * 1000, - max: 5, - message: 'Too many login attempts' -}); - -router.post('/login', loginLimiter, loginHandler); -``` - ---- - -**3. Password in Error Message (Line 67)** -```typescript -logger.error(`Login failed for ${email} with password ${password}`); -``` - -**Vulnerability:** CWE-209 (Information Exposure Through Error Message) -**OWASP:** A04:2021 – Insecure Design - -**Risk:** Passwords logged and visible to anyone with log access - -**Fix:** -```typescript -logger.error(`Login failed for ${email}`); -// Never log passwords -``` - ---- - -### Important Security Issues 🟠 - -**4. Weak Password Requirements (Line 23)** -```typescript -if (password.length < 6) { - return res.status(400).json({ error: 'Password too short' }); -} -``` - -**Vulnerability:** CWE-521 (Weak Password Requirements) - -**Risk:** -- 6 characters easily cracked -- No complexity requirements -- Common passwords allowed - -**Fix:** -```typescript -import { passwordStrength } from 'check-password-strength'; - -const strength = passwordStrength(password); -if (strength.value === 'Weak' || strength.value === 'Too weak') { - return res.status(400).json({ - error: 'Password must be at least 12 characters with uppercase, lowercase, number, and symbol' - }); -} -``` - ---- - -**5. JWT Never Expires (Line 34)** -```typescript -const token = jwt.sign({ userId: user.id }, JWT_SECRET); -``` - -**Vulnerability:** CWE-613 (Insufficient Session Expiration) - -**Risk:** -- Stolen token valid forever -- Can't revoke access -- Compromised token = permanent access - -**Fix:** -```typescript -const token = jwt.sign( - { userId: user.id }, - JWT_SECRET, - { expiresIn: '1h' } -); -``` - ---- - -### Minor Security Issues 🟡 - -**6. No HTTPS Enforcement** -- Check if reverse proxy handles HTTPS -- Add HTTP → HTTPS redirect if not - -**7. No CORS Configuration** -- Wide-open CORS is security risk -- Restrict to known origins - -**8. Timing Attack on Password Compare** -- Use constant-time comparison -- bcrypt.compare() is already safe (good!) - ---- - -### Security Checklist (OWASP Top 10) - -- [x] A01:2021 – Broken Access Control - - ✅ Auth middleware checks tokens - - ⚠️ Token never expires (issue #5) - -- [x] A02:2021 – Cryptographic Failures - - ✅ Passwords hashed with bcrypt - - 🔴 Hardcoded secret (issue #1) - -- [x] A03:2021 – Injection - - ✅ Using parameterized queries - - ✅ No SQL injection found - -- [x] A04:2021 – Insecure Design - - 🔴 Password in logs (issue #3) - - 🟠 Weak password policy (issue #4) - -- [x] A05:2021 – Security Misconfiguration - - ⚠️ No HTTPS enforcement (issue #6) - - ⚠️ No CORS policy (issue #7) - -- [x] A07:2021 – Identification and Authentication Failures - - 🔴 No rate limiting (issue #2) - - 🟠 Tokens never expire (issue #5) - ---- - -### Verdict - -**❌ NOT PRODUCTION-READY** - -**Critical vulnerabilities:** 3 -**Estimated risk level:** HIGH - -**Must fix before any deployment:** -1. Remove hardcoded secret -2. Add rate limiting -3. Remove password from logs - -**Recommended timeline:** -- Critical fixes: Today (2-3 hours) -- Important fixes: This week (4-5 hours) -- Full security audit: Next sprint - ---- - -### Recommended Security Additions - -Beyond fixing issues: - -1. **Add 2FA support** - - Time-based OTP (TOTP) - - Backup codes - -2. **Implement password reset** - - Secure token generation - - Time-limited reset links - - Email verification - -3. **Add security headers** - ```typescript - import helmet from 'helmet'; - app.use(helmet()); - ``` - -4. **Set up security monitoring** - - Log failed login attempts - - Alert on suspicious patterns - - Track token usage - -5. **Regular security audits** - - Automated: npm audit, Snyk - - Manual: Code review - - Professional: Penetration testing -``` - -### Performance-Focused Review - -**Request:** -```bash -/review --persona=performance src/api/posts.ts -``` - -**Review Mode Response:** -```markdown -## Performance Review: posts.ts - -Persona: Performance Engineer -Focus: Response time, resource usage, scalability - ---- - -### Critical Performance Issues 🔴 - -**1. N+1 Query Problem (Line 45-55)** - -**Current code:** -```typescript -const posts = await db.posts.findAll(); -for (const post of posts) { - post.author = await db.users.findById(post.authorId); - post.comments = await db.comments.findByPostId(post.id); -} -``` - -**Problem:** -- 100 posts = 1 + 100 + 100 = 201 database queries -- Each query: ~10ms -- Total: ~2,000ms just for queries - -**Impact:** Page load takes 2+ seconds - -**Fix:** -```typescript -const posts = await db.posts.findAll({ - include: [ - { model: db.users, as: 'author' }, - { model: db.comments, as: 'comments' } - ] -}); -// Now: 1 query with JOINs, ~50ms -``` - -**Expected improvement:** 95% faster (2,000ms → 100ms) - ---- - -### Important Performance Issues 🟠 - -**2. No Pagination (Line 23)** -```typescript -router.get('/posts', async (req, res) => { - const posts = await db.posts.findAll(); - res.json(posts); -}); -``` - -**Problem:** -- Returns ALL posts (currently 1,000) -- 2.3KB per post = 2.3MB response -- Mobile users download entire dataset - -**Fix:** -```typescript -const limit = Math.min(parseInt(req.query.limit) || 10, 100); -const offset = parseInt(req.query.offset) || 0; - -const posts = await db.posts.findAll({ limit, offset }); -const total = await db.posts.count(); - -res.json({ posts, total, limit, offset }); -``` - -**Expected improvement:** 99% smaller response (2.3MB → 23KB) - ---- - -**3. No Caching (Line 23)** - -**Problem:** -- Every request hits database -- Posts don't change frequently -- Redundant computation - -**Analysis:** -- Checked git history: Posts updated 2-3 times/hour -- Could cache for 5-10 minutes -- 95% of requests could be cache hits - -**Fix:** -```typescript -const cacheKey = `posts:${limit}:${offset}`; -let posts = await redis.get(cacheKey); - -if (!posts) { - posts = await db.posts.findAll({...}); - await redis.setex(cacheKey, 300, JSON.stringify(posts)); -} -``` - -**Expected improvement:** 90% faster for cache hits - ---- - -### Minor Performance Issues 🟡 - -**4. Inefficient Filtering (Line 78)** -```typescript -const filtered = posts.filter(p => p.published); -``` - -**Problem:** Filtering in application, not database - -**Fix:** -```typescript -const posts = await db.posts.findAll({ - where: { published: true } -}); -``` - ---- - -**5. No Compression (Response Headers)** - -**Problem:** Large JSON responses not compressed - -**Fix:** -```typescript -import compression from 'compression'; -app.use(compression()); -``` - -**Expected improvement:** 60-80% smaller responses - ---- - -**6. Synchronous Processing (Line 89)** -```typescript -for (const post of posts) { - await analytics.track(post.id); // Blocks response -} -``` - -**Problem:** Analytics tracking blocks response - -**Fix:** -```typescript -// Fire and forget -Promise.all(posts.map(p => analytics.track(p.id))).catch(err => - logger.error('Analytics error', err) -); -// or better: queue for background processing -``` - ---- - -### Performance Metrics - -**Current Performance:** -- Response time: 2,347ms (p95) -- Payload size: 2.3MB uncompressed -- Database queries: 201 per request -- Cache hit rate: 0% (no cache) - -**After Fixes:** -- Response time: ~120ms (p95) -- Payload size: ~23KB compressed -- Database queries: 1 per request -- Cache hit rate: ~90% (estimated) - -**Total improvement: 95% faster, 99% less bandwidth** - ---- - -### Scalability Analysis - -**Current capacity:** -- Server: 8 concurrent requests max -- Database: 100 connections, saturates quickly -- Bottleneck: N+1 queries - -**After fixes:** -- Server: 100+ concurrent requests -- Database: Minimal load with caching -- Bottleneck: Cache size (manageable) - ---- - -### Load Test Recommendations - -```bash -# Before fixes -ab -n 1000 -c 10 http://localhost:3000/api/posts -# Expect: Many failures, high latency - -# After fixes -ab -n 1000 -c 50 http://localhost:3000/api/posts -# Should handle gracefully -``` - ---- - -### Verdict - -**🟠 Needs Performance Work** - -Not currently scalable beyond 10-20 concurrent users. - -**Priority fixes:** -1. Fix N+1 queries (critical for any load) -2. Add pagination (critical for mobile) -3. Implement caching (high impact) - -**Estimated fix time:** 1 day - ---- - -### Performance Checklist - -- [ ] Database queries optimized -- [ ] Pagination implemented -- [ ] Caching layer added -- [ ] Response compression enabled -- [ ] No blocking operations in request path -- [ ] Load tested - -**Recommendation:** Fix N+1 and pagination before launch. -``` - -## Review Personas - -Use `--persona` flag to focus the review: - -| Persona | Focus | Best For | -|---------|-------|----------| -| `security` | OWASP Top 10, vulnerabilities, auth | Security-critical code | -| `performance` | Efficiency, queries, caching | High-traffic endpoints | -| `architecture` | Patterns, coupling, design | Structural decisions | -| `testing` | Coverage, quality, edge cases | Test review | - -**Example:** -```bash -/review --persona=security src/auth/ -/review --persona=performance src/api/ -``` - -## Mode Activation - -```bash -# Session-wide review mode -/mode review - -# All reviews now use critical analysis -/review src/services/ -/review src/api/ - -# Single command with review mode -/review --mode=review src/payment/ - -# With specific persona -/review --mode=review --persona=security src/auth/ -``` - -## Tips for Effective Reviews - -### Prepare the Code - -Before reviewing: -1. Ensure tests pass -2. Run linter -3. Check for obvious issues -4. Have context ready - -### Focus Reviews - -```bash -# Too broad - hard to review thoroughly -/review src/ - -# Better - focused review -/review src/services/payment-service.ts -/review src/api/auth.ts --persona=security -``` - -### Progressive Review - -```bash -# Quick first pass -/review --depth=2 src/new-feature/ - -# Deep dive on concerning areas -/review --depth=5 --persona=security src/new-feature/auth.ts -``` - -### Combine with Other Modes - -```bash -# Review, then fix -/mode review -/review src/feature/ -# Identify issues - -/mode implementation -/fix "issue 1" -/fix "issue 2" - -/mode review -/review src/feature/ -# Verify fixes -``` - -## Checklist Template - -Standard checklist used in reviews: - -```markdown -### Pre-Review -- [ ] Tests pass -- [ ] Lint clean -- [ ] No console.logs -- [ ] Dependencies updated - -### Code Quality -- [ ] Readable and maintainable -- [ ] No code smells -- [ ] Proper error handling -- [ ] Edge cases considered - -### Security -- [ ] Input validation -- [ ] No hardcoded secrets -- [ ] Auth/authz correct -- [ ] No security warnings - -### Performance -- [ ] No N+1 queries -- [ ] Efficient algorithms -- [ ] Proper indexing -- [ ] No memory leaks - -### Testing -- [ ] Tests cover new code -- [ ] Edge cases tested -- [ ] Error scenarios tested -- [ ] Coverage maintained -``` - -## Comparison with Other Modes - -| Aspect | Review | Deep Research | Default | -|--------|--------|---------------|---------| -| Critical analysis | High | Medium | Low | -| Finding issues | Primary goal | Secondary | Incidental | -| Evidence required | Yes | Always | Sometimes | -| Actionable feedback | Always | Sometimes | Sometimes | -| Best for | Code review | Investigation | General use | - -## Configuration - -Review mode is customizable in `.claude/modes/review.md`: - -- Severity thresholds -- Checklist items -- Required categories -- Verdict criteria - -## Related Modes - -- **Deep Research Mode**: For evidence-based investigation -- **Default Mode**: For less critical review -- **Security Auditor Agent**: Specialized security reviews - -## Related Documentation - -- [Code Review Guide](/claudekit/guides/code-review) -- [Security Best Practices](/claudekit/guides/security) -- [Review Command](/claudekit/commands/review) diff --git a/website/src/content/docs/modes/token-efficient.md b/website/src/content/docs/modes/token-efficient.md deleted file mode 100644 index 224332e..0000000 --- a/website/src/content/docs/modes/token-efficient.md +++ /dev/null @@ -1,544 +0,0 @@ ---- -title: Token-Efficient Mode -description: Cost optimization mode with minimal prose and maximum code ---- - -# Token-Efficient Mode - -## Overview - -Token-efficient mode optimizes for cost savings by reducing output verbosity while maintaining accuracy. It can reduce token usage by 30-70% depending on the task type. - -This mode produces compressed, concise outputs with minimal explanation - perfect for high-volume sessions, simple tasks, or when cost is a primary concern. - -## When to Use - -Token-efficient mode is ideal for: - -- **High-volume sessions** - Many similar tasks in one session -- **Simple, clear tasks** - Well-defined work that doesn't need explanation -- **Cost-sensitive projects** - When minimizing API costs matters -- **Repeated operations** - Batch file generation, similar edits -- **Quick iterations** - Fast back-and-forth during development - -## Behavior Changes - -### Communication Style - -**Minimal explanations:** -- No conversational filler or preambles -- Direct answers only -- Skip obvious context -- Assume developer competence - -**Standard Mode Example:** -``` -I'll help you fix this bug. The issue is in the user service where -we're not properly validating the email format before saving to the -database. Here's the fix: - -[code block with detailed comments] - -This change adds email validation using a regex pattern that checks -for a valid email format before proceeding with the save operation. -``` - -**Token-Efficient Mode Example:** -``` -Fix: Add email validation - -[code block with minimal comments] -``` - -### Problem-Solving Approach - -- Jump directly to solutions -- Assume competence - no hand-holding -- Skip basic explanations -- Reference documentation instead of explaining -- Make reasonable defaults without discussion - -### Output Format - -- Code blocks without surrounding prose -- Abbreviated inline comments -- Terse commit messages -- Bullet points instead of paragraphs -- No "I'll help you" preambles - -## Token Savings Breakdown - -| Technique | Token Savings | Trade-off | -|-----------|---------------|-----------| -| Skip preambles | 20-30% | Less context setting | -| Code-only responses | 40-50% | No explanation | -| Abbreviated comments | 10-15% | Less documentation | -| Reference over explain | 30-40% | Requires looking up docs | -| Combined (Ultra mode) | 60-70% | Minimal guidance | - -## Examples - -### Bug Fix - -**Request:** -```bash -/fix --format=concise "null pointer in user.ts line 42" -``` - -**Token-Efficient Response:** -```typescript -// user.ts:42 -if (!user) return null; -// Before: user.name (crashes when null) -// After: user?.name ?? 'Unknown' -``` - -Test: `npm test -- --grep "null user"` - ---- - -**Compare to Standard Mode:** -```markdown -I found the null pointer issue. When user is null, we're trying to -access the name property which causes a crash. Here's the fix: - -```typescript -// user.ts:42 -if (!user) { - return null; -} - -// Use optional chaining to safely access name -const userName = user?.name ?? 'Unknown'; -``` - -This uses TypeScript's optional chaining operator (?.) which safely -accesses properties on potentially null objects. If user is null, -it returns undefined instead of crashing. The nullish coalescing -operator (??) provides a fallback value of 'Unknown'. - -To test this fix, run: -```bash -npm test -- --grep "null user" -``` -``` - -Token savings: ~65% - -### Feature Implementation - -**Request:** -```bash -/feature --format=ultra "add user avatar upload" -``` - -**Token-Efficient Response:** -```typescript -// src/api/user.ts -router.post('/avatar', upload.single('avatar'), async (req, res) => { - const file = req.file; - if (!file) return res.status(400).json({ error: 'No file' }); - - const url = await s3.upload(file); - await db.users.update(req.user.id, { avatarUrl: url }); - - res.json({ avatarUrl: url }); -}); - -// src/middleware/upload.ts -import multer from 'multer'; -export const upload = multer({ - limits: { fileSize: 5 * 1024 * 1024 }, // 5MB - fileFilter: (req, file, cb) => { - if (!file.mimetype.startsWith('image/')) { - return cb(new Error('Images only')); - } - cb(null, true); - } -}); -``` - -Test: `curl -F "avatar=@test.jpg" http://localhost:3000/api/avatar` - ---- - -**Compare to Standard Mode:** -```markdown -I'll implement avatar upload functionality with file size limits and -type validation. - -## Implementation Plan -1. Add multer middleware for file uploads -2. Create upload endpoint -3. Validate file type and size -4. Upload to S3 -5. Update user record - -Let me create the necessary files: - -**src/api/user.ts** -```typescript -import { Router } from 'express'; -import { upload } from '../middleware/upload'; -import { s3Service } from '../services/s3'; -import { db } from '../db'; - -const router = Router(); - -// Avatar upload endpoint -// Accepts: multipart/form-data with 'avatar' field -// Returns: { avatarUrl: string } -router.post('/avatar', upload.single('avatar'), async (req, res) => { - const file = req.file; - - // Validate file exists - if (!file) { - return res.status(400).json({ error: 'No file provided' }); - } - - // Upload to S3 and get URL - const url = await s3Service.upload(file); - - // Update user's avatar URL in database - await db.users.update(req.user.id, { avatarUrl: url }); - - res.json({ avatarUrl: url }); -}); - -export default router; -``` - -**src/middleware/upload.ts** -```typescript -import multer from 'multer'; - -// Configure multer with size and type restrictions -export const upload = multer({ - // Limit file size to 5MB - limits: { - fileSize: 5 * 1024 * 1024 - }, - - // Only allow image files - fileFilter: (req, file, cb) => { - if (!file.mimetype.startsWith('image/')) { - return cb(new Error('Only image files allowed')); - } - cb(null, true); - } -}); -``` - -This implementation: -- Uses multer for handling multipart form data -- Restricts uploads to images only (JPEG, PNG, etc.) -- Enforces a 5MB file size limit -- Uploads to S3 for persistent storage -- Updates the user's database record with the new avatar URL - -To test the endpoint: -```bash -curl -F "avatar=@test.jpg" http://localhost:3000/api/avatar -``` -``` - -Token savings: ~70% - -### Code Review - -**Request:** -```bash -/review --format=concise src/services/payment.ts -``` - -**Token-Efficient Response:** -```markdown -## payment.ts - -**Critical:** -- Line 45: API key in logs → Remove from error message -- Line 78: No timeout → Add 30s timeout - -**Important:** -- Line 12: Magic number 3 → Extract constant `MAX_RETRIES` -- Line 56: No retry backoff → Add exponential backoff - -**Minor:** -- Inconsistent error handling -- Missing JSDoc on public methods - -Tests pass. Fix critical before merge. -``` - ---- - -**Compare to Standard Mode:** -```markdown -## Code Review: payment-service.ts - -I've reviewed the payment service code. Here's what I found: - -### Critical Issues 🔴 - -**Issue 1: API Key Exposure in Logs (Line 45)** -- **Problem**: The error handler logs the full API key when payment - fails, which exposes sensitive credentials in application logs. -- **Risk**: Anyone with log access can see the API key -- **Fix**: Remove the API key from the error message: - ```typescript - // Before - logger.error(`Payment failed with key ${apiKey}`, error); - - // After - logger.error('Payment failed', { error: error.message }); - ``` - -**Issue 2: No Timeout on API Calls (Line 78)** -- **Problem**: The payment API call has no timeout, which means it - could hang indefinitely if the payment provider is down. -- **Risk**: Could cause your entire application to hang -- **Fix**: Add a 30-second timeout: - ```typescript - const response = await axios.post(url, data, { - timeout: 30000 // 30 seconds - }); - ``` - -### Important Issues 🟠 - -**Issue 3: Magic Number for Retries (Line 12)** -- **Problem**: The number 3 is hardcoded for retry attempts -- **Fix**: Extract to a named constant for clarity: - ```typescript - const MAX_RETRIES = 3; - ``` - -... [more detailed explanations] - -### Positive Notes ✅ -- Good error handling structure overall -- Tests cover the main payment flows -- Clear function names and organization - -### Recommendation -This code needs changes before merging. The critical issues must be -fixed, and I recommend addressing the important issues as well for -better reliability. -``` - -Token savings: ~75% - -## Format Levels - -Token-efficient mode has two levels: - -### Concise (`--format=concise`) - -**Token savings: 30-40%** - -- Reduced explanations but still present -- Standard code with fewer comments -- Brief context setting -- Short examples - -**Use when:** -- You still want some explanation -- Working on moderately complex tasks -- Collaborating with others who need context - -### Ultra (`--format=ultra`) - -**Token savings: 60-70%** - -- Code-only responses -- Minimal to no explanations -- Terse comments only -- No examples unless critical - -**Use when:** -- Task is very clear -- You're experienced with the codebase -- Doing repetitive operations -- Maximum cost savings needed - -## Mode Activation - -### Session-Wide - -```bash -# Enable for entire session -/mode token-efficient - -# All commands now use token-efficient mode -/fix "error message" -/feature "new feature" -/review "file.ts" -``` - -### Single Command - -```bash -# Concise format for one command -/fix --format=concise "error message" - -# Ultra format for maximum savings -/feature --format=ultra "simple feature" -``` - -### Combining with Other Modes - -```bash -# Token-efficient implementation (very fast) -/execute-plan --mode=implementation --format=ultra plan.md - -# Concise deep research (save tokens on output) -/research --mode=deep-research --format=concise "topic" -``` - -## When NOT to Use - -Avoid token-efficient mode for: - -- **Complex architectural decisions** - Need thorough discussion -- **Code reviews** - Need detailed analysis and explanations -- **Documentation tasks** - Literally requires verbose output -- **Teaching/explanation requests** - Defeats the purpose -- **Debugging complex issues** - Need thorough investigation -- **First time with unfamiliar tech** - Need learning context - -## Best Practices - -### Progressive Refinement - -Start verbose, then compress: - -```bash -# First iteration - understand the problem -/fix "complex error" - -# Subsequent iterations - just make it work -/mode token-efficient -/fix "similar error" -/fix "another similar error" -``` - -### Batch Operations - -Perfect for repetitive tasks: - -```bash -/mode token-efficient - -# Generate tests for multiple files -/test src/services/user-service.ts -/test src/services/auth-service.ts -/test src/services/payment-service.ts -# ...repeat for all services - -/mode default # Switch back when done -``` - -### Know Your Codebase - -Token-efficient mode assumes you: -- Know the file structure -- Understand the tech stack -- Can read code without extensive comments -- Know where to find documentation - -If any of these are false, use default mode instead. - -## Token Usage Comparison - -Real example from a feature implementation: - -| Mode | Input Tokens | Output Tokens | Total | Cost (Sonnet) | -|------|--------------|---------------|-------|---------------| -| Default | 1,200 | 3,500 | 4,700 | $0.014 | -| Concise | 1,200 | 2,100 | 3,300 | $0.010 | -| Ultra | 1,200 | 1,200 | 2,400 | $0.007 | - -**Savings over 100 similar tasks:** -- Concise: $0.40 saved (~30%) -- Ultra: $0.70 saved (~50%) - -## Tips for Maximum Efficiency - -### 1. Be Specific in Requests - -**Less efficient:** -```bash -/fix "there's a bug in the user service" -``` - -**More efficient:** -```bash -/fix "null pointer at user-service.ts:42" -``` - -Saves tokens on both input and output. - -### 2. Use File Paths - -**Less efficient:** -```bash -/feature "add login endpoint" -``` - -**More efficient:** -```bash -/feature "add POST /auth/login to src/api/auth.ts" -``` - -Claude spends fewer tokens figuring out where code goes. - -### 3. Batch Similar Tasks - -**Less efficient:** -```bash -/test "user service" -[wait for response] -/test "auth service" -[wait for response] -``` - -**More efficient:** -```bash -/mode token-efficient -/test src/services/*.ts --format=ultra -``` - -### 4. Reference Previous Work - -**Less efficient:** -```bash -/feature "add logout endpoint similar to login" -``` - -**More efficient:** -```bash -/feature "add logout to auth.ts, same pattern as login" -``` - -Claude reuses context instead of regenerating it. - -## Configuration - -Customize token-efficient behavior in `.claude/modes/token-efficient.md`: - -- Default compression level -- When to skip explanations -- Comment verbosity -- Auto-activation conditions - -## Related Modes - -- **Implementation Mode**: Similar code-focus, for execution -- **Default Mode**: When you need more explanation -- **Brainstorm Mode**: Complete opposite - verbose exploration - -## Related Documentation - -- [Token Optimization Guide](/claudekit/optimization/token-efficient) -- [Cost Management](/claudekit/advanced/cost) -- [Batch Operations](/claudekit/guides/batch) diff --git a/website/src/content/docs/reference/agents.md b/website/src/content/docs/reference/agents.md new file mode 100644 index 0000000..e0638b9 --- /dev/null +++ b/website/src/content/docs/reference/agents.md @@ -0,0 +1,118 @@ +--- +title: Agents Reference +description: All 20 specialized subagents in Claude Kit. +--- + +# Agents Reference + +Agents are specialized subagents that Claude can dispatch for focused tasks. Each agent has access to specific tools and expertise, making it more effective than a general-purpose prompt for its domain. + +## How Agents Work + +Agents are defined as markdown files in `.claude/agents/`. When Claude dispatches a subagent, it starts a fresh context focused entirely on the task at hand: + +``` +You: "Review this code for security issues" + +Claude dispatches → security-auditor agent + → Focused security review + → Returns findings with severity ratings +``` + +Agents run independently and return results to the main conversation. They can be dispatched in parallel for independent tasks. + +--- + +## Planning & Research + +| Agent | Description | Use When | +|-------|-------------|----------| +| **planner** | Designs implementation plans, identifies critical files, considers trade-offs | Planning complex features or migrations | +| **brainstormer** | Explores solutions, evaluates architectures, debates technical decisions | Evaluating options before implementation | +| **researcher** | Comprehensive research on technologies, libraries, and best practices | Need in-depth comparison or analysis | + +## Code Quality + +| Agent | Description | Use When | +|-------|-------------|----------| +| **code-reviewer** | Reviews code for quality, security, performance, and maintainability | After implementing features, before PRs | +| **tester** | Runs test suites, analyzes coverage, validates error handling, verifies builds | After code changes, checking coverage | +| **debugger** | Investigates issues, analyzes system behavior, traces root causes | Debugging test failures or production bugs | + +## Security + +| Agent | Description | Use When | +|-------|-------------|----------| +| **security-auditor** | Security audits, OWASP compliance, code vulnerability review | Before production release, security review | +| **vulnerability-scanner** | Automated dependency scanning for known CVEs | Checking for dependency vulnerabilities | + +## Infrastructure & Data + +| Agent | Description | Use When | +|-------|-------------|----------| +| **database-admin** | Schema design, migrations, query optimization, data modeling | Database work for PostgreSQL or MongoDB | +| **cicd-manager** | CI/CD pipeline management, deployment automation | Setting up or fixing CI pipelines | +| **pipeline-architect** | Pipeline architecture design and build optimization | Redesigning slow CI/CD pipelines | + +## Content & Documentation + +| Agent | Description | Use When | +|-------|-------------|----------| +| **docs-manager** | API docs, READMEs, code comments, technical specifications | Documentation needs updating | +| **copywriter** | Marketing copy, release notes, changelogs, product descriptions | User-facing content creation | +| **journal-writer** | Development journals, decision logs, incident documentation | Recording failures or key decisions | + +## Design & UI + +| Agent | Description | Use When | +|-------|-------------|----------| +| **ui-ux-designer** | Design mockups to code, UI components, responsive/accessible layouts | Building or fixing UI components | +| **api-designer** | RESTful/GraphQL API design, OpenAPI specifications | Designing new APIs | + +## Project Management + +| Agent | Description | Use When | +|-------|-------------|----------| +| **project-manager** | Progress tracking, roadmaps, task monitoring, status reports | Checking project progress | +| **git-manager** | Stage, commit, push with conventional commits | Git operations | + +## Exploration + +| Agent | Description | Use When | +|-------|-------------|----------| +| **scout** | Rapidly maps internal codebase — files, patterns, dependencies | Finding code locations, understanding structure | +| **scout-external** | Explores external resources, APIs, open-source projects | Researching external APIs or libraries | + +--- + +## Dispatching Agents + +Claude dispatches agents automatically when appropriate. You can also request it explicitly: + +``` +"Have the security-auditor review the auth module" +"Ask the database-admin to optimize this query" +"Get the code-reviewer to check my changes" +``` + +### Parallel Dispatch + +For independent tasks, agents run in parallel: + +``` +You: "Review security, check test coverage, and audit the database schema" + +Claude dispatches simultaneously: + → security-auditor (auth module) + → tester (coverage analysis) + → database-admin (schema review) +``` + +### Agent vs. Skill + +| | Skills | Agents | +|---|--------|--------| +| **How** | Auto-trigger by keywords | Dispatched for focused tasks | +| **Context** | Same conversation | Fresh, isolated context | +| **Best for** | Patterns and methodology | Focused independent work | +| **Parallelism** | Sequential | Can run in parallel | diff --git a/website/src/content/docs/reference/mcp-servers.md b/website/src/content/docs/reference/mcp-servers.md new file mode 100644 index 0000000..199ac52 --- /dev/null +++ b/website/src/content/docs/reference/mcp-servers.md @@ -0,0 +1,145 @@ +--- +title: MCP Servers +description: Optional MCP server integrations for enhanced capabilities. +--- + +# MCP Servers + +Claude Kit includes optional [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server configurations that extend Claude's capabilities with external tools. + +## How MCP Works + +MCP servers give Claude access to tools it doesn't have natively — browser automation, persistent memory, real-time documentation, and structured reasoning. They run as local processes that Claude communicates with during your session. + +Server configurations live in `.claude/mcp/`. + +--- + +## Available Servers + +### Context7 + +**Purpose**: Real-time library documentation lookup + +Fetches current documentation for any library, framework, or API. Use instead of relying on Claude's training data, which may be outdated. + +``` +You: "How do I set up middleware in Next.js 15?" + +Claude fetches current Next.js 15 docs via Context7 +→ Answers with up-to-date API syntax +``` + +**Best for**: API syntax, configuration, version migration, library-specific debugging. + +**Config**: `.claude/mcp/context7.json` + +--- + +### Sequential Thinking + +**Purpose**: Structured step-by-step reasoning + +Provides a tool for multi-step analysis with explicit thought chains. Used automatically by the sequential-thinking skill for complex problems. + +``` +Complex debugging scenario: + Step 1: Observe the error → confidence: 0.9 + Step 2: Form hypothesis → confidence: 0.7 + Step 3: Test hypothesis → confidence: 0.85 + Step 4: Verify fix → confidence: 0.95 +``` + +**Best for**: Complex debugging, architecture decisions, security analysis. + +**Config**: `.claude/mcp/sequential.json` + +--- + +### Memory + +**Purpose**: Persistent knowledge graph across sessions + +Stores entities, relationships, and observations that persist across conversations. Claude can recall project decisions, user preferences, and architectural context. + +``` +Session 1: "We decided to use PostgreSQL RLS for multi-tenancy" + → Stored as entity + decision observation + +Session 2: "What did we decide about multi-tenancy?" + → Retrieved from memory graph +``` + +**Best for**: Long-running projects, team knowledge persistence, decision tracking. + +--- + +### Filesystem + +**Purpose**: Secure file operations with access controls + +Provides sandboxed file operations with configurable allowed directories. Useful for projects that need restricted file access. + +**Best for**: Projects with strict file access requirements. + +--- + +### Playwright + +**Purpose**: Browser automation for testing + +Enables Claude to control a browser for E2E testing, visual verification, and web scraping. Works with the playwright skill for end-to-end test workflows. + +``` +You: "Test the login flow in the browser" + +Claude launches browser via Playwright MCP: + → Navigate to /login + → Fill email and password + → Click submit + → Verify redirect to /dashboard + → Take screenshot for evidence +``` + +**Best for**: E2E testing, visual regression, browser-based verification. + +--- + +## Setup + +### Prerequisites + +MCP servers require Node.js installed on your system. + +### Enabling a Server + +1. Check the config file in `.claude/mcp/` for the server you want +2. Install any required dependencies (noted in the config) +3. Restart Claude Code + +### Configuration Format + +Each server has a JSON config file: + +```json +{ + "mcpServers": { + "server-name": { + "command": "npx", + "args": ["-y", "@package/server-name"], + "env": {} + } + } +} +``` + +See `.claude/mcp/README.md` for detailed setup instructions. + +## Skills That Use MCP + +| MCP Server | Skills That Benefit | +|------------|-------------------| +| Context7 | All framework/library skills (frontend, backend-frameworks, databases) | +| Sequential | sequential-thinking, systematic-debugging, brainstorming | +| Memory | session-management, brainstorming (persisting design decisions) | +| Playwright | playwright, verification-before-completion | diff --git a/website/src/content/docs/reference/modes.md b/website/src/content/docs/reference/modes.md new file mode 100644 index 0000000..8ae96ab --- /dev/null +++ b/website/src/content/docs/reference/modes.md @@ -0,0 +1,177 @@ +--- +title: Modes Reference +description: All 7 behavioral modes in Claude Kit. +--- + +# Modes Reference + +Modes change how Claude communicates and solves problems. Each mode optimizes behavior for a specific type of task. + +## How Modes Work + +Switch modes naturally in conversation: + +``` +"switch to brainstorm mode" +"use implementation mode" +"go into review mode" +``` + +Mode files live in `.claude/modes/`. Each defines communication style, output format, and problem-solving approach. + +--- + +## Available Modes + +### Default + +The standard balanced mode for general tasks. + +- **Communication**: Clear, helpful, balanced detail +- **Output**: Mix of explanation and code +- **Best for**: General development tasks, questions, exploration + +--- + +### Brainstorm + +Creative exploration for design and ideation. + +- **Communication**: Asks lots of questions, explores alternatives +- **Output**: Options with trade-offs, diagrams, decision matrices +- **Best for**: Feature design, architecture decisions, requirement exploration + +**Example**: +``` +You: "switch to brainstorm mode" +You: "I need to add search to our product catalog" + +Claude asks one question at a time: + "What search complexity do you need? + a) Simple text matching (LIKE queries) + b) Full-text search (PostgreSQL tsvector) + c) Dedicated search engine (Elasticsearch/Meilisearch)" +``` + +--- + +### Implementation + +Code-focused execution with minimal prose. + +- **Communication**: Terse, action-oriented +- **Output**: Mostly code, minimal explanation +- **Best for**: Executing known tasks, coding from clear specs + +**Example**: +``` +You: "switch to implementation mode" +You: "add a PATCH /api/users/:id endpoint" + +Claude writes code immediately with minimal commentary. +``` + +--- + +### Review + +Critical analysis for code review and quality assurance. + +- **Communication**: Critical, thorough, finds issues +- **Output**: Issue lists with severity, suggestions, security flags +- **Best for**: Code review, QA, pre-merge checks + +**Example**: +``` +You: "switch to review mode" +You: "review the auth middleware" + +Claude examines code critically: + "CRITICAL: Token expiry not checked after decode (line 42) + IMPORTANT: Missing rate limiting on login endpoint + MINOR: Inconsistent error response format" +``` + +--- + +### Token-Efficient + +Compressed output for high-volume work and cost optimization. + +- **Communication**: Minimal prose, maximum density +- **Output**: Code-only when possible, compressed explanations +- **Best for**: Long sessions, repetitive tasks, cost-conscious work +- **Savings**: 30-70% token reduction + +**Levels**: + +| Level | How to Activate | Savings | +|-------|----------------|---------| +| Concise | "be concise" | 30-40% | +| Ultra | "code only" | 60-70% | +| Session | "switch to token-efficient mode" | 30-70% | + +--- + +### Deep Research + +Thorough investigation with evidence and citations. + +- **Communication**: Detailed analysis, cites sources +- **Output**: Structured reports, evidence-backed conclusions +- **Best for**: Technology evaluation, incident investigation, audits + +**Example**: +``` +You: "switch to deep research mode" +You: "analyze our authentication flow for security issues" + +Claude produces a structured report: + "## Findings + ### 1. Session Token Storage (High Risk) + Current: localStorage (vulnerable to XSS) + Recommended: httpOnly cookie + Evidence: OWASP Session Management Cheat Sheet..." +``` + +--- + +### Orchestration + +Multi-agent coordination for complex parallel work. + +- **Communication**: Status-oriented, progress tracking +- **Output**: Agent dispatch summaries, consolidated results +- **Best for**: Large tasks requiring multiple agents working in parallel + +**Example**: +``` +You: "switch to orchestration mode" +You: "audit the entire API layer" + +Claude coordinates multiple agents: + "Dispatching 3 agents in parallel: + → security-auditor: reviewing auth endpoints + → code-reviewer: reviewing business logic + → tester: checking coverage gaps + + Results consolidated in ~2 minutes..." +``` + +--- + +## Mode Comparison + +| Mode | Verbosity | Focus | Output Style | +|------|-----------|-------|-------------| +| Default | Medium | Balanced | Explanation + code | +| Brainstorm | High | Exploration | Questions + options | +| Implementation | Low | Execution | Code-first | +| Review | Medium | Quality | Issue lists | +| Token-Efficient | Minimal | Density | Compressed | +| Deep Research | High | Analysis | Reports | +| Orchestration | Medium | Coordination | Status + results | + +## Customizing Modes + +Mode files are markdown in `.claude/modes/`. You can edit existing modes or create new ones. See [Creating Agents & Modes](/claudekit/customization/creating-agents-and-modes/) for details. diff --git a/website/src/content/docs/reference/skills.md b/website/src/content/docs/reference/skills.md new file mode 100644 index 0000000..72fff00 --- /dev/null +++ b/website/src/content/docs/reference/skills.md @@ -0,0 +1,108 @@ +--- +title: Skills Reference +description: All 43 skills in Claude Kit, organized by category. +--- + +# Skills Reference + +Skills are knowledge modules that auto-trigger based on keywords in your conversation. No commands needed — Claude activates the right skills based on what you're doing. + +## How Skills Work + +Each skill has a trigger description with keywords. When you say something that matches, the skill loads automatically: + +``` +"fix this bug" → systematic-debugging, root-cause-tracing +"plan the feature" → brainstorming, writing-plans +"review the code" → requesting-code-review +"switch to brainstorm" → mode-switching, brainstorming +``` + +Skills live in `.claude/skills/` and can be customized or extended. + +--- + +## Development + +Skills for languages, frameworks, and application patterns. + +| Skill | Description | Triggers On | +|-------|-------------|-------------| +| **languages** | Python, TypeScript, JavaScript idioms — type hints, generics, async/await, Pydantic, Zod | Language-specific code patterns | +| **frontend** | React components, Next.js App Router, SSR/SSG, shadcn/ui, hooks | React, Next.js, component work | +| **frontend-styling** | Tailwind CSS, WCAG accessibility, ARIA, dark mode, responsive | Styling, accessibility | +| **backend-frameworks** | FastAPI, Django, NestJS, Express — routing, middleware, DI | API endpoints, server code | +| **databases** | PostgreSQL, MongoDB, Redis — schema, queries, indexing, migrations | Database operations | +| **state-management** | useState, Zustand, Jotai, TanStack Query, server/form/URL state | State architecture | +| **api-client** | axios, fetch, httpx — interceptors, retry logic, type-safe clients | HTTP requests, API integration | +| **openapi** | OpenAPI 3.1 design, error contracts, pagination, code-gen | API specification | + +## Infrastructure + +Skills for deployment, caching, logging, and operational concerns. + +| Skill | Description | Triggers On | +|-------|-------------|-------------| +| **devops** | Docker, GitHub Actions, Cloudflare Workers, multi-stage builds | Containers, CI/CD, deployment | +| **caching** | Redis, memoization, HTTP cache headers, CDN, TTL policies | Cache strategy | +| **logging** | Logger setup, log levels, correlation IDs, sensitive data redaction | Logging, observability | +| **error-handling** | Try/catch, custom errors, retry logic, React error boundaries | Exception handling | +| **background-jobs** | Celery, BullMQ, task queues, cron jobs, async processing | Background tasks, workers | +| **authentication** | JWT, OAuth2, sessions, RBAC, password hashing, MFA | Login, auth, permissions | +| **performance-optimization** | Profiling, N+1 queries, bundle size, memory leaks, benchmarks | "slow", "optimize", "profiling" | + +## Quality + +Skills for testing, security, and code verification. + +| Skill | Description | Triggers On | +|-------|-------------|-------------| +| **testing** | pytest, Vitest, Jest — fixtures, mocking, coverage, config | Writing/debugging tests | +| **test-driven-development** | Strict red-green-refactor — no production code without failing test | "implement", "add feature", "build" | +| **testing-anti-patterns** | Detecting unreliable tests, heavy mocking, false positives | "flaky test", "mock", test review | +| **playwright** | E2E tests, page objects, visual regression, cross-browser | End-to-end testing | +| **owasp** | OWASP Top 10, XSS, SQL injection, CSRF, dependency scanning | Security review, user input | +| **defense-in-depth** | Multi-layer validation, preventing single-point bypass | Data integrity bugs | +| **verification-before-completion** | Mandatory evidence before completion claims | "done", "fixed", "tests pass" | + +## Debugging + +Skills for investigating and resolving issues. + +| Skill | Description | Triggers On | +|-------|-------------|-------------| +| **systematic-debugging** | Four-phase investigation: observe, hypothesize, test, fix | "bug", "error", "broken", stack traces | +| **root-cause-tracing** | Tracing bugs that manifest far from their origin | Deep bugs, data corruption | +| **sequential-thinking** | Step-by-step reasoning with confidence tracking | Complex decisions, analysis | +| **condition-based-waiting** | Polling CI pipelines, deployments, long-running processes | "wait for", "check status" | + +## Workflow + +Skills for development process and session management. + +| Skill | Description | Triggers On | +|-------|-------------|-------------| +| **feature-workflow** | End-to-end: requirements → planning → implementation → review | "feature", "implement end-to-end" | +| **brainstorming** | Interactive design with one question at a time | "brainstorm", "design", "explore" | +| **writing-plans** | Detailed task breakdown with exact code and file paths | "plan", "break down", "task list" | +| **executing-plans** | Subagent-driven execution with review gates | "execute the plan", "run the plan" | +| **git-workflows** | Conventional commits, PRs, changelogs, release notes | "commit", "PR", "ship", "changelog" | +| **documentation** | Docstrings, JSDoc, README, API docs, tech specs | "document", "docstring", "README" | +| **refactoring** | Improving code structure without behavior change | "refactor", "clean up", "simplify" | +| **mode-switching** | Switching behavioral modes for the session | "mode", "switch to brainstorm" | +| **session-management** | Checkpoints, project indexing, context loading | "checkpoint", "index", "status" | +| **writing-concisely** | Token optimization, compressed output, 30-70% savings | "be concise", "code only" | + +## Collaboration + +Skills for multi-agent workflows and team processes. + +| Skill | Description | Triggers On | +|-------|-------------|-------------| +| **dispatching-parallel-agents** | Launching parallel agents for independent tasks | 3+ independent failures/tasks | +| **subagent-driven-development** | Parallel task execution via Agent tool | "use subagents", "dispatch agents" | +| **using-git-worktrees** | Isolated branch work, parallel development | "worktree", "isolated branch" | +| **requesting-code-review** | Preparing code for review with clear context | Before PRs, before merging | +| **receiving-code-review** | Processing review feedback systematically | Review comments, PR feedback | +| **finishing-a-development-branch** | Branch completion: verify, review, merge/PR options | "ship it", "ready to merge" | +| **writing-skills** | Creating and editing skills for this kit | "create a skill", "new skill" | diff --git a/website/src/content/docs/skills/frameworks/django.md b/website/src/content/docs/skills/frameworks/django.md deleted file mode 100644 index ccce7c6..0000000 --- a/website/src/content/docs/skills/frameworks/django.md +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: Django -description: Django ORM, views, and REST framework patterns ---- - -The Django skill provides expertise in Django web framework including ORM, class-based views, and Django REST Framework. - -## When Activated - -- Python web applications -- Admin interfaces -- Django REST Framework APIs -- Working with Django projects - -## Core Patterns - -### Models - -```python -from django.db import models - -class User(models.Model): - email = models.EmailField(unique=True) - name = models.CharField(max_length=100) - created_at = models.DateTimeField(auto_now_add=True) - updated_at = models.DateTimeField(auto_now=True) - - class Meta: - ordering = ['-created_at'] - indexes = [ - models.Index(fields=['email']), - ] - - def __str__(self): - return self.email -``` - -### Views (Class-based) - -```python -from django.views.generic import ListView, DetailView, CreateView - -class UserListView(ListView): - model = User - template_name = 'users/list.html' - context_object_name = 'users' - paginate_by = 20 - -class UserDetailView(DetailView): - model = User - template_name = 'users/detail.html' - context_object_name = 'user' - -class UserCreateView(CreateView): - model = User - fields = ['email', 'name'] - template_name = 'users/create.html' - success_url = '/users/' -``` - -### Django REST Framework - -```python -from rest_framework import serializers, viewsets -from rest_framework.decorators import action -from rest_framework.response import Response - -class UserSerializer(serializers.ModelSerializer): - class Meta: - model = User - fields = ['id', 'email', 'name', 'created_at'] - read_only_fields = ['created_at'] - -class UserViewSet(viewsets.ModelViewSet): - queryset = User.objects.all() - serializer_class = UserSerializer - - @action(detail=True, methods=['post']) - def activate(self, request, pk=None): - user = self.get_object() - user.is_active = True - user.save() - return Response({'status': 'activated'}) -``` - -### URLs - -```python -from django.urls import path, include -from rest_framework.routers import DefaultRouter - -router = DefaultRouter() -router.register('users', UserViewSet) - -urlpatterns = [ - path('api/', include(router.urls)), - path('users/', UserListView.as_view(), name='user-list'), - path('users//', UserDetailView.as_view(), name='user-detail'), -] -``` - -## Best Practices - -1. **Use class-based views for standard CRUD** -2. **Define model methods for business logic** -3. **Use serializers for validation** -4. **Add proper permissions** -5. **Use select_related/prefetch_related for queries** - -## Common Pitfalls - -### N+1 Queries - -```python -# ❌ BAD: N+1 query problem -users = User.objects.all() -for user in users: - print(user.profile.bio) # Separate query for each user - -# ✅ GOOD: Use select_related -users = User.objects.select_related('profile').all() -for user in users: - print(user.profile.bio) # Single query -``` - -### Missing Migrations - -```python -# ❌ BAD: Forgetting migrations -# After changing models, forgetting to: -python manage.py makemigrations -python manage.py migrate - -# ✅ GOOD: Always create and run migrations -python manage.py makemigrations -python manage.py migrate -``` - -### No Validation - -```python -# ❌ BAD: Direct model creation -user = User.objects.create(email=request.POST['email']) - -# ✅ GOOD: Use serializer for validation -serializer = UserSerializer(data=request.data) -if serializer.is_valid(): - user = serializer.save() -else: - return Response(serializer.errors, status=400) -``` - -## Advanced Patterns - -### Custom Managers - -```python -class ActiveUserManager(models.Manager): - def get_queryset(self): - return super().get_queryset().filter(is_active=True) - -class User(models.Model): - # ... - objects = models.Manager() - active = ActiveUserManager() - -# Usage -all_users = User.objects.all() -active_users = User.active.all() -``` - -### Signals - -```python -from django.db.models.signals import post_save -from django.dispatch import receiver - -@receiver(post_save, sender=User) -def create_user_profile(sender, instance, created, **kwargs): - if created: - Profile.objects.create(user=instance) -``` - -### Permissions - -```python -from rest_framework import permissions - -class IsOwnerOrReadOnly(permissions.BasePermission): - def has_object_permission(self, request, view, obj): - if request.method in permissions.SAFE_METHODS: - return True - return obj.owner == request.user - -class UserViewSet(viewsets.ModelViewSet): - permission_classes = [IsOwnerOrReadOnly] - # ... -``` - -### Pagination - -```python -from rest_framework.pagination import PageNumberPagination - -class StandardResultsSetPagination(PageNumberPagination): - page_size = 20 - page_size_query_param = 'page_size' - max_page_size = 100 - -class UserViewSet(viewsets.ModelViewSet): - pagination_class = StandardResultsSetPagination - # ... -``` - -## Testing - -```python -from django.test import TestCase -from rest_framework.test import APITestCase - -class UserModelTest(TestCase): - def test_create_user(self): - user = User.objects.create( - email='test@example.com', - name='Test User' - ) - self.assertEqual(user.email, 'test@example.com') - -class UserAPITest(APITestCase): - def test_list_users(self): - response = self.client.get('/api/users/') - self.assertEqual(response.status_code, 200) - - def test_create_user(self): - data = {'email': 'new@example.com', 'name': 'New User'} - response = self.client.post('/api/users/', data) - self.assertEqual(response.status_code, 201) -``` - -## Related Skills - -- [Python](/claudekit/skills/languages/python) - Python language -- [PostgreSQL](/claudekit/skills/databases/postgresql) - Database -- [pytest](/claudekit/skills/testing/pytest) - Testing -- [OpenAPI](/claudekit/skills/api/openapi) - API documentation diff --git a/website/src/content/docs/skills/frameworks/fastapi.md b/website/src/content/docs/skills/frameworks/fastapi.md deleted file mode 100644 index 863461d..0000000 --- a/website/src/content/docs/skills/frameworks/fastapi.md +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: FastAPI -description: FastAPI async patterns, Pydantic validation, and OpenAPI documentation ---- - -The FastAPI skill provides expertise in building REST APIs with Python, async patterns, Pydantic validation, and automatic OpenAPI documentation. - -## When Activated - -- Building REST APIs with Python -- Async web applications -- OpenAPI/Swagger documentation needed -- Working with FastAPI framework - -## Core Patterns - -### Route Definition - -```python -from fastapi import FastAPI, HTTPException, Depends -from pydantic import BaseModel - -app = FastAPI() - -class UserCreate(BaseModel): - email: str - name: str - -class UserResponse(BaseModel): - id: int - email: str - name: str - -@app.post("/users", response_model=UserResponse, status_code=201) -async def create_user(user: UserCreate): - # Create user logic - return UserResponse(id=1, **user.model_dump()) - -@app.get("/users/{user_id}", response_model=UserResponse) -async def get_user(user_id: int): - user = await get_user_by_id(user_id) - if not user: - raise HTTPException(status_code=404, detail="User not found") - return user -``` - -### Dependency Injection - -```python -from fastapi import Depends -from sqlalchemy.ext.asyncio import AsyncSession - -async def get_db() -> AsyncGenerator[AsyncSession, None]: - async with async_session_maker() as session: - yield session - -@app.get("/users") -async def list_users(db: AsyncSession = Depends(get_db)): - result = await db.execute(select(User)) - return result.scalars().all() -``` - -### Router Organization - -```python -from fastapi import APIRouter - -router = APIRouter(prefix="/users", tags=["users"]) - -@router.get("/") -async def list_users(): - pass - -@router.post("/") -async def create_user(user: UserCreate): - pass - -# In main.py -app.include_router(router) -``` - -### Request Validation - -```python -from pydantic import BaseModel, EmailStr, Field - -class UserCreate(BaseModel): - email: EmailStr - name: str = Field(min_length=1, max_length=100) - age: int = Field(ge=0, le=150) - - class Config: - json_schema_extra = { - "example": { - "email": "user@example.com", - "name": "John Doe", - "age": 30 - } - } -``` - -### Error Handling - -```python -from fastapi import HTTPException, status -from fastapi.responses import JSONResponse - -class UserNotFoundError(Exception): - pass - -@app.exception_handler(UserNotFoundError) -async def user_not_found_handler(request, exc): - return JSONResponse( - status_code=status.HTTP_404_NOT_FOUND, - content={"detail": "User not found"} - ) - -@app.get("/users/{user_id}") -async def get_user(user_id: int): - user = await find_user(user_id) - if not user: - raise UserNotFoundError() - return user -``` - -### Background Tasks - -```python -from fastapi import BackgroundTasks - -def send_email(email: str, message: str): - # Send email logic - pass - -@app.post("/users") -async def create_user( - user: UserCreate, - background_tasks: BackgroundTasks -): - new_user = await create_user_in_db(user) - background_tasks.add_task(send_email, user.email, "Welcome!") - return new_user -``` - -## Best Practices - -1. **Use Pydantic models for request/response validation** -2. **Organize routes with APIRouter** -3. **Use dependency injection for services** -4. **Return proper HTTP status codes** -5. **Add OpenAPI descriptions and examples** - -## Common Pitfalls - -### Blocking I/O in Async - -```python -# ❌ BAD: Blocking call in async function -@app.get("/users") -async def list_users(): - users = blocking_db_call() # Blocks event loop - return users - -# ✅ GOOD: Use async libraries -@app.get("/users") -async def list_users(db: AsyncSession = Depends(get_db)): - result = await db.execute(select(User)) - return result.scalars().all() -``` - -### Missing Response Models - -```python -# ❌ BAD: No response model -@app.get("/users/{user_id}") -async def get_user(user_id: int): - return await get_user_by_id(user_id) - -# ✅ GOOD: Define response model -@app.get("/users/{user_id}", response_model=UserResponse) -async def get_user(user_id: int): - return await get_user_by_id(user_id) -``` - -### Not Using HTTPException - -```python -# ❌ BAD: Returning error dict -@app.get("/users/{user_id}") -async def get_user(user_id: int): - user = await find_user(user_id) - if not user: - return {"error": "Not found"} # Returns 200! - return user - -# ✅ GOOD: Raise HTTPException -@app.get("/users/{user_id}") -async def get_user(user_id: int): - user = await find_user(user_id) - if not user: - raise HTTPException(status_code=404, detail="User not found") - return user -``` - -## Advanced Patterns - -### Middleware - -```python -from fastapi import Request -import time - -@app.middleware("http") -async def add_process_time_header(request: Request, call_next): - start_time = time.time() - response = await call_next(request) - process_time = time.time() - start_time - response.headers["X-Process-Time"] = str(process_time) - return response -``` - -### Authentication - -```python -from fastapi import Security, HTTPException -from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials - -security = HTTPBearer() - -async def get_current_user( - credentials: HTTPAuthorizationCredentials = Security(security) -) -> User: - token = credentials.credentials - user = await verify_token(token) - if not user: - raise HTTPException(status_code=401, detail="Invalid token") - return user - -@app.get("/profile") -async def get_profile(current_user: User = Depends(get_current_user)): - return current_user -``` - -### CORS - -```python -from fastapi.middleware.cors import CORSMiddleware - -app.add_middleware( - CORSMiddleware, - allow_origins=["https://example.com"], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) -``` - -## Testing - -```python -from fastapi.testclient import TestClient - -client = TestClient(app) - -def test_create_user(): - response = client.post( - "/users", - json={"email": "test@example.com", "name": "Test"} - ) - assert response.status_code == 201 - assert response.json()["email"] == "test@example.com" - -def test_get_nonexistent_user(): - response = client.get("/users/999") - assert response.status_code == 404 -``` - -## Related Skills - -- [Python](/claudekit/skills/languages/python) - Python language -- [Pydantic](/claudekit/skills/languages/python) - Data validation -- [PostgreSQL](/claudekit/skills/databases/postgresql) - Database -- [pytest](/claudekit/skills/testing/pytest) - Testing diff --git a/website/src/content/docs/skills/frameworks/nextjs.md b/website/src/content/docs/skills/frameworks/nextjs.md deleted file mode 100644 index 6d7ab3d..0000000 --- a/website/src/content/docs/skills/frameworks/nextjs.md +++ /dev/null @@ -1,404 +0,0 @@ ---- -title: Next.js -description: Next.js App Router, Server Components, and full-stack patterns ---- - -The Next.js skill provides expertise in Next.js with App Router, Server Components, Server Actions, and full-stack development patterns. - -## When Activated - -- React applications with SSR/SSG -- Full-stack applications -- App Router patterns -- Working in `app/` directory - -## Core Patterns - -### App Router Structure - -``` -app/ -├── layout.tsx # Root layout -├── page.tsx # Home page -├── loading.tsx # Loading UI -├── error.tsx # Error UI -├── api/ -│ └── users/ -│ └── route.ts # API route -└── users/ - ├── page.tsx # Users page - └── [id]/ - └── page.tsx # User detail -``` - -### Server Components - -```tsx -// app/users/page.tsx - Server Component (default) -async function UsersPage() { - const users = await db.users.findMany(); - - return ( -
    - {users.map(user => ( -
  • {user.name}
  • - ))} -
- ); -} -``` - -### Client Components - -```tsx -'use client'; - -import { useState } from 'react'; - -export function Counter() { - const [count, setCount] = useState(0); - - return ( - - ); -} -``` - -### API Routes - -```typescript -// app/api/users/route.ts -import { NextRequest, NextResponse } from 'next/server'; - -export async function GET() { - const users = await db.users.findMany(); - return NextResponse.json(users); -} - -export async function POST(request: NextRequest) { - const data = await request.json(); - const user = await db.users.create({ data }); - return NextResponse.json(user, { status: 201 }); -} -``` - -### Server Actions - -```tsx -// app/actions.ts -'use server'; - -export async function createUser(formData: FormData) { - const name = formData.get('name') as string; - await db.users.create({ data: { name } }); - revalidatePath('/users'); -} - -// app/users/new/page.tsx -import { createUser } from '@/app/actions'; - -export default function NewUserPage() { - return ( -
- - -
- ); -} -``` - -### Dynamic Routes - -```tsx -// app/users/[id]/page.tsx -interface PageProps { - params: { id: string }; -} - -export default async function UserPage({ params }: PageProps) { - const user = await db.users.findUnique({ - where: { id: params.id } - }); - - if (!user) { - notFound(); - } - - return
{user.name}
; -} -``` - -### Layouts - -```tsx -// app/layout.tsx -export default function RootLayout({ - children, -}: { - children: React.ReactNode; -}) { - return ( - - - -
{children}
-
{/* Footer */}
- - - ); -} -``` - -## Best Practices - -1. **Use Server Components by default** -2. **Add 'use client' only when needed** -3. **Colocate data fetching with components** -4. **Use loading.tsx for suspense boundaries** -5. **Implement proper error boundaries** - -## Common Pitfalls - -### Using Hooks in Server Components - -```tsx -// ❌ BAD: Hooks in Server Component -export default async function Page() { - const [state, setState] = useState(0); // Error! - return
{state}
; -} - -// ✅ GOOD: Mark as Client Component -'use client'; - -export default function Page() { - const [state, setState] = useState(0); - return
{state}
; -} -``` - -### Large Client Bundles - -```tsx -// ❌ BAD: Entire page as Client Component -'use client'; - -export default function Page() { - const [count, setCount] = useState(0); - const data = await fetchData(); // Can't use await in Client Component - - return ( -
- - -
- ); -} - -// ✅ GOOD: Extract interactive parts only -export default async function Page() { - const data = await fetchData(); // Server Component can await - - return ( -
- {/* Server Component */} - {/* Small Client Component */} -
- ); -} - -// Counter.tsx -'use client'; -export function Counter() { - const [count, setCount] = useState(0); - return ; -} -``` - -### Missing Loading States - -```tsx -// ❌ BAD: No loading state -export default async function Page() { - const data = await slowFetch(); - return
{data}
; -} - -// ✅ GOOD: Add loading.tsx -// app/page.tsx -export default async function Page() { - const data = await slowFetch(); - return
{data}
; -} - -// app/loading.tsx -export default function Loading() { - return
Loading...
; -} -``` - -### Not Revalidating After Mutations - -```tsx -// ❌ BAD: No revalidation -'use server'; -export async function createUser(data: FormData) { - await db.users.create({ data: getData(data) }); - // Page still shows old data -} - -// ✅ GOOD: Revalidate path -'use server'; -export async function createUser(data: FormData) { - await db.users.create({ data: getData(data) }); - revalidatePath('/users'); - redirect('/users'); -} -``` - -## Data Fetching Patterns - -### Parallel Data Fetching - -```tsx -export default async function Page() { - // Fetch in parallel - const [users, posts] = await Promise.all([ - fetchUsers(), - fetchPosts(), - ]); - - return ( -
- - -
- ); -} -``` - -### Sequential Data Fetching - -```tsx -export default async function UserPage({ params }: { params: { id: string } }) { - const user = await fetchUser(params.id); - const posts = await fetchUserPosts(user.id); // Depends on user - - return ( -
-

{user.name}

- -
- ); -} -``` - -### Streaming with Suspense - -```tsx -import { Suspense } from 'react'; - -export default function Page() { - return ( -
-

Dashboard

- }> - - - -
- ); -} - -async function SlowComponent() { - const data = await slowFetch(); - return
{data}
; -} -``` - -## Caching and Revalidation - -### Time-Based Revalidation - -```tsx -// Revalidate every hour -export const revalidate = 3600; - -export default async function Page() { - const data = await fetch('https://api.example.com/data', { - next: { revalidate: 3600 } - }); - return
{JSON.stringify(data)}
; -} -``` - -### On-Demand Revalidation - -```tsx -// app/actions.ts -'use server'; - -import { revalidatePath, revalidateTag } from 'next/cache'; - -export async function createPost(data: FormData) { - await db.posts.create({ data: getData(data) }); - revalidatePath('/posts'); - // or - revalidateTag('posts'); -} -``` - -## Metadata - -```tsx -import { Metadata } from 'next'; - -export const metadata: Metadata = { - title: 'User Profile', - description: 'View user profile information', -}; - -export default function Page() { - return
Profile
; -} - -// Dynamic metadata -export async function generateMetadata({ params }: PageProps): Promise { - const user = await fetchUser(params.id); - - return { - title: `${user.name}'s Profile`, - description: `Profile page for ${user.name}`, - }; -} -``` - -## Integration with Other Skills - -### With React - -See [React skill](/claudekit/skills/frameworks/react) for component patterns and hooks. - -### With TypeScript - -Full TypeScript integration: -```tsx -import { NextRequest, NextResponse } from 'next/server'; - -export async function GET( - request: NextRequest, - { params }: { params: { id: string } } -): Promise { - const user = await fetchUser(params.id); - return NextResponse.json(user); -} -``` - -## Related Skills - -- [React](/claudekit/skills/frameworks/react) - Component patterns -- [TypeScript](/claudekit/skills/languages/typescript) - Type safety -- [Tailwind CSS](/claudekit/skills/frontend/tailwind) - Styling -- [PostgreSQL](/claudekit/skills/databases/postgresql) - Database diff --git a/website/src/content/docs/skills/frameworks/react.md b/website/src/content/docs/skills/frameworks/react.md deleted file mode 100644 index b1c190f..0000000 --- a/website/src/content/docs/skills/frameworks/react.md +++ /dev/null @@ -1,287 +0,0 @@ ---- -title: React -description: React component patterns, hooks, and state management ---- - -The React skill provides expertise in React component patterns, hooks, context, and modern React best practices. - -## When Activated - -- Building React components -- Using React hooks -- Component state management -- Working with `.jsx` or `.tsx` files containing React - -## Core Patterns - -### Functional Components - -```tsx -interface UserCardProps { - user: User; - onSelect?: (user: User) => void; -} - -export function UserCard({ user, onSelect }: UserCardProps) { - return ( -
onSelect?.(user)}> -

{user.name}

-

{user.email}

-
- ); -} -``` - -### Hooks - -```tsx -// useState -const [count, setCount] = useState(0); - -// useEffect -useEffect(() => { - const subscription = subscribe(); - return () => subscription.unsubscribe(); -}, [dependency]); - -// useMemo -const expensive = useMemo(() => compute(data), [data]); - -// useCallback -const handleClick = useCallback(() => { - doSomething(id); -}, [id]); -``` - -### Custom Hooks - -```tsx -function useUser(id: string) { - const [user, setUser] = useState(null); - const [loading, setLoading] = useState(true); - - useEffect(() => { - setLoading(true); - fetchUser(id) - .then(setUser) - .finally(() => setLoading(false)); - }, [id]); - - return { user, loading }; -} - -// Usage -function UserProfile({ userId }: { userId: string }) { - const { user, loading } = useUser(userId); - - if (loading) return
Loading...
; - if (!user) return
User not found
; - - return
{user.name}
; -} -``` - -### Context Pattern - -```tsx -const UserContext = createContext(null); - -export function UserProvider({ children }: { children: ReactNode }) { - const [user, setUser] = useState(null); - - return ( - - {children} - - ); -} - -export function useUser() { - const context = useContext(UserContext); - if (!context) throw new Error('useUser must be within UserProvider'); - return context; -} -``` - -## Best Practices - -1. **Keep components small and focused** -2. **Use TypeScript for props** -3. **Memoize expensive computations** -4. **Clean up effects properly** -5. **Lift state up when needed** - -## Common Pitfalls - -### Missing Dependencies in Hooks - -```tsx -// ❌ BAD: Missing dependency -useEffect(() => { - fetchData(userId); -}, []); // userId not in dependencies - -// ✅ GOOD: All dependencies included -useEffect(() => { - fetchData(userId); -}, [userId]); -``` - -### State Updates on Unmounted Components - -```tsx -// ❌ BAD: No cleanup -useEffect(() => { - fetchUser(id).then(setUser); -}, [id]); - -// ✅ GOOD: Cleanup function -useEffect(() => { - let cancelled = false; - - fetchUser(id).then(user => { - if (!cancelled) setUser(user); - }); - - return () => { - cancelled = true; - }; -}, [id]); -``` - -### Prop Drilling - -```tsx -// ❌ BAD: Passing props through many levels - - -
- -
-
-
- -// ✅ GOOD: Use context - - - -
- {/* Gets user from context */} -
-
-
-
-``` - -### Not Memoizing Callbacks - -```tsx -// ❌ BAD: New function every render - handleUpdate(id, data)} /> - -// ✅ GOOD: Memoized callback -const handleUpdate = useCallback((data) => { - updateData(id, data); -}, [id]); - - -``` - -## Component Patterns - -### Compound Components - -```tsx -function Tabs({ children }: { children: ReactNode }) { - const [activeTab, setActiveTab] = useState(0); - - return ( - - {children} - - ); -} - -Tabs.List = function TabsList({ children }: { children: ReactNode }) { - return
{children}
; -}; - -Tabs.Tab = function Tab({ index, children }: { index: number; children: ReactNode }) { - const { activeTab, setActiveTab } = useTabsContext(); - return ( - - ); -}; - -// Usage - - - Tab 1 - Tab 2 - - -``` - -### Render Props - -```tsx -interface DataLoaderProps { - url: string; - children: (data: T | null, loading: boolean) => ReactNode; -} - -function DataLoader({ url, children }: DataLoaderProps) { - const [data, setData] = useState(null); - const [loading, setLoading] = useState(true); - - useEffect(() => { - fetch(url) - .then(res => res.json()) - .then(setData) - .finally(() => setLoading(false)); - }, [url]); - - return <>{children(data, loading)}; -} - -// Usage - url="/api/user"> - {(user, loading) => ( - loading ? : - )} - -``` - -## Integration with Frameworks - -### With Next.js - -See [Next.js skill](/claudekit/skills/frameworks/nextjs) for server components and App Router patterns. - -### With Testing - -```tsx -import { render, screen } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; - -it('should increment count on click', async () => { - render(); - - const button = screen.getByRole('button', { name: /increment/i }); - await userEvent.click(button); - - expect(screen.getByText('Count: 1')).toBeInTheDocument(); -}); -``` - -## Related Skills - -- [TypeScript](/claudekit/skills/languages/typescript) - Type safety -- [Next.js](/claudekit/skills/frameworks/nextjs) - Full-stack React -- [Tailwind CSS](/claudekit/skills/frontend/tailwind) - Styling -- [vitest](/claudekit/skills/testing/vitest) - Testing diff --git a/website/src/content/docs/skills/languages/javascript.md b/website/src/content/docs/skills/languages/javascript.md deleted file mode 100644 index ed8fd52..0000000 --- a/website/src/content/docs/skills/languages/javascript.md +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: JavaScript -description: Modern JavaScript (ES6+) patterns and best practices ---- - -The JavaScript skill provides expertise in modern JavaScript (ES6+) for Node.js and browser environments. - -## When Activated - -- Working with JavaScript files (`.js`, `.mjs`) -- Browser scripting -- Node.js applications without TypeScript - -## Core Patterns - -### Modern Syntax - -```javascript -// Destructuring -const { name, email } = user; -const [first, ...rest] = items; - -// Spread operator -const merged = { ...defaults, ...options }; -const combined = [...array1, ...array2]; - -// Template literals -const message = `Hello, ${name}!`; - -// Optional chaining and nullish coalescing -const city = user?.address?.city ?? 'Unknown'; -``` - -### Async Patterns - -```javascript -// Async/await -async function fetchData(url) { - const response = await fetch(url); - if (!response.ok) throw new Error('Fetch failed'); - return response.json(); -} - -// Promise.all for parallel -const results = await Promise.all([ - fetchData(url1), - fetchData(url2), -]); - -// Error handling -try { - const data = await fetchData(url); -} catch (error) { - console.error('Failed:', error.message); -} -``` - -### Array Methods - -```javascript -// Map, filter, reduce -const names = users.map(u => u.name); -const active = users.filter(u => u.active); -const total = items.reduce((sum, i) => sum + i.price, 0); - -// Find and includes -const user = users.find(u => u.id === id); -const hasAdmin = users.some(u => u.role === 'admin'); -``` - -### Classes - -```javascript -class UserService { - #db; // Private field - - constructor(database) { - this.#db = database; - } - - async findById(id) { - return this.#db.users.find(u => u.id === id); - } -} -``` - -## Best Practices - -1. **Use `const` by default, `let` when needed** -2. **Avoid `var` - use block-scoped declarations** -3. **Use arrow functions for callbacks** -4. **Handle all promise rejections** -5. **Use ESLint for consistent style** - -## Common Pitfalls - -### Implicit Type Coercion - -```javascript -// ❌ BAD: Uses == -if (value == null) { } - -// ✅ GOOD: Uses === -if (value === null || value === undefined) { } -// Or better: -if (value == null) { } // Only for null/undefined check -``` - -### Callback Hell - -```javascript -// ❌ BAD: Nested callbacks -getData(function(a) { - getMoreData(a, function(b) { - getMoreData(b, function(c) { - // ... - }); - }); -}); - -// ✅ GOOD: Async/await -const a = await getData(); -const b = await getMoreData(a); -const c = await getMoreData(b); -``` - -### Mutating Objects - -```javascript -// ❌ BAD: Mutates original -function addProperty(obj) { - obj.newProp = 'value'; - return obj; -} - -// ✅ GOOD: Creates new object -function addProperty(obj) { - return { ...obj, newProp: 'value' }; -} -``` - -### Not Handling Errors - -```javascript -// ❌ BAD: Unhandled rejection -async function loadData() { - const data = await fetch(url); - return data.json(); -} - -// ✅ GOOD: Handle errors -async function loadData() { - try { - const response = await fetch(url); - if (!response.ok) { - throw new Error(`HTTP ${response.status}`); - } - return response.json(); - } catch (error) { - console.error('Load failed:', error); - throw error; - } -} -``` - -## Related Skills - -- [TypeScript](/claudekit/skills/languages/typescript) - Typed JavaScript -- [React](/claudekit/skills/frameworks/react) - UI components -- [Next.js](/claudekit/skills/frameworks/nextjs) - Full-stack framework diff --git a/website/src/content/docs/skills/languages/python.md b/website/src/content/docs/skills/languages/python.md deleted file mode 100644 index 1c9d0ed..0000000 --- a/website/src/content/docs/skills/languages/python.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: Python -description: Modern Python development with type hints, async, and best practices ---- - -The Python skill provides expertise in modern Python development including type hints, async patterns, dataclasses, and Pythonic idioms. - -## When Activated - -- Working with Python files (`.py`) -- Writing Python scripts or applications -- Using Python frameworks (Django, FastAPI, Flask) -- Data processing and automation - -## Core Patterns - -### Type Hints - -```python -from typing import Optional, List, Dict, Union -from collections.abc import Callable - -def process_items( - items: List[str], - callback: Callable[[str], None], - config: Optional[Dict[str, Any]] = None -) -> List[str]: - """Process items with optional callback.""" - return [callback(item) for item in items] -``` - -### Async/Await - -```python -import asyncio -from typing import List - -async def fetch_data(url: str) -> dict: - async with aiohttp.ClientSession() as session: - async with session.get(url) as response: - return await response.json() - -async def fetch_all(urls: List[str]) -> List[dict]: - return await asyncio.gather(*[fetch_data(url) for url in urls]) -``` - -### Context Managers - -```python -from contextlib import contextmanager - -@contextmanager -def managed_resource(): - resource = acquire_resource() - try: - yield resource - finally: - release_resource(resource) - -# Usage -with managed_resource() as r: - r.do_something() -``` - -### Dataclasses - -```python -from dataclasses import dataclass, field -from datetime import datetime - -@dataclass -class User: - id: int - email: str - name: str - created_at: datetime = field(default_factory=datetime.now) - - def __post_init__(self): - self.email = self.email.lower() -``` - -### Pydantic Models - -```python -from pydantic import BaseModel, EmailStr, Field - -class UserCreate(BaseModel): - email: EmailStr - name: str = Field(min_length=1, max_length=100) - password: str = Field(min_length=8) - - class Config: - str_strip_whitespace = True -``` - -## Best Practices - -1. **Use type hints for all public functions** -2. **Use dataclasses or Pydantic for data models** -3. **Prefer context managers for resource management** -4. **Use async for I/O-bound operations** -5. **Follow PEP 8 style guidelines** - -## Common Pitfalls - -### Mutable Default Arguments - -```python -# ❌ BAD: Mutable default -def add_item(item, items=[]): - items.append(item) - return items - -# ✅ GOOD: Use None and initialize -def add_item(item, items=None): - if items is None: - items = [] - items.append(item) - return items -``` - -### Not Closing Resources - -```python -# ❌ BAD: Manual resource management -file = open('data.txt') -data = file.read() -file.close() - -# ✅ GOOD: Use with statement -with open('data.txt') as file: - data = file.read() -``` - -### Blocking in Async - -```python -# ❌ BAD: Blocking call in async function -async def process(): - result = expensive_cpu_work() # Blocks event loop - return result - -# ✅ GOOD: Run in thread pool -async def process(): - loop = asyncio.get_event_loop() - result = await loop.run_in_executor(None, expensive_cpu_work) - return result -``` - -### Catching Bare Exceptions - -```python -# ❌ BAD: Catching everything -try: - risky_operation() -except: - handle_error() - -# ✅ GOOD: Specific exceptions -try: - risky_operation() -except (ValueError, TypeError) as e: - handle_error(e) -``` - -## Integration with Frameworks - -### With FastAPI - -See [FastAPI skill](/claudekit/skills/frameworks/fastapi) for API development patterns. - -### With Django - -See [Django skill](/claudekit/skills/frameworks/django) for web application patterns. - -### With pytest - -See pytest skill for testing patterns. - -## Related Skills - -- [FastAPI](/claudekit/skills/frameworks/fastapi) - REST API development -- [Django](/claudekit/skills/frameworks/django) - Web applications -- [pytest](/claudekit/skills/testing/pytest) - Testing framework -- [PostgreSQL](/claudekit/skills/databases/postgresql) - Database integration diff --git a/website/src/content/docs/skills/languages/typescript.md b/website/src/content/docs/skills/languages/typescript.md deleted file mode 100644 index 5eebad3..0000000 --- a/website/src/content/docs/skills/languages/typescript.md +++ /dev/null @@ -1,214 +0,0 @@ ---- -title: TypeScript -description: TypeScript development with strict typing and modern patterns ---- - -The TypeScript skill provides expertise in strict typing, advanced type utilities, and modern TypeScript patterns. - -## When Activated - -- Working with TypeScript files (`.ts`, `.tsx`) -- Building typed JavaScript applications -- React/Next.js development -- Node.js backend development - -## Core Patterns - -### Type Definitions - -```typescript -// Interfaces for objects -interface User { - id: string; - email: string; - name: string; - createdAt: Date; -} - -// Types for unions and utilities -type Status = 'pending' | 'active' | 'inactive'; -type UserWithStatus = User & { status: Status }; - -// Generic types -type ApiResponse = { - data: T; - error?: string; - status: number; -}; -``` - -### Utility Types - -```typescript -// Partial - all properties optional -type UserUpdate = Partial; - -// Pick - select properties -type UserPreview = Pick; - -// Omit - exclude properties -type UserWithoutId = Omit; - -// Record - dictionary type -type UserMap = Record; -``` - -### Async Patterns - -```typescript -async function fetchUser(id: string): Promise { - const response = await fetch(`/api/users/${id}`); - if (!response.ok) { - throw new Error(`Failed to fetch user: ${response.status}`); - } - return response.json(); -} - -// Error handling -async function safeOperation( - operation: () => Promise -): Promise<[T, null] | [null, Error]> { - try { - const result = await operation(); - return [result, null]; - } catch (error) { - return [null, error as Error]; - } -} -``` - -### Class Patterns - -```typescript -class UserService { - constructor(private readonly db: Database) {} - - async findById(id: string): Promise { - return this.db.users.findUnique({ where: { id } }); - } - - async create(data: UserCreate): Promise { - return this.db.users.create({ data }); - } -} -``` - -### Zod Validation - -```typescript -import { z } from 'zod'; - -const UserSchema = z.object({ - email: z.string().email(), - name: z.string().min(1).max(100), - password: z.string().min(8), -}); - -type UserInput = z.infer; - -function validateUser(data: unknown): UserInput { - return UserSchema.parse(data); -} -``` - -## Best Practices - -1. **Enable strict mode in tsconfig.json** -2. **Avoid `any` - use `unknown` and type guards** -3. **Use interfaces for object shapes, types for unions** -4. **Prefer `const` assertions for literal types** -5. **Use discriminated unions for state** - -## Common Pitfalls - -### Using `any` - -```typescript -// ❌ BAD: Defeats type safety -function process(data: any) { - return data.value; -} - -// ✅ GOOD: Use unknown and type guards -function process(data: unknown) { - if (typeof data === 'object' && data !== null && 'value' in data) { - return (data as { value: string }).value; - } - throw new Error('Invalid data'); -} -``` - -### Not Handling Null/Undefined - -```typescript -// ❌ BAD: Assumes user exists -function getUserName(id: string): string { - const user = findUser(id); - return user.name; // Might crash -} - -// ✅ GOOD: Handle null case -function getUserName(id: string): string | null { - const user = findUser(id); - return user?.name ?? null; -} -``` - -### Type Assertions Over Guards - -```typescript -// ❌ BAD: Unsafe type assertion -const user = data as User; - -// ✅ GOOD: Type guard -function isUser(data: unknown): data is User { - return ( - typeof data === 'object' && - data !== null && - 'id' in data && - 'email' in data - ); -} - -if (isUser(data)) { - // data is safely typed as User here -} -``` - -### Ignoring Errors - -```typescript -// ❌ BAD: Unhandled rejection -async function loadData() { - const data = await fetchData(); - return data; -} - -// ✅ GOOD: Handle errors -async function loadData() { - try { - const data = await fetchData(); - return data; - } catch (error) { - console.error('Failed to load data:', error); - throw error; - } -} -``` - -## Integration with Frameworks - -### With React - -See [React skill](/claudekit/skills/frameworks/react) for component patterns. - -### With Next.js - -See [Next.js skill](/claudekit/skills/frameworks/nextjs) for full-stack patterns. - -## Related Skills - -- [JavaScript](/claudekit/skills/languages/javascript) - Parent language -- [React](/claudekit/skills/frameworks/react) - UI components -- [Next.js](/claudekit/skills/frameworks/nextjs) - Full-stack framework -- [vitest](/claudekit/skills/testing/vitest) - Testing framework diff --git a/website/src/content/docs/skills/methodology/brainstorming.md b/website/src/content/docs/skills/methodology/brainstorming.md deleted file mode 100644 index ff9380f..0000000 --- a/website/src/content/docs/skills/methodology/brainstorming.md +++ /dev/null @@ -1,378 +0,0 @@ ---- -title: Brainstorming -description: Interactive design refinement through collaborative dialogue ---- - -The Brainstorming skill transforms rough ideas into fully-formed designs through structured questioning and incremental validation. - -## Overview - -Brainstorming is an interactive design methodology that uses sequential questioning to clarify requirements, explore alternatives, and validate design decisions before implementation begins. - -**Core Principle**: One question at a time produces better designs than dumping everything at once. - -## When to Use - -Use brainstorming for: - -- Designing new features with unclear requirements -- Exploring architecture decisions -- Refining user requirements -- Breaking down complex problems -- When multiple valid approaches exist - -## When NOT to Use - -Skip brainstorming for: - -- Clear "mechanical" processes with known implementation -- Simple bug fixes with obvious solutions -- Tasks with explicit requirements already defined - -## The Three-Phase Process - -### Phase 1: Understanding - -**Goal**: Clarify requirements through sequential questioning. - -**Rules**: -- Ask only ONE question per message -- Break complex topics into multiple questions -- Prefer multiple-choice over open-ended questions -- Wait for user response before next question - -**Example**: - -``` -❌ BAD: "What authentication method do you want, and should we support SSO, - and what about password requirements?" - -✅ GOOD: "Which authentication method should we use? - a) Username/password only - b) OAuth (Google, GitHub) - c) Both options" -``` - -### Phase 2: Exploration - -**Goal**: Present alternatives with clear trade-offs. - -**Process**: -1. Present 2-3 different approaches -2. Lead with the recommended option -3. Explain trade-offs for each -4. Let user choose direction - -**Format**: - -```markdown -## Approach 1: JWT-Based Auth (Recommended) -Stateless tokens stored in HTTP-only cookies. - -- **Pros**: Scalable, no server-side session storage, works across services -- **Cons**: Cannot revoke tokens before expiry, larger cookie size - -## Approach 2: Session-Based Auth -Server-side sessions with session IDs. - -- **Pros**: Easy revocation, smaller cookie size, familiar pattern -- **Cons**: Requires session store (Redis), harder to scale horizontally - -Which approach aligns better with your goals? -``` - -### Phase 3: Design Presentation - -**Goal**: Present validated design in digestible chunks. - -**Rules**: -- Break design into 200-300 word sections -- Validate incrementally after each section -- Be flexible - allow clarification or changes - -**Sections to Cover**: -1. Architecture overview -2. Component breakdown -3. Data flow -4. Error handling -5. Testing considerations - -## Core Principles - -### YAGNI Ruthlessly - -Remove unnecessary features aggressively: - -- Question every "nice to have" -- Start with minimal viable design -- Add complexity only when justified -- "We might need this later" = remove it - -**Example**: - -``` -User: "Let's add user roles, permissions, and audit logging" - -Brainstorming: "Do you need all of those now, or can we start with - basic roles and add permissions/audit later when - you have real requirements?" -``` - -### One Question at a Time - -Sequential questioning produces better results: - -- Gives user time to think deeply -- Prevents overwhelming with choices -- Creates natural conversation flow -- Allows follow-up on unclear points - -### Multiple-Choice Preference - -When possible, provide structured options: - -``` -Instead of: "How should we handle errors?" - -Ask: "How should we handle validation errors? - a) Return 400 with error details in JSON - b) Return 422 with field-specific errors - c) Return 400 with generic error message" -``` - -Benefits: -- Reduces cognitive load -- Surfaces your understanding -- Makes decisions concrete -- Still allow "Other" option - -## Output Format - -After design validation, document to timestamped markdown: - -```markdown -# Design: User Email Verification -Date: 2025-01-29 - -## Summary -Add email verification to registration flow. Users receive verification -email on signup, click link to verify, and are marked as verified in database. - -## Architecture -- Verification token: JWT with 24-hour expiry -- Storage: Add `verified` boolean to User table -- Email: SendGrid API for delivery - -## Components -### UserService -- `createUser()`: Create user, send verification email -- `verifyEmail()`: Validate token, mark user verified - -### EmailService -- `sendVerificationEmail()`: Generate token, send email - -## Data Flow -1. User registers → User created with verified=false -2. System generates JWT token with user email -3. Email sent with verification link -4. User clicks link → Token validated -5. User marked verified=true - -## Error Handling -- Expired token: Return error, offer resend -- Invalid token: Return 400 error -- Already verified: Return success (idempotent) - -## Testing Strategy -- Unit: Token generation, validation logic -- Integration: Full registration → verification flow -- Manual: Test email delivery in staging - -## Open Questions -- Should unverified users have limited access? (Deferred to v2) -``` - -## Activation - -### Via Command - -```bash -/brainstorm "user authentication system" -/brainstorm --interactive "payment processing" -``` - -### Via Mode - -```bash -/mode brainstorm -# Now in brainstorming mode for the session -``` - -### Implicit Activation - -Brainstorming activates automatically when: -- `/feature` command encounters unclear requirements -- Design discussion is needed before planning -- Multiple approaches are possible - -## Integration with Other Skills - -### Flows to Writing Plans - -After brainstorming completes: - -```bash -# 1. Brainstorm the design -/brainstorm "email verification" - -# 2. Convert design to implementation plan -/plan designs/email-verification.md -``` - -### Combines with Sequential Thinking - -For complex decisions: - -```bash -# Use sequential thinking during brainstorming -/brainstorm --use-skill=sequential-thinking "database architecture" -``` - -## Examples - -### Example 1: Authentication Design - -``` -User: I need authentication - -Claude: What type of users will authenticate? - a) End users (customers) - b) Administrators only - c) Both end users and admins - -User: Both - -Claude: Should end users and admins use the same auth system? - a) Yes, same system with role differentiation - b) No, separate systems (admin has higher security) - -User: Same system - -Claude: Which authentication method? - a) Email/password - b) OAuth (Google, GitHub, etc.) - c) Both options - -User: Both - -Claude: [Presents 2-3 architecture approaches with trade-offs] -``` - -### Example 2: API Design - -``` -User: Design a REST API for products - -Claude: What operations do you need? - a) Read-only (GET products, search) - b) Full CRUD (create, read, update, delete) - c) Read + Create only - -User: Full CRUD - -Claude: Who can create/update/delete products? - a) Anyone (public API) - b) Authenticated users - c) Admins only - -User: Admins only - -Claude: [Presents API design with endpoints and auth requirements] -``` - -## Best Practices - -### Ask Better Questions - -``` -❌ "What do you want?" -✅ "Should new users start with limited access or full access?" - -❌ "How should this work?" -✅ "When a user clicks 'delete', should we: - a) Delete immediately - b) Soft delete (mark as deleted) - c) Require confirmation first" -``` - -### Validate Incrementally - -``` -After presenting architecture: -"Does this architecture make sense so far, or should I clarify anything?" - -After data flow: -"Is this the flow you envisioned, or should we adjust?" -``` - -### Push Back on Complexity - -``` -User: "Let's add caching, rate limiting, and API versioning" - -Claude: "Those are all valuable features. Which one solves your - immediate problem? We can add the others later when needed." -``` - -## Common Patterns - -### The "Why" Question - -Always understand motivation: - -``` -User: "Add pagination to the API" -Claude: "What problem does pagination solve for you? - a) Performance (large datasets) - b) UX (easier navigation) - c) Both" -``` - -### The Scope Question - -Define boundaries early: - -``` -User: "Build a notification system" -Claude: "What types of notifications? - a) Email only - b) Email + SMS - c) Email + SMS + Push" -``` - -### The Constraint Question - -Identify limitations: - -``` -User: "Design file upload" -Claude: "What's the maximum file size you need to support? - a) < 10 MB (standard) - b) 10-100 MB (medium) - c) > 100 MB (large, needs chunking)" -``` - -## Next Steps - -After brainstorming: - -1. **Save the design**: Commit design doc to version control -2. **Create plan**: Use [Writing Plans](/claudekit/skills/methodology/writing-plans) skill -3. **Implement**: Use [Executing Plans](/claudekit/skills/methodology/executing-plans) skill -4. **Review**: Use [Code Review](/claudekit/skills/methodology/code-review) skill - -## Related Skills - -- [Writing Plans](/claudekit/skills/methodology/writing-plans) - Convert designs to tasks -- [Sequential Thinking](/claudekit/skills/methodology/sequential-thinking) - Deep analysis -- [Executing Plans](/claudekit/skills/methodology/executing-plans) - Implement designs diff --git a/website/src/content/docs/skills/methodology/code-review.md b/website/src/content/docs/skills/methodology/code-review.md deleted file mode 100644 index 7f93122..0000000 --- a/website/src/content/docs/skills/methodology/code-review.md +++ /dev/null @@ -1,455 +0,0 @@ ---- -title: Code Review -description: Request and receive code reviews effectively ---- - -The Code Review skill covers both requesting reviews with clear context and processing feedback systematically. - -## Overview - -Effective code review involves clear communication when requesting reviews and systematic processing of feedback. This skill combines both requesting and receiving reviews into a cohesive workflow. - -## Requesting Code Reviews - -### When to Request - -- After completing a task (before proceeding to next) -- After implementing a feature -- Before merging to main branch -- When unsure about implementation approach -- After fixing critical bugs - -### Review Request Components - -#### 1. Scope Definition - -Clearly state what should be reviewed: - -```markdown -## Review Scope - -**Files changed**: -- src/services/user-service.ts (modified) -- src/services/user-service.test.ts (added) -- src/types/user.ts (modified) - -**Lines changed**: ~150 additions, ~20 deletions - -**Not in scope** (don't review): -- package.json changes (unrelated dependency update) -- Generated files in dist/ -``` - -#### 2. Context - -Explain why these changes were made: - -```markdown -## Context - -**Task**: Implement user email verification - -**Requirements**: -- Users must verify email before accessing features -- Verification link expires after 24 hours -- Users can request new verification email - -**Design decisions**: -- Used JWT for verification token (stateless) -- Stored verification status in existing User table -``` - -#### 3. Areas of Concern - -Highlight where you want focused attention: - -```markdown -## Areas of Concern - -1. **Security**: Is the token generation secure enough? -2. **Error handling**: Are all edge cases covered? -3. **Performance**: Will the verification lookup be efficient? -``` - -#### 4. Test Coverage - -Show what's tested: - -```markdown -## Test Coverage - -- Unit tests: 8 new tests in user-service.test.ts -- Integration: Manual testing of full flow -- Edge cases: Expired token, invalid token, already verified - -**Not tested** (known gaps): -- Load testing with many concurrent verifications -``` - -### Review Request Template - -```markdown -## Code Review Request - -### Summary -Implemented email verification for new user registrations. - -### Files Changed -- `src/services/user-service.ts` - Added verification methods -- `src/services/user-service.test.ts` - Added 8 unit tests -- `src/types/user.ts` - Added verified field - -### Context -Users now receive a verification email on signup. They must click -the link within 24 hours to verify their account. - -### Implementation Notes -- JWT tokens for stateless verification -- Tokens expire after 24 hours -- Idempotent verification (safe to verify twice) - -### Areas for Focus -1. Token security (generation and validation) -2. Edge case handling -3. Test coverage completeness - -### Testing -- [x] Unit tests added/updated -- [x] Integration tests pass -- [ ] E2E tests (not applicable) - -### Checklist -- [x] Code follows project conventions -- [x] No security vulnerabilities introduced -- [x] Documentation updated if needed -``` - -## Receiving Code Reviews - -### Feedback Categories - -#### Critical Issues - -**Definition**: Must fix before proceeding. - -Examples: -- SQL injection vulnerability -- Unhandled null pointer -- Data corruption possibility -- Authentication bypass - -**Response**: Fix immediately. Do not proceed until resolved. - -#### Important Issues - -**Definition**: Should fix before proceeding. - -Examples: -- Missing error handling -- Inefficient algorithm -- Poor naming -- Missing tests for edge cases - -**Response**: Fix before merging. May defer to follow-up if blocking. - -#### Minor Issues - -**Definition**: Can fix later. - -Examples: -- Variable naming suggestions -- Comment improvements -- Minor refactoring opportunities -- Documentation polish - -**Response**: Note for later. Can merge without addressing. - -### Processing Workflow - -#### Step 1: Categorize All Feedback - -```markdown -## Review Feedback - -### Critical (Must Fix) -1. Line 45: SQL query vulnerable to injection -2. Line 89: User data exposed in logs - -### Important (Should Fix) -1. Line 23: Missing null check -2. Line 67: Test doesn't cover error path - -### Minor (Can Defer) -1. Line 12: Consider renaming 'x' to 'count' -2. Line 34: Could extract to helper function -``` - -#### Step 2: Fix Critical Issues First - -```markdown -Addressing critical issue 1: -- File: src/db/queries.ts:45 -- Issue: SQL injection vulnerability -- Fix: Use parameterized query -- Verification: Tested with malicious input -``` - -#### Step 3: Fix Important Issues - -```markdown -Addressing important issue 1: -- File: src/services/user.ts:23 -- Issue: Missing null check -- Fix: Added guard clause -- Verification: Test added for null case -``` - -#### Step 4: Note Minor Issues - -```markdown -Deferred for follow-up: -- Line 12: Variable rename (tracked in TODO) -- Line 34: Extract helper (low priority) -``` - -#### Step 5: Request Re-Review - -After fixes applied: - -```markdown -## Re-Review Request - -### Fixed Issues -- [x] SQL injection (line 45) - Now uses parameterized query -- [x] Data exposure (line 89) - Removed user data from logs -- [x] Null check (line 23) - Added guard clause -- [x] Test coverage (line 67) - Added error path test - -### Deferred (Minor) -- Variable rename (line 12) - Will address in cleanup PR - -### Changes Since Last Review -- 4 files modified -- 2 tests added -- All previous feedback addressed -``` - -## Review Types - -### Quick Review - -For small, low-risk changes: - -```markdown -## Quick Review: Fix typo in error message - -**File**: src/errors.ts -**Change**: Fixed "recieved" → "received" in error message -**Risk**: None -``` - -### Standard Review - -For typical feature work: - -```markdown -## Review: Add user preferences - -**Files**: 3 files, ~200 lines -**Context**: Users can now save display preferences -**Focus**: Data validation, storage approach -``` - -### Critical Review - -For high-risk changes: - -```markdown -## CRITICAL REVIEW: Authentication refactor - -**Files**: 12 files, ~800 lines -**Risk**: HIGH - Authentication system changes -**Required reviewers**: Security team -**Focus**: Token handling, session management, encryption -``` - -## Handling Disagreements - -### When You Disagree - -1. Don't dismiss immediately -2. Consider the reviewer's perspective -3. Explain your reasoning -4. Provide evidence (code, tests, docs) -5. Be open to being wrong -6. Escalate if needed (tech lead, team discussion) - -### Disagreement Response Template - -```markdown -## Re: Token expiration approach - -I considered this feedback carefully. Here's my perspective: - -**Reviewer's concern**: Token should expire after 1 hour -**My reasoning**: 24 hours allows users to verify later -**Evidence**: User research shows 40% verify after 6+ hours -**Proposed resolution**: Keep 24 hours, add configurable option -``` - -## Common Feedback Types - -### Security Issues - -Always fix immediately: - -```typescript -// Before (vulnerable) -const query = `SELECT * FROM users WHERE id = '${userId}'`; - -// After (secure) -const query = 'SELECT * FROM users WHERE id = $1'; -const result = await db.query(query, [userId]); -``` - -### Error Handling - -Add comprehensive handling: - -```typescript -// Before -const user = await getUser(id); -return user.name; - -// After -const user = await getUser(id); -if (!user) { - throw new NotFoundError(`User ${id} not found`); -} -return user.name; -``` - -### Test Coverage - -Add missing tests: - -```typescript -// Before: Only happy path tested -it('should return user', async () => { - const user = await getUser('valid-id'); - expect(user).toBeDefined(); -}); - -// After: Edge cases covered -it('should return user', async () => { /* ... */ }); -it('should throw NotFoundError for missing user', async () => { /* ... */ }); -it('should throw ValidationError for invalid id', async () => { /* ... */ }); -``` - -## Re-Review Checklist - -Before requesting re-review: - -- [ ] All Critical issues fixed -- [ ] All Important issues fixed (or explicitly deferred with reason) -- [ ] Minor issues noted for follow-up -- [ ] Tests added/updated for fixes -- [ ] Full test suite passes -- [ ] Changes summarized for reviewer - -## Iteration Limits - -If review requires 3+ cycles: - -1. STOP -2. Schedule discussion with reviewer -3. Identify root cause of misalignment -4. May need design discussion -5. Don't keep iterating endlessly - -## Activation - -### Requesting Reviews - -```bash -/review src/services/user-service.ts -/review --persona=security src/auth/ -/ship --review "implement email verification" -``` - -### After Executing Plans - -Automatic code review between tasks when using [Executing Plans](/claudekit/skills/methodology/executing-plans). - -## Integration with Other Skills - -### With Executing Plans - -[Executing Plans](/claudekit/skills/methodology/executing-plans) includes automatic code review: -- Review after each task -- Categorize issues (Critical/Important/Minor) -- Fix before proceeding - -### With TDD - -Code reviews check: -- Tests exist for new code -- Tests follow TDD pattern (written first) -- Tests cover edge cases - -### With Verification - -Reviews verify: -- Claims are backed by evidence -- Tests actually pass -- No unverified assertions - -## Best Practices - -### Keep Reviews Focused - -``` -✅ "Review the user verification feature (3 files)" -❌ "Review my last week of work" -``` - -### Provide Runnable Context - -```markdown -## To test locally -1. git checkout feature/email-verification -2. npm install -3. npm test -- --grep "email verification" -``` - -### Be Specific About Concerns - -``` -✅ "I'm unsure about the error handling in lines 45-60" -❌ "Let me know if anything looks wrong" -``` - -### Respond to All Feedback - -```markdown -✅ Issue 1: Fixed -✅ Issue 2: Fixed -✅ Issue 3: Disagree, here's why (with evidence) -✅ Issue 4: Deferred to follow-up PR #123 -``` - -## Next Steps - -After review approval: - -1. **Merge code**: If all issues resolved -2. **Follow-up tasks**: Create tickets for deferred issues -3. **Documentation**: Update if needed -4. **Deployment**: Use [deploy command](/claudekit/commands/deploy) - -## Related Skills - -- [Executing Plans](/claudekit/skills/methodology/executing-plans) - Automated reviews -- [TDD](/claudekit/skills/methodology/tdd) - Test coverage checks -- [Verification](/claudekit/skills/methodology/verification) - Evidence-based claims -- [Security (OWASP)](/claudekit/skills/security/owasp) - Security review focus diff --git a/website/src/content/docs/skills/methodology/executing-plans.md b/website/src/content/docs/skills/methodology/executing-plans.md deleted file mode 100644 index 404f18a..0000000 --- a/website/src/content/docs/skills/methodology/executing-plans.md +++ /dev/null @@ -1,472 +0,0 @@ ---- -title: Executing Plans -description: Subagent-driven plan execution with quality gates ---- - -The Executing Plans skill automates implementation of detailed plans using fresh agents per task and mandatory code review between tasks. - -## Overview - -Executing Plans bridges planning and delivery through systematic, quality-gated execution. Each task runs in isolation with independent review, preventing context pollution and ensuring consistent quality. - -**Core Pattern**: Fresh subagent per task + review between tasks = high quality, fast iteration - -## When to Use - -- Executing plans created with [Writing Plans](/claudekit/skills/methodology/writing-plans) skill -- Staying in current session with independent tasks -- Wanting quality gates without human delays -- Systematic implementation with verification - -## When NOT to Use - -- Plan needs review first (use brainstorming) -- Tasks are tightly coupled and need shared context -- Plan requires revision during execution - -## The Workflow - -### Step 1: Load Plan - -```markdown -1. Read the plan file -2. Verify plan is complete and approved -3. Create task tracking with all tasks -4. Set first task to in_progress -``` - -### Step 2: Execute Task - -For each task: - -```markdown -1. Dispatch fresh subagent with task details -2. Subagent implements following TDD cycle: - - Write failing test - - Verify test fails - - Implement minimally - - Verify test passes - - Commit -3. Subagent returns completion summary -``` - -### Step 3: Code Review - -After each task: - -```markdown -1. Dispatch code-reviewer subagent -2. Review scope: only changes from current task -3. Reviewer returns findings: - - Critical: Must fix before proceeding - - Important: Should fix before proceeding - - Minor: Can fix later -``` - -### Step 4: Handle Review Findings - -```markdown -IF Critical or Important issues found: - 1. Dispatch fix subagent for each issue - 2. Re-request code review - 3. Repeat until no Critical/Important issues - -IF only Minor issues: - 1. Note for later cleanup - 2. Proceed to next task -``` - -### Step 5: Mark Complete - -```markdown -1. Update task tracking - mark task completed -2. Move to next task -3. Repeat from Step 2 -``` - -### Step 6: Final Review - -After all tasks complete: - -```markdown -1. Dispatch comprehensive code review -2. Review entire implementation against plan -3. Verify all success criteria met -4. Run full test suite -5. Use finishing-development-branch skill -``` - -## Critical Rules - -### Never Skip Code Reviews - -Every task must be reviewed before proceeding. No exceptions. - -**Why**: Catches issues when they're easiest to fix. - -### Never Proceed with Critical Issues - -Critical issues must be fixed immediately: - -``` -implement → review → fix critical → re-review → proceed -``` - -**Not**: -``` -implement → review → note issue → proceed anyway -``` - -### Never Run Parallel Implementation - -Tasks run sequentially: - -``` -❌ WRONG: Run Task 1, 2, 3 simultaneously -✅ RIGHT: Run Task 1 → Review → Task 2 → Review → Task 3 → Review -``` - -**Why**: Each task may depend on previous tasks being correct. - -### Always Read Plan Before Implementing - -``` -❌ WRONG: Start coding based on memory of plan -✅ RIGHT: Read plan file, extract task details, then implement -``` - -## Subagent Communication - -### Implementation Subagent Prompt - -```markdown -## Task: Add verified flag to User model - -**Context**: Executing plan for Email Verification feature - -**Files to modify**: -- Modify: src/models/user.ts -- Test: src/models/user.test.ts - -**Steps**: -1. Write failing test for verified flag -2. Verify test fails (run npm test) -3. Add verified field to User model -4. Verify test passes -5. Commit changes - -**Requirements**: -- Follow TDD: test first, then implement -- Commit after completion -- Return summary of what was done - -**Output expected**: -- Files modified: [list] -- Tests added: [count] -- Commit hash: [hash] -- Any issues encountered: [none or details] -``` - -### Code Review Subagent Prompt - -```markdown -## Code Review Request - -**Scope**: Changes from Task 3: Add login endpoint - -**Files changed**: -- src/routes/auth.ts -- src/routes/auth.test.ts -- src/middleware/auth.ts - -**Review against**: -- Plan requirements for this task -- Code quality standards -- Security best practices -- Test coverage requirements - -**Return**: -- Critical issues (must fix before continuing) -- Important issues (should fix before continuing) -- Minor issues (can defer) -- Approval status (approved / needs fixes) -``` - -## Task Tracking - -Track status throughout execution: - -```markdown -| Task | Status | Reviewed | -|------|--------|----------| -| Task 1: Create model | completed | ✓ | -| Task 2: Add validation | completed | ✓ | -| Task 3: Create endpoint | in_progress | - | -| Task 4: Add tests | pending | - | -| Task 5: Documentation | pending | - | -``` - -Status values: -- `pending` - Not started -- `in_progress` - Currently being implemented -- `completed` - Done and reviewed - -## Error Handling - -### Task Fails - -```markdown -1. Capture error details -2. Attempt fix (max 2 retries) -3. If still failing, pause execution -4. Report to user with: - - Which task failed - - Error details - - Suggested resolution -5. Wait for user decision -``` - -### Review Finds Major Issues - -```markdown -1. List all Critical/Important issues -2. Dispatch fix subagent for each -3. Re-run code review -4. If issues persist after 2 cycles: - - Pause execution - - Report to user - - May need plan revision -``` - -## Activation - -### Via Command - -```bash -/execute-plan plans/feature-x.md -/execute-plan plans/feature-x.md --parallel-reviews # Review multiple tasks -``` - -### From Writing Plans - -```bash -/plan "add email verification" -# Plan created at plans/email-verification.md - -"Would you like to execute this plan now?" -> Yes - -# Begins execution automatically -``` - -## Example Execution - -```markdown -## Plan Execution: Email Verification - -### Status: In Progress (Task 3 of 8) - ---- - -### Task 1: Add verified flag ✓ -**Implementation**: Completed in 3 minutes -- Added `verified: boolean` field to User model -- Test: user.test.ts (1 new test) -- Commit: a1b2c3d - -**Code Review**: Approved -- No issues found -- Test coverage: 100% - ---- - -### Task 2: Create verification token ✓ -**Implementation**: Completed in 4 minutes -- Added token generation utility -- Test: token.test.ts (3 new tests) -- Commit: e4f5g6h - -**Code Review**: 1 Important issue found -- Issue: Token expiry not validated -- Fix: Added expiry check -- Re-review: Approved - ---- - -### Task 3: Send verification email ⏳ -**Status**: Implementation in progress... -``` - -## Completion Checklist - -Before declaring plan execution complete: - -- [ ] All tasks marked completed -- [ ] All code reviews passed -- [ ] Full test suite passes -- [ ] No Critical issues outstanding -- [ ] No Important issues outstanding -- [ ] Final comprehensive review done -- [ ] Ready for branch cleanup/merge - -## Integration with Other Skills - -### From Writing Plans - -```bash -# 1. Create plan -/plan "feature X" - -# 2. Execute plan -/execute-plan plans/feature-x.md -``` - -### With TDD - -Every task implementation follows [TDD](/claudekit/skills/methodology/tdd): -1. Write failing test -2. Verify it fails -3. Implement minimally -4. Verify it passes - -### With Code Review - -Automatic [code review](/claudekit/skills/methodology/code-review) after each task: -- Categorizes issues (Critical/Important/Minor) -- Enforces fixes before proceeding -- Maintains code quality - -### With Verification - -Uses [verification before completion](/claudekit/skills/methodology/verification): -- Never claims completion without proof -- Runs tests to verify -- Checks actual output - -## Best Practices - -### Review Scope - -Keep review focused on current task: - -``` -✅ "Review changes in src/auth.ts from Task 5" -❌ "Review the entire codebase" -``` - -### Fresh Agents - -Each task gets a clean slate: - -``` -Task 1 Agent: Focuses only on Task 1 -Task 2 Agent: No memory of Task 1 details -Task 3 Agent: No memory of Task 1 or 2 -``` - -**Benefit**: No context pollution, clearer focus. - -### Incremental Quality - -Fix issues immediately: - -``` -Task → Review → Issues Found → Fix → Re-review → Pass → Next Task -``` - -**Not**: -``` -Task 1 → Issues noted -Task 2 → More issues noted -Task 3 → Try to fix all issues (context lost) -``` - -## Common Patterns - -### Standard Task - -```markdown -1. Load task from plan -2. Dispatch implementation agent -3. Agent implements with TDD -4. Agent commits -5. Dispatch review agent -6. If approved → next task -7. If issues → fix → re-review -``` - -### Error Recovery - -```markdown -1. Task fails -2. Capture error -3. Attempt automatic fix -4. If fix works → review → proceed -5. If fix fails → pause → report to user -``` - -### Quality Gate - -```markdown -After each task: -1. Code review categorizes issues -2. Critical → Must fix (block) -3. Important → Should fix (block) -4. Minor → Note for later (allow) -``` - -## Troubleshooting - -### Task Keeps Failing - -```markdown -Problem: Task 5 fails 3 times - -Actions: -1. STOP execution -2. Review task requirements -3. Check if plan needs adjustment -4. May need to revise approach -5. Consult user before continuing -``` - -### Review Never Passes - -```markdown -Problem: Task 2 reviewed 3 times, still has issues - -Actions: -1. PAUSE execution -2. Review the review feedback -3. May indicate plan gap -4. May need design discussion -5. Don't iterate endlessly -``` - -### Tests Pass Individually, Fail Together - -```markdown -Problem: Each task's tests pass, but full suite fails - -Actions: -1. Identify test interdependencies -2. Fix test isolation -3. May need test setup/teardown improvements -4. Run full suite after each task (not just new tests) -``` - -## Next Steps - -After plan execution completes: - -1. **Final verification**: Run full test suite -2. **Cleanup**: Address Minor issues noted during reviews -3. **Documentation**: Update docs if needed -4. **Branch finishing**: Use finishing-development-branch skill - -## Related Skills - -- [Writing Plans](/claudekit/skills/methodology/writing-plans) - Create plans to execute -- [TDD](/claudekit/skills/methodology/tdd) - Test-first implementation -- [Code Review](/claudekit/skills/methodology/code-review) - Quality gates -- [Verification](/claudekit/skills/methodology/verification) - Prove completion diff --git a/website/src/content/docs/skills/methodology/sequential-thinking.md b/website/src/content/docs/skills/methodology/sequential-thinking.md deleted file mode 100644 index a22e12a..0000000 --- a/website/src/content/docs/skills/methodology/sequential-thinking.md +++ /dev/null @@ -1,391 +0,0 @@ ---- -title: Sequential Thinking -description: Step-by-step reasoning with evidence and confidence tracking ---- - -The Sequential Thinking skill provides a structured methodology for complex problem analysis using explicit evidence collection and confidence tracking. - -## Overview - -Sequential Thinking breaks down complex problems into systematic steps with documented evidence, hypotheses, and confidence scores. This approach creates an audit trail of decision-making and prevents jumping to conclusions. - -**Use for**: Complex debugging, architecture decisions, security analysis, performance investigation - -## When to Use - -- Complex debugging -- Architecture decisions -- Security analysis -- Performance investigation -- Any problem with multiple possible causes -- When decisions need documentation - -## The Sequential Process - -### Step 1: Define the Question - -Clearly state what you're investigating: - -```markdown -## Question -What is causing the authentication timeout for users with special characters in passwords? -``` - -### Step 2: Gather Evidence - -Collect all relevant information systematically: - -```markdown -## Evidence Collection - -### Evidence 1: Error Logs -- Source: `logs/auth-service.log` -- Finding: Timeout occurs at password encoding step -- Confidence: High (direct observation) - -### Evidence 2: Code Review -- Source: `src/auth/password.ts:42` -- Finding: URL encoding applied to password -- Confidence: High (code inspection) - -### Evidence 3: Test Results -- Source: Manual testing -- Finding: Works with alphanumeric, fails with `@#$` -- Confidence: High (reproducible) -``` - -### Step 3: Form Hypotheses - -Generate possible explanations: - -```markdown -## Hypotheses - -### Hypothesis A: URL Encoding Issue -- Evidence supporting: E1, E2, E3 -- Evidence against: None -- Probability: 80% - -### Hypothesis B: Character Set Mismatch -- Evidence supporting: E3 -- Evidence against: E2 (UTF-8 used) -- Probability: 15% - -### Hypothesis C: Database Encoding -- Evidence supporting: None directly -- Evidence against: E1 (fails before DB) -- Probability: 5% -``` - -### Step 4: Test Hypotheses - -Verify the most likely explanation: - -```markdown -## Testing - -### Test for Hypothesis A -Action: Remove URL encoding, use base64 instead -Result: Password `test@123` now works -Conclusion: Hypothesis A confirmed -``` - -### Step 5: Document Conclusion - -State the final answer with confidence: - -```markdown -## Conclusion - -**Root Cause**: URL encoding in password.ts:42 mangles special characters - -**Confidence**: 9/10 - -**Evidence Chain**: -1. Timeout at encoding step (logs) -2. URL encoding in code (review) -3. Special char passwords fail (testing) -4. Removing encoding fixes issue (verification) - -**Fix**: Replace URL encoding with base64 at line 42 -``` - -## Output Template - -```markdown -# Sequential Analysis: [Problem Description] - -## Question -[Clear statement of what we're investigating] - -## Evidence - -### Evidence 1: [Title] -- Source: [where found] -- Finding: [what it shows] -- Confidence: [High/Medium/Low] - -### Evidence 2: [Title] -... - -## Hypotheses - -### Hypothesis A: [Name] -- Supporting evidence: [list] -- Contradicting evidence: [list] -- Probability: [X%] - -### Hypothesis B: [Name] -... - -## Testing - -### Test 1: [What tested] -- Action: [what was done] -- Expected: [what should happen if hypothesis true] -- Actual: [what happened] -- Result: [confirms/refutes hypothesis] - -## Conclusion - -**Answer**: [clear statement] -**Confidence**: [X/10] -**Key Evidence**: [most important findings] -**Recommended Action**: [what to do next] -``` - -## Confidence Scoring - -| Score | Meaning | Evidence Required | -|-------|---------|-------------------| -| 9-10 | Certain | Multiple independent confirmations | -| 7-8 | High | Strong evidence, tested hypothesis | -| 5-6 | Medium | Good evidence, some uncertainty | -| 3-4 | Low | Limited evidence, multiple possibilities | -| 1-2 | Guess | Insufficient evidence | - -## Anti-Patterns - -### Jumping to Conclusions - -``` -❌ "The bug is probably in the database" -✅ "Let me gather evidence before hypothesizing" -``` - -### Confirmation Bias - -``` -❌ Only looking for evidence supporting first guess -✅ Actively seeking contradicting evidence -``` - -### Skipping Documentation - -``` -❌ Fixing without recording reasoning -✅ Document even simple analysis for future reference -``` - -## Activation - -### Via Mode - -```bash -/mode deep-research -# Enables sequential thinking for session -``` - -### Via Command - -```bash -/research --sequential "authentication timeout" -/debug --sequential "performance degradation" -``` - -### Explicit Request - -``` -"Use sequential thinking to analyze why the cache is returning stale data" -``` - -## Example Analysis - -```markdown -# Sequential Analysis: API Response Time Degradation - -## Question -Why did API response times increase from 100ms to 3000ms after deployment? - -## Evidence - -### Evidence 1: Deployment Timing -- Source: Deployment logs -- Finding: Degradation started 5 minutes after deploy at 2:34 PM -- Confidence: High (exact timing match) - -### Evidence 2: Database Query Logs -- Source: PostgreSQL slow query log -- Finding: No new slow queries, same query times as before -- Confidence: High (database not the cause) - -### Evidence 3: Code Changes -- Source: git diff deploy-123 -- Finding: Added Redis caching to user lookup -- Confidence: High (code inspection) - -### Evidence 4: Redis Metrics -- Source: Redis monitoring -- Finding: Redis responding in < 1ms per request -- Confidence: High (Redis not slow) - -### Evidence 5: Network Latency -- Source: Application metrics -- Finding: 2900ms spent waiting for external API -- Confidence: High (measured directly) - -### Evidence 6: Code Review of Caching Logic -- Source: src/services/user.ts:45-60 -- Finding: Cache miss triggers external API call -- Confidence: High (code inspection) - -### Evidence 7: Cache Hit Rate -- Source: Application metrics -- Finding: Cache hit rate: 5% (95% miss rate) -- Confidence: High (measured) - -## Hypotheses - -### Hypothesis A: Cache Not Working Properly -- Supporting: E3 (caching added), E7 (low hit rate) -- Contradicting: E4 (Redis is fast) -- Probability: 60% -- Details: Cache might not be storing data correctly - -### Hypothesis B: External API Became Slow -- Supporting: E5 (external API latency) -- Contradicting: E1 (timing matches deploy, not external change) -- Probability: 20% - -### Hypothesis C: Cache Key Mismatch -- Supporting: E3 (new code), E7 (low hit rate), E6 (cache logic) -- Contradicting: None -- Probability: 90% (after code review) -- Details: New code might generate different cache keys than lookup - -## Testing - -### Test 1: Verify Cache Storage -- Action: Log cache keys on write and read -- Expected: Keys should match -- Actual: Write key: `user:123`, Read key: `user:{"id":"123"}` -- Result: CONFIRMED - Key mismatch found - -### Test 2: Fix Cache Key Format -- Action: Standardize cache key format in both write and read -- Expected: Hit rate should increase dramatically -- Actual: Hit rate increased to 95%, response time back to 100ms -- Result: CONFIRMED - This was the root cause - -## Conclusion - -**Root Cause**: Cache key format mismatch between write and read operations - -**Confidence**: 10/10 (tested and verified) - -**Evidence Chain**: -1. Timing matches deployment (E1) -2. Caching logic was added (E3) -3. Cache hit rate extremely low (E7) -4. Cache keys don't match between read/write (Test 1) -5. Fixing keys resolves issue (Test 2) - -**Fix Applied**: Standardized cache key format in user.ts:45-60 - -**Recommended Follow-up**: -1. Add unit tests for cache key generation -2. Add monitoring for cache hit rate -3. Review other services for similar issues -``` - -## Integration with Other Skills - -### With Systematic Debugging - -Sequential Thinking provides the framework, [Systematic Debugging](/claudekit/skills/methodology/systematic-debugging) provides the debugging-specific workflow. - -### With TDD - -After identifying root cause: -1. Write test that reproduces issue (TDD red) -2. Fix based on conclusion (TDD green) -3. Verify test passes (TDD verify) - -### With Verification - -All conclusions must be verified with [evidence-based completion](/claudekit/skills/methodology/verification). - -## Best Practices - -### Number Your Evidence - -Makes it easy to reference: "E1 and E3 support Hypothesis A" - -### Update Probabilities - -As you gather evidence, adjust hypothesis probabilities - -### Document Contradictions - -Evidence against a hypothesis is as valuable as evidence for it - -### Test Highest Probability First - -Focus effort on most likely causes - -## Common Use Cases - -### Security Analysis - -```markdown -Question: Is this authentication bypass a real vulnerability? -Evidence: Code review, test results, security logs -Hypotheses: Multiple attack vectors -Testing: Actual exploit attempts -Conclusion: Confirmed vulnerability with 9/10 confidence -``` - -### Performance Investigation - -```markdown -Question: What's causing 95th percentile latency spike? -Evidence: Metrics, logs, profiling data -Hypotheses: Database, network, algorithm -Testing: Controlled experiments -Conclusion: Database connection pool exhaustion -``` - -### Architecture Decision - -```markdown -Question: Should we use microservices or monolith? -Evidence: Team size, requirements, constraints -Hypotheses: Different architectural patterns -Testing: Prototype both approaches -Conclusion: Monolith recommended with 8/10 confidence -``` - -## Next Steps - -After completing sequential analysis: - -1. **Implement fix** based on conclusion -2. **Add regression test** to prevent recurrence -3. **Document learning** for future reference -4. **Review similar code** for related issues - -## Related Skills - -- [Systematic Debugging](/claudekit/skills/methodology/systematic-debugging) - Debugging methodology -- [Verification](/claudekit/skills/methodology/verification) - Evidence-based completion -- [Root Cause Tracing](/claudekit/skills/methodology/root-cause-tracing) - Deep investigation diff --git a/website/src/content/docs/skills/methodology/systematic-debugging.md b/website/src/content/docs/skills/methodology/systematic-debugging.md deleted file mode 100644 index f5740d6..0000000 --- a/website/src/content/docs/skills/methodology/systematic-debugging.md +++ /dev/null @@ -1,336 +0,0 @@ ---- -title: Systematic Debugging -description: Four-phase debugging methodology for finding root causes ---- - -The Systematic Debugging skill uses a structured four-phase process centered on finding root causes before implementing fixes. - -**Foundational Principle**: NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST - -## Overview - -Systematic debugging prevents "whack-a-mole" bug fixing by requiring thorough investigation before any code changes. This approach saves time by fixing the actual problem, not symptoms. - -## When to Use - -- Bug reports with unclear cause -- Errors appearing in production -- Tests failing unexpectedly -- Intermittent/flaky issues -- Complex multi-component failures - -## The Four Phases - -### Phase 1: Root Cause Investigation - -**Goal**: Understand what's happening before attempting to fix. - -**Steps**: - -1. **Read error messages carefully** - - What is the exact error message? - - What is the stack trace? - - What line numbers are mentioned? - - What values are shown? - -2. **Reproduce consistently** - - Can you trigger the bug reliably? - - What exact steps reproduce it? - - What environment is required? - - Document the reproduction steps - -3. **Track recent changes** - - What changed recently? - - `git log --oneline -20` - - When did it last work? - - What was deployed? - -4. **Gather evidence** - - Collect logs - - Check monitoring/metrics - - Review related code - - Note any patterns - -5. **Add instrumentation** (for multi-component systems) - ```typescript - // Add diagnostic logging at each boundary - console.error('[DEBUG] Input received:', JSON.stringify(input)); - console.error('[DEBUG] After validation:', JSON.stringify(validated)); - console.error('[DEBUG] Before database call:', JSON.stringify(query)); - console.error('[DEBUG] Database result:', JSON.stringify(result)); - ``` - -### Phase 2: Pattern Analysis - -**Goal**: Find comparable working code to identify differences. - -**Steps**: - -1. **Find working code** - - Is there similar functionality that works? - - What did this code look like before? - - Are there reference implementations? - -2. **Study reference thoroughly** - - How does the working version handle this case? - - What dependencies does it use? - - What assumptions does it make? - -3. **Identify differences** - - What's different between working and broken? - - Configuration differences? - - Data differences? - - Environment differences? - -4. **Understand dependencies** - - What does this code depend on? - - What depends on this code? - - Are dependencies behaving correctly? - -### Phase 3: Hypothesis and Testing - -**Goal**: Form and test a specific theory about the cause. - -**Steps**: - -1. **Form specific hypothesis** - ```markdown - Write it down explicitly: - "The bug occurs because [X] causes [Y] when [Z]" - - Example: - "The bug occurs because the cache returns stale data - when the user's session expires during an active request" - ``` - -2. **Test with minimal changes** - - Change ONE variable at a time - - Don't combine multiple fixes - - Verify results after each change - -3. **Validate hypothesis** - - Does the fix address the hypothesis? - - Can you explain WHY it works? - - Does it make the bug impossible, not just unlikely? - -### Phase 4: Implementation - -**Goal**: Fix properly with verification. - -**Steps**: - -1. **Write failing test first** - ```typescript - it('should handle expired session during request', () => { - // Reproduce the bug scenario - const session = createExpiredSession(); - const result = processRequest(session); - - // This should fail before the fix - expect(result.error).toBe('SESSION_EXPIRED'); - }); - ``` - -2. **Implement single targeted fix** - ```typescript - // Fix addresses root cause, not symptom - function processRequest(session: Session) { - if (session.isExpired()) { - return { error: 'SESSION_EXPIRED' }; - } - // ... rest of logic - } - ``` - -3. **Verify fix works** - ```bash - npm test -- --grep "expired session" - # Should pass - ``` - -4. **Verify no regressions** - ```bash - npm test - # All tests should pass - ``` - -## The Three-Fix Rule - -**If three or more fixes fail consecutively, STOP.** - -This signals an architectural problem, not a simple bug: - -```markdown -Fix attempt 1: Failed -Fix attempt 2: Failed -Fix attempt 3: Failed - -STOP: This is not a bug - this is a design problem. - -Action: Discuss with user/team before proceeding -- Explain what's been tried -- Explain why it's not working -- Propose architectural changes -``` - -## Key Principles - -### Never Skip Error Details - -``` -❌ BAD: "There's an error somewhere" -✅ GOOD: "TypeError: Cannot read property 'id' of undefined - at UserService.getUser (user-service.ts:42)" -``` - -### Reproduce Before Investigating - -``` -❌ BAD: "I think I know what's wrong" (starts coding) -✅ GOOD: "Let me reproduce this first" (writes repro steps) -``` - -### Trace Backward to Origin - -``` -❌ BAD: Fix where error appears -✅ GOOD: Trace data backward to find where it became invalid -``` - -### One Change Per Test - -``` -❌ BAD: "I changed A, B, and C - now it works!" - (Which one fixed it? Are the others safe?) - -✅ GOOD: "I changed A - still broken. - I reverted A and changed B - now it works. - B was the fix." -``` - -## Debugging Checklist - -Before attempting any fix: - -- [ ] Error message fully read and understood -- [ ] Bug reproduced consistently -- [ ] Recent changes reviewed -- [ ] Evidence gathered (logs, traces) -- [ ] Hypothesis written down -- [ ] Similar working code identified -- [ ] Root cause identified (not just symptom) - -Before declaring fixed: - -- [ ] Failing test written -- [ ] Fix implemented -- [ ] Test passes -- [ ] No regressions (full test suite passes) -- [ ] Fix explained (can articulate why it works) - -## Activation - -```bash -/fix "timeout error in auth service" -/debug --systematic "flaky test" -/feature --debug-mode "fix login bug" -``` - -## Integration with Other Skills - -### With TDD - -1. Reproduce bug with failing test (TDD red) -2. Investigate root cause (Debugging) -3. Fix root cause (TDD green) -4. Verify test passes (TDD verify) - -### With Sequential Thinking - -For complex bugs, combine with [sequential thinking](/claudekit/skills/methodology/sequential-thinking): -- Document evidence systematically -- Form hypotheses with confidence scores -- Test hypotheses methodically - -### With Verification - -Always verify fix with [verification before completion](/claudekit/skills/methodology/verification): -- Run test before fix (must fail) -- Run test after fix (must pass) -- Run full suite (must pass) - -## Example Debugging Session - -```markdown -## Bug: Users logged out randomly - -### Phase 1: Investigation -- Error: "Session not found" in production logs -- Reproduces: Yes, after 30-45 minutes of inactivity -- Recent changes: Session timeout increased to 1 hour (commit abc123) -- Evidence: Session exists in Redis, but app can't find it - -### Phase 2: Pattern Analysis -- Working code: Login endpoint creates sessions correctly -- Difference: Session keys use different format after timeout change -- Key format before: `sess:user-id` -- Key format after: `session:user-id` - -### Phase 3: Hypothesis -"The timeout change introduced a key format mismatch. Old sessions use - 'sess:' prefix, new code looks for 'session:' prefix." - -Test: Check Redis for both key formats -Result: Confirmed - old keys exist with 'sess:' prefix - -### Phase 4: Implementation -1. Test: Verify session lookup handles both formats -2. Fix: Update lookup to check both prefixes -3. Verify: Test passes, no more random logouts -4. Full suite: All tests pass - -## Root Cause -Key prefix changed in commit abc123 without migration of existing sessions. - -## Fix -Check both 'sess:' and 'session:' prefixes during lookup until old sessions expire. -``` - -## Common Pitfalls - -### Fixing Symptoms - -``` -❌ "Error happens at line 42, I'll add a try-catch" -✅ "Why does line 42 error? What's the invalid data?" -``` - -### Shotgun Debugging - -``` -❌ "Let me try changing A, B, C, D and see what happens" -✅ "I hypothesize A is the cause. Let me test only A." -``` - -### Assuming vs. Verifying - -``` -❌ "The cache is probably stale" -✅ "Let me check the cache: console.log(cache.get(key))" -``` - -## Next Steps - -After successful debugging: - -1. **Add regression test**: Ensure bug can't return -2. **Document root cause**: Help future debugging -3. **Review related code**: Are there similar issues? -4. **Update monitoring**: Catch this class of bug earlier - -## Related Skills - -- [TDD](/claudekit/skills/methodology/tdd) - Write failing test first -- [Sequential Thinking](/claudekit/skills/methodology/sequential-thinking) - Evidence-based analysis -- [Verification](/claudekit/skills/methodology/verification) - Prove the fix works -- [Root Cause Tracing](/claudekit/skills/methodology/root-cause-tracing) - Deep investigation diff --git a/website/src/content/docs/skills/methodology/tdd.md b/website/src/content/docs/skills/methodology/tdd.md deleted file mode 100644 index 883fb71..0000000 --- a/website/src/content/docs/skills/methodology/tdd.md +++ /dev/null @@ -1,436 +0,0 @@ ---- -title: Test-Driven Development (TDD) -description: Strict test-first development methodology ---- - -The TDD skill enforces test-driven development with the fundamental rule: "If you didn't watch the test fail, you don't know if it tests the right thing." - -## Overview - -Test-Driven Development is a methodology where tests are written before production code. This ensures code is designed to be testable and that tests actually verify the intended behavior. - -**Non-Negotiable Rule**: NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST - -## When to Use - -- New feature development -- Bug fixes (write test that reproduces bug first) -- Refactoring (ensure tests exist before changing) -- Any behavior change - -## When NOT to Use - -Requires explicit approval: -- Throwaway prototypes -- Generated/scaffolded code -- Pure configuration changes - -## The Red-Green-Refactor Cycle - -### 1. RED: Write Failing Test - -Write a minimal test demonstrating the desired behavior: - -```typescript -describe('calculateTotal', () => { - it('should sum item prices', () => { - const items = [{ price: 10 }, { price: 20 }]; - expect(calculateTotal(items)).toBe(30); - }); -}); -``` - -### 2. VERIFY RED: Confirm Test Fails - -Run the test and confirm it fails **for the right reason**: - -```bash -npm test -- --grep "sum item prices" -# Expected: FAIL -# Reason: calculateTotal is not defined -``` - -**Critical**: The failure should be because the feature doesn't exist, not because of typos or syntax errors. - -### 3. GREEN: Write Minimal Code - -Write the simplest code that makes the test pass: - -```typescript -function calculateTotal(items: Item[]): number { - return items.reduce((sum, item) => sum + item.price, 0); -} -``` - -**Don't over-engineer**. If the test passes with simple code, stop. - -### 4. VERIFY GREEN: Confirm Test Passes - -```bash -npm test -- --grep "sum item prices" -# Expected: PASS -``` - -### 5. REFACTOR: Clean Up - -With green tests, refactor safely: -- Extract functions -- Rename variables -- Remove duplication -- Run tests after each change - -## The Rule - -**NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST** - -This is not a guideline. It's a rule. - -### What If I Already Wrote Code? - -Delete it. Completely. - -``` -❌ WRONG: "I'll keep this code as reference while writing tests" -✅ RIGHT: Delete the code, write test, rewrite implementation -``` - -### Why So Strict? - -- Code written before tests wasn't driven by tests -- Keeping it as reference leads to rationalization -- Tests written after code often just verify what was written -- True TDD produces different (usually better) designs - -## Test Quality Standards - -### One Behavior Per Test - -```typescript -// ❌ BAD: Multiple behaviors -it('should validate and save user', () => { - expect(validateUser(user)).toBe(true); - expect(saveUser(user)).toBe(1); -}); - -// ✅ GOOD: Single behavior -it('should validate user email format', () => { - expect(validateUser({ email: 'test@example.com' })).toBe(true); -}); - -it('should save valid user', () => { - const user = createValidUser(); - expect(saveUser(user)).toBe(1); -}); -``` - -### Clear Naming - -Test names should describe the behavior: - -```typescript -// ❌ BAD -it('test1', () => {}); -it('calculateTotal', () => {}); - -// ✅ GOOD -it('should return 0 for empty cart', () => {}); -it('should apply discount when coupon is valid', () => {}); -``` - -### Real Code Over Mocks - -Use real implementations when possible: - -```typescript -// ✅ PREFER: Real database (test container) -const db = await startTestDatabase(); -const result = await userRepo.save(user); - -// ⚠️ AVOID: Excessive mocking -const mockDb = { save: jest.fn().mockResolvedValue(1) }; -``` - -### Test Observable Behavior - -Test what the code does, not how it does it: - -```typescript -// ❌ BAD: Testing implementation -it('should call helper function', () => { - calculateTotal(items); - expect(helperFn).toHaveBeenCalled(); -}); - -// ✅ GOOD: Testing behavior -it('should return correct total', () => { - expect(calculateTotal(items)).toBe(30); -}); -``` - -## Edge Cases to Test - -Always include tests for: - -- Empty inputs -- Null/undefined values -- Boundary conditions -- Error scenarios -- Large inputs -- Invalid inputs - -```typescript -describe('calculateTotal', () => { - it('should return 0 for empty array', () => { - expect(calculateTotal([])).toBe(0); - }); - - it('should handle null items array', () => { - expect(() => calculateTotal(null)).toThrow(); - }); - - it('should handle negative prices', () => { - const items = [{ price: -10 }, { price: 20 }]; - expect(calculateTotal(items)).toBe(10); - }); -}); -``` - -## Common Rationalizations - -### "I'll write tests after" - -**Rejected**. Tests written after code verify what was written, not what should happen. - -### "Manual testing is enough" - -**Rejected**. Ad-hoc testing is not systematic, misses edge cases, and doesn't prevent regressions. - -### "This code is too simple to test" - -**Rejected**. Simple code breaks too. A test takes seconds and provides permanent verification. - -### "I don't have time" - -**Rejected**. TDD is faster in the medium term. Debugging time saved far exceeds test-writing time. - -### "I already wrote it, might as well keep it" - -**Rejected**. Sunk cost fallacy. Delete and rewrite properly. - -## TDD Workflow Example - -### Bug Fix with TDD - -```typescript -// 1. RED: Write test that reproduces bug -it('should handle expired session gracefully', () => { - const session = createExpiredSession(); - const result = processRequest(session); - expect(result.error).toBe('SESSION_EXPIRED'); -}); - -// 2. VERIFY RED: Confirm test fails -// npm test → FAIL (current code crashes or returns wrong error) - -// 3. GREEN: Fix the bug -function processRequest(session: Session) { - if (session.isExpired()) { - return { error: 'SESSION_EXPIRED' }; - } - // ... rest of logic -} - -// 4. VERIFY GREEN: Confirm test passes -// npm test → PASS - -// 5. Commit with test -// git commit -m "fix: handle expired session gracefully" -``` - -### New Feature with TDD - -```typescript -// 1. RED: Write test for feature -it('should calculate discount for premium users', () => { - const user = { type: 'premium' }; - const price = 100; - expect(calculatePrice(user, price)).toBe(90); // 10% off -}); - -// 2. VERIFY RED -// npm test → FAIL (calculatePrice doesn't consider user type) - -// 3. GREEN: Implement feature -function calculatePrice(user: User, price: number): number { - if (user.type === 'premium') { - return price * 0.9; - } - return price; -} - -// 4. VERIFY GREEN -// npm test → PASS - -// 5. REFACTOR: Extract discount logic -function getDiscount(user: User): number { - return user.type === 'premium' ? 0.1 : 0; -} - -function calculatePrice(user: User, price: number): number { - const discount = getDiscount(user); - return price * (1 - discount); -} - -// 6. VERIFY still GREEN -// npm test → PASS -``` - -## Activation - -### Via Command - -```bash -/tdd "add user authentication" -/feature --methodology=tdd "payment processing" -``` - -### Automatic in Plans - -When using [Writing Plans](/claudekit/skills/methodology/writing-plans), every task follows TDD automatically. - -### During Execution - -[Executing Plans](/claudekit/skills/methodology/executing-plans) enforces TDD for each task. - -## Integration with Other Skills - -### With Writing Plans - -Plans include TDD steps for every task: - -```markdown -1. Write failing test -2. Verify test fails -3. Implement minimally -4. Verify test passes -5. Commit -``` - -### With Verification - -[Verification](/claudekit/skills/methodology/verification) ensures: -- Tests actually fail before implementation -- Tests pass after implementation -- Full suite remains green - -### With Testing Anti-Patterns - -[Testing Anti-Patterns](/claudekit/skills/methodology/testing-anti-patterns) prevents: -- Testing mocks instead of real code -- Incomplete mocks -- Over-mocking -- Afterthought tests - -## Benefits - -### TDD Catches Bugs Early - -- Writing test first forces you to think about edge cases -- Seeing test fail proves it can catch failures -- Green bar confirms the fix works -- Test prevents regression forever - -### TDD Improves Design - -- Forces consideration of interfaces before implementation -- Encourages small, focused functions -- Makes dependencies explicit -- Results in more testable code - -### TDD Saves Time - -Prevents this cycle: -1. Write code -2. Manual test (miss edge case) -3. Ship -4. Bug reported -5. Debug -6. Fix -7. Ship again - -With TDD: -1. Write test -2. See it fail -3. Implement -4. See it pass -5. Ship confidently - -## Best Practices - -### Keep Tests Fast - -```typescript -// ✅ Fast tests -it('should validate email format', () => { - expect(validateEmail('test@example.com')).toBe(true); -}); - -// ⚠️ Slow tests (when avoidable) -it('should validate email', async () => { - await db.connect(); - await db.query('SELECT ...'); - // Use test doubles for unit tests -}); -``` - -### Test Behavior, Not Implementation - -```typescript -// ❌ BAD: Brittle implementation test -it('should call emailService.send', () => { - registerUser(data); - expect(emailService.send).toHaveBeenCalled(); -}); - -// ✅ GOOD: Behavior test -it('should send welcome email to new user', async () => { - await registerUser({ email: 'test@example.com' }); - const emails = await getTestEmails(); - expect(emails).toContainEqual( - expect.objectContaining({ - to: 'test@example.com', - subject: 'Welcome' - }) - ); -}); -``` - -### Arrange-Act-Assert Pattern - -```typescript -it('should calculate total with tax', () => { - // Arrange - const items = [{ price: 100 }]; - const taxRate = 0.1; - - // Act - const total = calculateTotalWithTax(items, taxRate); - - // Assert - expect(total).toBe(110); -}); -``` - -## Next Steps - -- Use with [Writing Plans](/claudekit/skills/methodology/writing-plans) for structured TDD -- Combine with [Code Review](/claudekit/skills/methodology/code-review) for quality -- Avoid [Testing Anti-Patterns](/claudekit/skills/methodology/testing-anti-patterns) -- Enforce with [Verification](/claudekit/skills/methodology/verification) - -## Related Skills - -- [Writing Plans](/claudekit/skills/methodology/writing-plans) - Plans include TDD steps -- [Executing Plans](/claudekit/skills/methodology/executing-plans) - Enforces TDD per task -- [Testing Anti-Patterns](/claudekit/skills/methodology/testing-anti-patterns) - Avoid mistakes -- [Verification](/claudekit/skills/methodology/verification) - Prove tests work diff --git a/website/src/content/docs/skills/methodology/testing-anti-patterns.md b/website/src/content/docs/skills/methodology/testing-anti-patterns.md deleted file mode 100644 index 5b4d169..0000000 --- a/website/src/content/docs/skills/methodology/testing-anti-patterns.md +++ /dev/null @@ -1,376 +0,0 @@ ---- -title: Testing Anti-Patterns -description: Common testing mistakes that create false confidence ---- - -The Testing Anti-Patterns skill helps recognize and avoid common testing mistakes that make tests pass while failing to verify actual behavior. - -## Overview - -Tests can provide false confidence when they verify mocks instead of real behavior, pollute production code, or are written as afterthoughts. This skill identifies these patterns and provides solutions. - -## When to Use - -- Writing new tests -- Reviewing test code -- Debugging flaky or unreliable tests -- When tests pass but bugs still ship - -## The Five Anti-Patterns - -### 1. Testing Mock Behavior Instead of Real Code - -**The Problem**: Tests verify mocks work, not that actual code works. - -```typescript -// ❌ BAD: Testing the mock -it('should call the database', () => { - const mockDb = { save: jest.fn().mockResolvedValue({ id: 1 }) }; - const service = new UserService(mockDb); - - await service.createUser({ name: 'Test' }); - - expect(mockDb.save).toHaveBeenCalled(); // Only proves mock was called -}); -``` - -**The Solution**: Test actual behavior with real (or realistic) dependencies. - -```typescript -// ✅ GOOD: Testing real behavior -it('should persist user to database', async () => { - const db = await createTestDatabase(); - const service = new UserService(db); - - const result = await service.createUser({ name: 'Test' }); - - const saved = await db.findById(result.id); - expect(saved.name).toBe('Test'); // Proves data was actually saved -}); -``` - -**Key Principle**: Test what the code does, not what the mocks do. - -### 2. Polluting Production with Test-Only Methods - -**The Problem**: Adding methods to production code solely for test cleanup or access. - -```typescript -// ❌ BAD: Production class with test-only method -class ConnectionPool { - private connections: Connection[] = []; - - // This method exists only for tests - destroy(): void { // DON'T DO THIS - this.connections.forEach(c => c.close()); - this.connections = []; - } -} -``` - -**The Solution**: Handle cleanup in test utilities, not production code. - -```typescript -// ✅ GOOD: Test utility handles cleanup -// test-utils/connection-pool.ts -export async function withTestPool(fn: (pool: ConnectionPool) => Promise) { - const pool = new ConnectionPool(); - try { - await fn(pool); - } finally { - // Cleanup handled by test infrastructure - await closeAllConnections(pool); - } -} -``` - -**Key Principle**: Production code should never know it's being tested. - -### 3. Mocking Without Understanding Dependencies - -**The Problem**: Over-mocking to "be safe" removes behavior the test actually depends on. - -```typescript -// ❌ BAD: Mocking everything blindly -it('should process order', () => { - jest.mock('./inventory'); // What does this mock? - jest.mock('./payment'); // Did we need to mock this? - jest.mock('./shipping'); // This might break the test logic - - const result = processOrder(order); - expect(result.status).toBe('complete'); -}); -``` - -**The Solution**: Understand what each dependency does before mocking it. - -```typescript -// ✅ GOOD: Selective, understood mocking -it('should process order when payment succeeds', () => { - // Only mock external service (payment gateway) - // Keep inventory and shipping real for integration test - const paymentGateway = createMockPaymentGateway({ - chargeResult: { success: true, transactionId: 'txn-123' } - }); - - const result = processOrder(order, { paymentGateway }); - - expect(result.status).toBe('complete'); - expect(result.transactionId).toBe('txn-123'); -}); -``` - -**Key Principle**: Mock at boundaries, not internally. - -### 4. Creating Incomplete Mocks - -**The Problem**: Partial mocks that only include known fields, hiding structural assumptions. - -```typescript -// ❌ BAD: Incomplete mock -const mockApiResponse = { - data: { users: [] } - // Missing: status, headers, pagination, errors -}; - -it('should handle API response', () => { - fetchMock.mockResolvedValue(mockApiResponse); - const result = await getUsers(); - expect(result).toEqual([]); -}); -// Test passes, but production fails when accessing response.pagination -``` - -**The Solution**: Create complete mocks that match real API responses. - -```typescript -// ✅ GOOD: Complete mock matching real response structure -const mockApiResponse = { - status: 200, - headers: { 'content-type': 'application/json' }, - data: { - users: [], - pagination: { page: 1, total: 0, hasMore: false }, - errors: null - } -}; - -it('should handle empty API response', () => { - fetchMock.mockResolvedValue(mockApiResponse); - const result = await getUsers(); - expect(result.users).toEqual([]); - expect(result.hasMore).toBe(false); -}); -``` - -**Key Principle**: Mocks should be indistinguishable from real responses. - -### 5. Writing Tests as Afterthoughts - -**The Problem**: Treating testing as optional follow-up work rather than integral to development. - -```typescript -// ❌ BAD: Tests written after code, just verifying what exists -it('should do what the function does', () => { - // This test was written by looking at the implementation - // It tests the current behavior, not the intended behavior - const result = processData(input); - expect(result).toMatchSnapshot(); // "Whatever it does is correct" -}); -``` - -**The Solution**: Use TDD - tests define requirements before implementation. - -```typescript -// ✅ GOOD: Test written first, defines requirement -it('should filter inactive users from report', () => { - const users = [ - { id: 1, name: 'Alice', active: true }, - { id: 2, name: 'Bob', active: false } - ]; - - const report = generateReport(users); - - expect(report.users).toHaveLength(1); - expect(report.users[0].name).toBe('Alice'); -}); -// Now implement generateReport to make this pass -``` - -**Key Principle**: TDD prevents all these anti-patterns naturally. - -## Recognition Guide - -| Symptom | Likely Anti-Pattern | -|---------|---------------------| -| Tests pass but bugs ship | #1 Testing mocks | -| `destroy()` or `reset()` in production | #2 Test pollution | -| "I mocked that to be safe" | #3 Blind mocking | -| TypeError in production, not tests | #4 Incomplete mocks | -| Tests feel like documentation | #5 Afterthought tests | - -## Prevention Checklist - -Before committing tests, verify: - -- [ ] Tests use real dependencies where possible -- [ ] Mocks are for external boundaries only -- [ ] No production code exists solely for tests -- [ ] Mock structures match real API responses -- [ ] Tests were written before implementation (TDD) -- [ ] Tests verify behavior, not implementation details - -## Core Principle - -**"Mocks are tools to isolate, not things to test."** - -Mocks help you: -- Isolate unit under test -- Control external dependencies -- Speed up slow operations (network, disk) - -Mocks should never: -- Be the thing you're verifying -- Hide bugs in dependencies -- Create false confidence - -## Good Mocking Practices - -### Mock External Services Only - -```typescript -// ✅ GOOD: Mock external API -const mockStripeApi = { - charges: { - create: jest.fn().mockResolvedValue({ id: 'ch_123' }) - } -}; - -// ✅ GOOD: Keep business logic real -const paymentService = new PaymentService(mockStripeApi); -const result = await paymentService.processPayment(order); -``` - -### Use Test Containers for Databases - -```typescript -// ✅ BETTER: Use real database (in Docker) -import { PostgreSqlContainer } from 'testcontainers'; - -let container: PostgreSqlContainer; -let db: Database; - -beforeAll(async () => { - container = await new PostgreSqlContainer().start(); - db = await createDatabase(container.getConnectionString()); -}); - -it('should save user', async () => { - const user = await db.users.create({ name: 'Test' }); - expect(user.id).toBeDefined(); -}); -``` - -### Create Mock Factories - -```typescript -// ✅ GOOD: Centralized, complete mocks -function createMockUser(overrides: Partial = {}): User { - return { - id: '123', - email: 'test@example.com', - name: 'Test User', - role: 'user', - active: true, - createdAt: new Date(), - ...overrides - }; -} - -// Tests use complete, consistent mocks -it('should greet admin', () => { - const admin = createMockUser({ role: 'admin' }); - expect(greet(admin)).toBe('Hello Admin!'); -}); -``` - -## Integration with Other Skills - -### With TDD - -[TDD](/claudekit/skills/methodology/tdd) naturally prevents anti-patterns: -- Tests written first define real requirements -- Can't test mocks when no mocks exist yet -- Forces thinking about actual behavior - -### With Verification - -[Verification](/claudekit/skills/methodology/verification) ensures: -- Tests actually run (not just mocked) -- Tests verify real behavior -- Evidence of actual execution - -### With Code Review - -[Code Review](/claudekit/skills/methodology/code-review) should catch: -- Over-mocking in tests -- Test pollution in production -- Incomplete mock structures - -## Examples of Good Tests - -### Integration Test (Preferred) - -```typescript -it('should create user and send welcome email', async () => { - const db = await createTestDatabase(); - const emailService = new TestEmailService(); - const userService = new UserService(db, emailService); - - const user = await userService.create({ - email: 'new@example.com', - name: 'New User' - }); - - // Verify database persistence - const saved = await db.users.findById(user.id); - expect(saved.email).toBe('new@example.com'); - - // Verify email sent - const emails = emailService.getSentEmails(); - expect(emails).toHaveLength(1); - expect(emails[0].to).toBe('new@example.com'); -}); -``` - -### Unit Test with Minimal Mocking - -```typescript -it('should calculate total with tax', () => { - const items = [ - { price: 100, taxable: true }, - { price: 50, taxable: false } - ]; - - const total = calculateTotal(items, 0.1); // 10% tax - - expect(total).toBe(160); // 100 + 10 (tax) + 50 -}); -``` - -## Next Steps - -To improve test quality: - -1. **Review existing tests** for these anti-patterns -2. **Use TDD** for new features -3. **Prefer integration tests** over heavily mocked unit tests -4. **Mock only at boundaries** (external APIs, file system) -5. **Create complete mocks** matching real structures - -## Related Skills - -- [TDD](/claudekit/skills/methodology/tdd) - Prevents afterthought tests -- [Verification](/claudekit/skills/methodology/verification) - Ensures tests run -- [Code Review](/claudekit/skills/methodology/code-review) - Catches anti-patterns -- [Systematic Debugging](/claudekit/skills/methodology/systematic-debugging) - Investigates test failures diff --git a/website/src/content/docs/skills/methodology/verification.md b/website/src/content/docs/skills/methodology/verification.md deleted file mode 100644 index 8cb2ec2..0000000 --- a/website/src/content/docs/skills/methodology/verification.md +++ /dev/null @@ -1,394 +0,0 @@ ---- -title: Verification Before Completion -description: Mandatory verification before claiming task completion ---- - -The Verification Before Completion skill enforces evidence-based completion rather than assumption-based claims. - -**Core Rule**: Never claim completion without proof - -## Overview - -This skill prevents premature completion claims by requiring actual verification for every assertion. Tests must run, builds must complete, and evidence must exist before declaring success. - -## When to Use - -- Before claiming tests pass -- Before claiming build succeeds -- Before claiming bug is fixed -- Before marking any task complete -- Before declaring success to user - -## The 5-Step Verification Process - -### Step 1: IDENTIFY - -Determine the command that proves your assertion: - -```markdown -Claim: "Tests pass" -Verification command: npm test - -Claim: "Build succeeds" -Verification command: npm run build - -Claim: "Linting passes" -Verification command: npm run lint -``` - -### Step 2: EXECUTE - -Run the command fully and freshly: - -```bash -# Don't rely on cached results -# Don't assume previous run is still valid -npm test -``` - -### Step 3: READ - -Read the complete output and exit codes: - -```bash -# Check output carefully -# Don't skim - read every line -# Note exit code (0 = success) -``` - -### Step 4: VERIFY - -Confirm the output matches your claim: - -```markdown -Claim: "All tests pass" -Output shows: "42 passing, 0 failing" -Verification: ✓ Claim is accurate -``` - -### Step 5: CLAIM - -Only now make the claim, with evidence: - -```markdown -✓ All tests pass (42 passing, verified at 2025-01-29 14:30) -``` - -## Required Validations by Category - -### Testing - -```bash -# Run test command -npm test - -# Verify in output: -# - Zero failures -# - Expected test count -# - No skipped tests (unless intentional) -``` - -**Not valid**: "Tests should pass" without running them - -### Linting - -```bash -# Run linter completely -npm run lint - -# Verify in output: -# - Zero errors -# - Zero warnings (or acceptable known warnings) -``` - -**Not valid**: Using lint as proxy for build success - -### Building - -```bash -# Run build command -npm run build - -# Verify: -# - Exit code 0 -# - Build artifacts created -# - No errors in output -``` - -**Not valid**: Assuming lint passing means build passes - -### Bug Fixes - -```bash -# Step 1: Reproduce original bug -npm test -- --grep "failing test" -# Should fail - -# Step 2: Apply fix - -# Step 3: Verify fix works -npm test -- --grep "failing test" -# Should pass -``` - -**Not valid**: Claiming fix works without reproducing original failure - -### Regression Tests - -Complete red-green cycle required: - -```bash -# 1. Write test, run it -npm test # Should PASS with new test - -# 2. Revert the fix -git stash - -# 3. Run test again -npm test # Should FAIL (proves test catches the bug) - -# 4. Restore fix -git stash pop - -# 5. Run test again -npm test # Should PASS -``` - -## Forbidden Language - -Never use these phrases without verification: - -| Forbidden | Why | -|-----------|-----| -| "should work" | Implies uncertainty | -| "probably fixed" | Not verified | -| "seems to pass" | Didn't read output | -| "I think it's done" | Guessing | -| "Great!" (before checking) | Premature celebration | -| "Done!" (before verification) | Unverified claim | - -### Replace With - -| Instead Say | After | -|-------------|-------| -| "Tests pass" | Running tests, seeing 0 failures | -| "Build succeeds" | Running build, exit code 0 | -| "Bug is fixed" | Reproducing bug, verifying fix | - -## Anti-Patterns - -### Partial Verification - -``` -❌ BAD: "I ran one test and it passed" -✅ GOOD: "Full test suite passes (42/42)" -``` - -### Relying on Prior Runs - -``` -❌ BAD: "Tests passed earlier" -✅ GOOD: "Tests pass now (just ran)" -``` - -### Skipping Verification - -``` -❌ BAD: "This is a small change, no need to verify" -✅ GOOD: "Small change, but verified: tests pass, lint clean" -``` - -### Trusting Without Checking - -``` -❌ BAD: "Agent said it's fixed, so it's fixed" -✅ GOOD: "Agent said it's fixed, I verified by running tests" -``` - -## Verification Checklist Template - -Use before claiming completion: - -```markdown -## Task: Add Email Verification - -### Verification Steps -- [ ] Tests run: `npm test` - - Result: 45 passing, 0 failing -- [ ] Lint passes: `npm run lint` - - Result: No errors, no warnings -- [ ] Build succeeds: `npm run build` - - Result: Exit code 0, dist/ created -- [ ] Requirements met: - - [ ] Users receive verification email (tested manually) - - [ ] Token expires after 24 hours (unit test added) - - [ ] Invalid tokens rejected (unit test added) - -### Evidence -``` -Test output: -PASS src/services/email.test.ts -PASS src/services/user.test.ts -Test Suites: 2 passed, 2 total -Tests: 45 passed, 45 total -``` - -### Conclusion -✓ Task complete, all verifications passed -``` - -## Integration with Other Skills - -### With TDD - -[TDD](/claudekit/skills/methodology/tdd) naturally includes verification: -1. Write test - verify it fails (red) -2. Implement - verify it passes (green) -3. Refactor - verify it still passes - -### With Systematic Debugging - -[Debugging](/claudekit/skills/methodology/systematic-debugging) requires verification: -1. Reproduce bug - verify it fails -2. Fix bug - verify it passes -3. Check regressions - verify full suite passes - -### With Executing Plans - -[Plan execution](/claudekit/skills/methodology/executing-plans) includes verification gates: -- After each task - verify tests pass -- After code review - verify issues fixed -- Before completion - verify all requirements met - -## Example Verification - -### Before Claiming "Tests Pass" - -```bash -$ npm test - -> project@1.0.0 test -> vitest run - - ✓ src/models/user.test.ts (12 tests) - ✓ src/services/auth.test.ts (18 tests) - ✓ src/api/users.test.ts (15 tests) - -Test Files 3 passed (3) - Tests 45 passed (45) - Start at 14:23:10 - Duration 2.34s -``` - -**Now you can claim**: "All tests pass (45/45, verified at 14:23)" - -### Before Claiming "Build Succeeds" - -```bash -$ npm run build - -> project@1.0.0 build -> tsc && vite build - -vite v4.3.9 building for production... -✓ 145 modules transformed. -dist/index.html 0.42 kB -dist/assets/index-a1b2c3d4.js 87.23 kB │ gzip: 28.42 kB - -✓ built in 3.45s - -$ echo $? -0 -``` - -**Now you can claim**: "Build succeeds (exit code 0, dist/ created)" - -### Before Claiming "Bug Fixed" - -```bash -# 1. Verify bug exists -$ npm test -- --grep "login with expired session" -FAIL src/auth.test.ts - ✕ login with expired session (45ms) - Expected error, got success - -# 2. Apply fix - -# 3. Verify fix works -$ npm test -- --grep "login with expired session" -PASS src/auth.test.ts - ✓ login with expired session (12ms) - -# 4. Verify no regressions -$ npm test -Test Files 3 passed (3) - Tests 45 passed (45) -``` - -**Now you can claim**: "Bug fixed, all tests pass including regression test" - -## Activation - -This skill is always active, but particularly enforced: - -- During [Executing Plans](/claudekit/skills/methodology/executing-plans) -- After [TDD](/claudekit/skills/methodology/tdd) implementation -- Before [Code Review](/claudekit/skills/methodology/code-review) -- In quality-critical contexts - -## Best Practices - -### Verify Immediately - -Don't wait to verify - do it right after implementation: - -``` -Implement → Verify → Claim -NOT: Implement → Claim → Verify later -``` - -### Include Output in Claims - -``` -✅ "Tests pass (45/45)" -✅ "Build succeeds (exit 0, 87KB bundle)" -✅ "Lint clean (0 errors, 0 warnings)" -``` - -### Re-verify After Changes - -``` -After changing code: -1. Re-run tests (don't trust old results) -2. Verify they still pass -3. Update verification timestamp -``` - -### Document Failed Attempts - -```markdown -## Verification Attempts - -Attempt 1: FAILED (test 12 failing) -- Fixed null check in user.ts:45 -- Re-verified - -Attempt 2: PASSED (45/45 tests) -- Verification complete -``` - -## Next Steps - -After successful verification: - -1. **Document the evidence**: Keep verification output -2. **Commit with confidence**: You know it works -3. **Report completion**: With evidence attached -4. **Move to next task**: Previous task is proven complete - -## Related Skills - -- [TDD](/claudekit/skills/methodology/tdd) - Includes verification in cycle -- [Systematic Debugging](/claudekit/skills/methodology/systematic-debugging) - Verify fixes work -- [Executing Plans](/claudekit/skills/methodology/executing-plans) - Verification gates -- [Code Review](/claudekit/skills/methodology/code-review) - Verify review feedback addressed diff --git a/website/src/content/docs/skills/methodology/writing-plans.md b/website/src/content/docs/skills/methodology/writing-plans.md deleted file mode 100644 index 6a2ce0e..0000000 --- a/website/src/content/docs/skills/methodology/writing-plans.md +++ /dev/null @@ -1,478 +0,0 @@ ---- -title: Writing Plans -description: Generate detailed implementation plans with bite-sized tasks ---- - -The Writing Plans skill creates comprehensive, step-by-step implementation plans that bridge design and execution with 2-5 minute tasks. - -## Overview - -Writing Plans transforms completed designs into executable roadmaps. Each task includes exact file paths, complete code samples, and expected outcomes - enabling anyone to implement the plan successfully. - -**Core Principle**: Tasks so small and clear that implementation becomes mechanical. - -## When to Use - -- After brainstorming/design is complete -- Before starting implementation -- When handing off work to another developer -- For complex features requiring structured approach - -## Plan Structure - -### Header Section - -```markdown -# Plan: Add Email Verification - -**Required Skill**: executing-plans - -## Goal -Add email verification to user registration flow. - -## Architecture Overview -Send verification email on registration, validate token on click, -mark user as verified in database. - -## Tech Stack -- Node.js, TypeScript -- PostgreSQL -- SendGrid for email -``` - -### Task Format - -Each task follows this structure: - -```markdown -## Task 1: Add verified flag to User model - -**Files**: -- Modify: `src/models/user.ts` -- Create: `src/migrations/add-verified-flag.ts` -- Test: `src/models/user.test.ts` - -**Steps**: - -1. Write failing test - ```typescript - describe('User model', () => { - it('should have verified flag defaulting to false', () => { - const user = new User({ email: 'test@example.com' }); - expect(user.verified).toBe(false); - }); - }); - ``` - -2. Verify test fails - ```bash - npm test -- --grep "verified flag" - # Expected: 1 failing (verified is undefined) - ``` - -3. Add verified field to User model - ```typescript - // src/models/user.ts - export class User { - email: string; - verified: boolean = false; // Add this line - // ... - } - ``` - -4. Verify test passes - ```bash - npm test -- --grep "verified flag" - # Expected: 1 passing - ``` - -5. Commit - ```bash - git add src/models/user.ts src/models/user.test.ts - git commit -m "feat(user): add verified flag with false default" - ``` -``` - -## Task Granularity - -### The 2-5 Minute Rule - -Each task should take 2-5 minutes of focused work: - -- Write one test -- Implement one function -- Add one validation -- Create one component - -### Why So Small? - -- Easier to verify correctness -- Natural commit points -- Reduces context switching -- Enables parallel work -- Clearer progress tracking - -### Bad vs Good Breakdown - -``` -❌ BAD: "Implement user authentication" - (Too large - could take hours) - -✅ GOOD: - - Task 1: Create User model with email field (3 min) - - Task 2: Add password hashing to User model (4 min) - - Task 3: Create login endpoint (5 min) - - Task 4: Add JWT token generation (4 min) - - Task 5: Create auth middleware (5 min) - - Task 6: Add token refresh endpoint (4 min) -``` - -## Core Requirements - -### Exact File Paths Always - -Never use vague references: - -``` -❌ BAD: "Update the user service" -✅ GOOD: "Modify `src/services/user-service.ts`" -``` - -### Complete Code Samples - -Include exact code, not descriptions: - -``` -❌ BAD: "Add a function that validates email" - -✅ GOOD: -```typescript -export function validateEmail(email: string): boolean { - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - return emailRegex.test(email); -} -``` -``` - -### Expected Output Specifications - -Always specify expected command results: - -```bash -npm test -# Expected output: -# PASS src/services/user.test.ts -# User validation -# ✓ validates correct email format (3ms) -# ✓ rejects invalid email format (1ms) -# 2 passing -``` - -## Guiding Principles - -### DRY (Don't Repeat Yourself) - -- Identify patterns before implementation -- Plan for reusable components -- Note shared utilities needed - -### YAGNI (You Aren't Gonna Need It) - -- Only plan what's required now -- Remove speculative features -- Add complexity when justified - -### TDD (Test-Driven Development) - -Every task follows the cycle: -1. Write failing test -2. Verify it fails -3. Implement minimally -4. Verify it passes -5. Refactor if needed -6. Commit - -### Frequent Commits - -- Commit after each task -- Clear, descriptive messages -- Atomic changes only - -## Activation - -### Via Command - -```bash -/plan "add email verification" -/plan --detailed "user authentication" # Extra detailed (30+ tasks) -/plan designs/feature-x.md # Plan from design doc -``` - -### Automatic from Brainstorming - -```bash -/brainstorm "payment processing" -# After design completes... -"Would you like me to create an implementation plan?" -``` - -## Example Plan - -```markdown -# Plan: Add Password Reset - -**Required Skill**: executing-plans - -## Goal -Allow users to reset forgotten passwords via email link. - -## Architecture Overview -User requests reset, receives email with token link, submits new password, -password updated if token valid. - -## Tech Stack -- TypeScript, Express -- PostgreSQL -- SendGrid - ---- - -## Task 1: Add resetToken field to User model - -**Files**: -- Modify: `src/models/user.ts` -- Test: `src/models/user.test.ts` - -**Steps**: - -1. Write test for reset token - ```typescript - it('should store password reset token', () => { - const user = new User({ email: 'test@example.com' }); - user.resetToken = 'abc123'; - user.resetTokenExpiry = new Date(Date.now() + 3600000); - expect(user.resetToken).toBe('abc123'); - }); - ``` - -2. Verify test fails - ```bash - npm test -- --grep "reset token" - # Expected: 1 failing - ``` - -3. Add fields to User model - ```typescript - export class User { - email: string; - passwordHash: string; - resetToken?: string; - resetTokenExpiry?: Date; - } - ``` - -4. Verify test passes - ```bash - npm test - # Expected: All passing - ``` - -5. Commit - ```bash - git add . - git commit -m "feat(user): add reset token fields" - ``` - -## Task 2: Create password reset request endpoint - -**Files**: -- Create: `src/routes/auth.ts` (if not exists) -- Modify: `src/routes/auth.ts` -- Test: `src/routes/auth.test.ts` - -**Steps**: - -1. Write test for POST /auth/reset-request - ```typescript - it('should generate reset token for valid email', async () => { - await createUser({ email: 'test@example.com' }); - - const res = await request(app) - .post('/auth/reset-request') - .send({ email: 'test@example.com' }); - - expect(res.status).toBe(200); - expect(res.body.message).toContain('sent'); - }); - ``` - -2. Verify test fails - ```bash - npm test -- --grep "reset-request" - # Expected: 404 (route doesn't exist) - ``` - -3. Implement endpoint - ```typescript - router.post('/reset-request', async (req, res) => { - const { email } = req.body; - const user = await User.findByEmail(email); - - if (!user) { - return res.status(200).json({ message: 'Reset email sent' }); - } - - user.resetToken = crypto.randomBytes(32).toString('hex'); - user.resetTokenExpiry = new Date(Date.now() + 3600000); - await user.save(); - - await sendResetEmail(user.email, user.resetToken); - - res.json({ message: 'Reset email sent' }); - }); - ``` - -4. Verify test passes - ```bash - npm test -- --grep "reset-request" - # Expected: 1 passing - ``` - -5. Commit - ```bash - git add . - git commit -m "feat(auth): add password reset request endpoint" - ``` - -## Task 3: ... (continue for remaining tasks) -``` - -## Execution Handoff - -After plan is complete, offer implementation pathways: - -### Option 1: Subagent-Driven (Current Session) - -``` -Use the executing-plans skill for automated execution with: -- Fresh agent per task -- Code review between tasks -- Quality gates -``` - -### Option 2: Manual Execution - -``` -Developer executes in current or separate session: -- Read plan file -- Follow tasks sequentially -- Commit after each task -``` - -## Integration with Other Skills - -### From Brainstorming - -```bash -/brainstorm "feature X" -# → Design created -/plan designs/feature-x.md -# → Plan created -``` - -### To Executing Plans - -```bash -/plan "feature Y" -# → Plan created in plans/feature-y.md -/execute-plan plans/feature-y.md -# → Automated execution begins -``` - -### With TDD - -Every task in the plan follows TDD: -1. Write failing test -2. Verify failure -3. Implement -4. Verify success -5. Commit - -See [TDD skill](/claudekit/skills/methodology/tdd) for details. - -## Best Practices - -### Start with File List - -Before writing tasks, list all files: - -```markdown -## Files Involved -- `src/models/user.ts` - Add fields -- `src/services/user-service.ts` - Add methods -- `src/routes/auth.ts` - Add endpoints -- `src/utils/email.ts` - Email helpers -- Tests for each of above -``` - -### Group Related Tasks - -```markdown -## Phase 1: Database Layer (Tasks 1-3) -## Phase 2: Business Logic (Tasks 4-6) -## Phase 3: API Layer (Tasks 7-9) -## Phase 4: Integration (Tasks 10-12) -``` - -### Include Verification Steps - -Every task must verify: -- Test fails before implementation -- Test passes after implementation -- Full suite still passes - -## Common Pitfalls - -### Tasks Too Large - -``` -❌ "Implement authentication system" (hours) -✅ "Add password field to User model" (3 minutes) -``` - -### Missing Expected Output - -``` -❌ "Run npm test" -✅ "Run npm test (expect: 42 passing, 0 failing)" -``` - -### Vague File References - -``` -❌ "Update the service" -✅ "Modify src/services/user-service.ts line 45" -``` - -### No TDD Cycle - -``` -❌ "Add the feature and test it" -✅ "1. Write failing test, 2. Verify fails, 3. Implement, 4. Verify passes" -``` - -## Next Steps - -After creating a plan: - -1. **Review the plan**: Ensure it's complete and detailed -2. **Execute manually**: Follow tasks yourself, or -3. **Execute with agent**: Use [Executing Plans](/claudekit/skills/methodology/executing-plans) -4. **Review code**: Use [Code Review](/claudekit/skills/methodology/code-review) - -## Related Skills - -- [Brainstorming](/claudekit/skills/methodology/brainstorming) - Design before planning -- [Executing Plans](/claudekit/skills/methodology/executing-plans) - Automated execution -- [TDD](/claudekit/skills/methodology/tdd) - Test-driven development -- [Code Review](/claudekit/skills/methodology/code-review) - Quality gates diff --git a/website/src/content/docs/skills/overview.md b/website/src/content/docs/skills/overview.md deleted file mode 100644 index 5cfea72..0000000 --- a/website/src/content/docs/skills/overview.md +++ /dev/null @@ -1,273 +0,0 @@ ---- -title: Skills Overview -description: Comprehensive guide to all Claude Kit skills organized by category ---- - -Claude Kit includes a rich library of skills that provide deep expertise in methodologies, languages, frameworks, and tools. Skills are automatically activated when relevant to your task, or can be explicitly invoked. - -## What Are Skills? - -Skills are knowledge modules that enhance Claude's capabilities in specific domains. Each skill contains: - -- **Best practices** for the technology or methodology -- **Common patterns** and code examples -- **Anti-patterns** to avoid -- **Activation conditions** - when the skill is used -- **Integration points** with other skills - -## Skill Categories - -### Methodology Skills - -Development methodologies and workflows for high-quality software delivery. - -| Skill | Purpose | Key Feature | -|-------|---------|-------------| -| [Brainstorming](/claudekit/skills/methodology/brainstorming) | Interactive design refinement | One question at a time | -| [Writing Plans](/claudekit/skills/methodology/writing-plans) | Detailed implementation plans | 2-5 minute tasks | -| [Executing Plans](/claudekit/skills/methodology/executing-plans) | Automated plan execution | Fresh agents per task | -| [Test-Driven Development](/claudekit/skills/methodology/tdd) | TDD workflow | Red-green-refactor cycle | -| [Systematic Debugging](/claudekit/skills/methodology/systematic-debugging) | Root-cause debugging | Four-phase process | -| [Code Review](/claudekit/skills/methodology/code-review) | Request & receive reviews | Categorized feedback | -| [Sequential Thinking](/claudekit/skills/methodology/sequential-thinking) | Complex problem analysis | Evidence-based reasoning | -| [Verification Before Completion](/claudekit/skills/methodology/verification) | Mandatory verification | Never claim without proof | -| [Testing Anti-Patterns](/claudekit/skills/methodology/testing-anti-patterns) | Avoid common test mistakes | Mock behavior detection | - -### Language Skills - -Modern programming language expertise with best practices. - -| Skill | Purpose | Key Features | -|-------|---------|--------------| -| [Python](/claudekit/skills/languages/python) | Python development | Type hints, async, dataclasses | -| [TypeScript](/claudekit/skills/languages/typescript) | TypeScript development | Strict typing, utility types | -| [JavaScript](/claudekit/skills/languages/javascript) | Modern JavaScript | ES6+, async patterns | - -### Framework Skills - -Full-stack framework knowledge and patterns. - -| Skill | Purpose | Key Features | -|-------|---------|--------------| -| [React](/claudekit/skills/frameworks/react) | React components | Hooks, context, patterns | -| [Next.js](/claudekit/skills/frameworks/nextjs) | Next.js App Router | Server components, actions | -| [FastAPI](/claudekit/skills/frameworks/fastapi) | FastAPI REST APIs | Pydantic, async, OpenAPI | -| [Django](/claudekit/skills/frameworks/django) | Django web apps | ORM, views, REST framework | - -### Database Skills - -Database design and query optimization. - -- **PostgreSQL** - Relational database expertise -- **MongoDB** - Document database patterns - -### Testing Skills - -Test frameworks and testing methodologies. - -- **pytest** - Python testing with fixtures -- **vitest** - Fast Vite-based testing - -### DevOps Skills - -Deployment and infrastructure automation. - -- **Docker** - Container best practices -- **GitHub Actions** - CI/CD workflows - -### Frontend Skills - -Modern frontend development tools. - -- **Tailwind CSS** - Utility-first CSS -- **shadcn/ui** - React component library - -### Security Skills - -Security best practices and vulnerability prevention. - -- **OWASP** - Web security standards - -### API Skills - -API design and documentation. - -- **OpenAPI** - REST API specification - -### Optimization Skills - -Performance and cost optimization. - -- **Token Efficient** - Reduce API costs - -## How Skills Are Activated - -### Automatic Activation - -Skills activate automatically based on context: - -```typescript -// Working with a .ts file automatically activates: -// - TypeScript skill -// - JavaScript skill (parent) - -// Using React components activates: -// - React skill -// - TypeScript skill -// - JavaScript skill -``` - -### Explicit Activation - -Reference skills directly in commands: - -```bash -# Use specific methodology -/plan --methodology=tdd "add user authentication" - -# Activate debugging skill -/fix --use-skill=systematic-debugging "timeout error" - -# Enable sequential thinking -/research --sequential "performance bottleneck" -``` - -### Mode-Based Activation - -Certain modes activate related skills: - -```bash -# Deep research mode enables: -/mode deep-research -# - Sequential thinking -# - Root cause tracing -# - Evidence collection - -# Implementation mode enables: -/mode implementation -# - TDD -# - Verification before completion -# - Testing anti-patterns awareness -``` - -## Combining Skills - -Skills work together synergistically: - -### Planning to Execution - -1. **Brainstorming** - Design the solution -2. **Writing Plans** - Break into tasks -3. **Executing Plans** - Automated implementation -4. **Code Review** - Quality gates - -### Bug Fixing - -1. **Systematic Debugging** - Find root cause -2. **Sequential Thinking** - Analyze evidence -3. **TDD** - Write regression test -4. **Verification** - Confirm fix works - -### Feature Development - -1. **Brainstorming** - Explore approaches -2. **Writing Plans** - Detailed tasks -3. **TDD** - Test-first implementation -4. **Code Review** - Review and iterate -5. **Verification** - Confirm completion - -## Customizing Skills - -Skills can be customized in your `.claude/CLAUDE.md`: - -```markdown -## Skill Overrides - -### TDD Strictness -- Level: Strict (no code without tests) -- Red-Green-Refactor: Always required - -### Code Review -- Required reviewers: 1 minimum -- Security review: Required for auth changes -- Performance review: Required for queries - -### Brainstorming -- Style: Interactive (one question at a time) -- YAGNI: Ruthless (remove all "might need") -``` - -## Creating Custom Skills - -Add project-specific skills: - -```bash -.claude/skills/ -├── custom/ -│ ├── company-api-patterns/ -│ │ └── SKILL.md -│ └── deployment-checklist/ -│ └── SKILL.md -``` - -See [Custom Skills Guide](/claudekit/guides/custom-skills) for details. - -## Skill Reference - -For detailed documentation on each skill: - -- **Methodology**: See individual skill pages linked above -- **Languages**: Python, TypeScript, JavaScript skill pages -- **Frameworks**: React, Next.js, FastAPI, Django pages -- **Other Categories**: Browse `/skills/` directory - -## Best Practices - -### Let Skills Guide You - -Trust the methodologies: - -```bash -# Instead of: -"Just write some code for X" - -# Use: -"/brainstorm X" → design first -"/plan X" → break into tasks -"/execute-plan" → implement systematically -``` - -### Combine Complementary Skills - -Use skills together: - -```bash -# TDD + Systematic Debugging -1. Write failing test (TDD) -2. Investigate why it fails (Debugging) -3. Fix root cause (Debugging) -4. Verify test passes (Verification) - -# Brainstorming + Sequential Thinking -1. Explore options (Brainstorming) -2. Analyze each deeply (Sequential Thinking) -3. Choose with evidence (Sequential Thinking) -``` - -### Respect Skill Constraints - -Skills enforce quality standards: - -- **TDD**: No production code without failing test first -- **Verification**: Never claim completion without proof -- **Code Review**: All critical issues must be fixed -- **Systematic Debugging**: Three-fix rule stops runaway debugging - -These aren't suggestions - they're requirements. - -## Next Steps - -- Explore [Methodology Skills](/claudekit/skills/methodology/brainstorming) -- Learn [Language Skills](/claudekit/skills/languages/python) -- Check [Framework Skills](/claudekit/skills/frameworks/react) -- Try [Custom Skills](/claudekit/guides/custom-skills) diff --git a/website/src/content/docs/workflows/planning-and-building.md b/website/src/content/docs/workflows/planning-and-building.md new file mode 100644 index 0000000..87704ad --- /dev/null +++ b/website/src/content/docs/workflows/planning-and-building.md @@ -0,0 +1,151 @@ +--- +title: Planning & Building +description: How Claude Kit guides you from idea to implementation using brainstorming, planning, and execution skills. +--- + +# Planning & Building + +Claude Kit provides a structured workflow for turning ideas into working code: **Brainstorm > Plan > Execute > Verify**. + +## The Workflow + +``` +"I need to add user authentication" + │ + ▼ +┌─────────────────┐ +│ Brainstorming │ Explore requirements, ask questions, +│ │ evaluate approaches, validate design +└────────┬────────┘ + ▼ +┌─────────────────┐ +│ Writing Plans │ Break into tasks, exact file paths, +│ │ code samples, verification steps +└────────┬────────┘ + ▼ +┌─────────────────┐ +│ Executing Plans │ Fresh subagent per task, code review +│ │ between tasks, quality gates +└────────┬────────┘ + ▼ +┌─────────────────┐ +│ Verification │ Run tests, verify builds, +│ │ evidence before claims +└─────────────────┘ +``` + +## Phase 1: Brainstorming + +**Triggers on**: "brainstorm", "design", "explore", "what if", "how should we", "trade-offs" + +The brainstorming skill uses a three-phase process: + +1. **Understanding** — Asks one question at a time to clarify requirements. Prefers multiple-choice over open-ended questions. +2. **Exploration** — Presents 2-3 approaches with trade-offs, leads with a recommendation. +3. **Design** — Presents the validated design in digestible 200-300 word sections. + +### Example + +``` +You: "Let's brainstorm adding real-time notifications" + +Claude: "Which delivery mechanism fits your use case best? + a) WebSockets — persistent connection, instant delivery + b) Server-Sent Events — simpler, one-way push + c) Polling — simplest, but higher latency" + +You: "b) SSE" + +Claude: "## Approach 1: SSE + Redis Pub/Sub (Recommended) + Server pushes events via SSE, Redis coordinates across instances. + - Pros: Simple, works with load balancers, auto-reconnect built in + - Cons: One-way only (client can't push back) + + ## Approach 2: SSE + PostgreSQL LISTEN/NOTIFY + ..." +``` + +## Phase 2: Writing Plans + +**Triggers on**: "plan", "break down", "implementation steps", "task list" + +The writing-plans skill creates detailed implementation plans with: + +- Exact file paths for every change +- Complete code samples (not descriptions) +- Verification commands with expected output +- 2-5 minute task granularity + +### Plan Structure + +```markdown +## Task 1: Create User model with email field + +**Files**: +- Create: `src/models/user.ts` +- Test: `src/models/user.test.ts` + +**Steps**: +1. Write failing test +2. Verify test fails +3. Implement minimally +4. Verify test passes +5. Commit +``` + +## Phase 3: Executing Plans + +**Triggers on**: "execute the plan", "run the plan", "implement the plan" + +The executing-plans skill runs each task with: + +- **Fresh subagent per task** — Prevents context pollution +- **Code review between tasks** — Catches issues early +- **Quality gates** — Critical issues must be fixed before proceeding + +### Execution Flow + +``` +Task 1 → Implement → Review → Fix issues → ✓ +Task 2 → Implement → Review → Fix issues → ✓ +Task 3 → Implement → Review → Fix issues → ✓ +Final comprehensive review → ✓ +``` + +## Phase 4: Verification + +**Auto-triggers on**: completion claims ("done", "fixed", "tests pass") + +The verification-before-completion skill requires evidence before any completion claim: + +- Run the actual test suite and read the output +- Verify the build succeeds +- Check that the feature works as intended + +## Supporting Skills + +These skills activate automatically during planning and building: + +| Skill | When It Helps | +|-------|---------------| +| `feature-workflow` | End-to-end feature development | +| `sequential-thinking` | Complex decisions needing step-by-step reasoning | +| `languages` | Python/TypeScript/JavaScript idioms and patterns | +| `backend-frameworks` | FastAPI, Django, NestJS, Express patterns | +| `frontend` | React, Next.js component architecture | +| `databases` | Schema design, queries, migrations | +| `state-management` | Choosing between useState, Zustand, TanStack Query | + +## Supporting Agents + +| Agent | Role | +|-------|------| +| `planner` | Research and create implementation plans | +| `brainstormer` | Explore solutions and evaluate trade-offs | +| `researcher` | Research technologies and best practices | + +## Related Pages + +- [Testing & Debugging](/claudekit/workflows/testing-and-debugging/) — TDD and debugging workflows +- [Reviewing & Shipping](/claudekit/workflows/reviewing-and-shipping/) — Code review and git workflows +- [Skills Reference](/claudekit/reference/skills/) — All 43 skills diff --git a/website/src/content/docs/workflows/reviewing-and-shipping.md b/website/src/content/docs/workflows/reviewing-and-shipping.md new file mode 100644 index 0000000..aab2795 --- /dev/null +++ b/website/src/content/docs/workflows/reviewing-and-shipping.md @@ -0,0 +1,147 @@ +--- +title: Reviewing & Shipping +description: How Claude Kit handles code review, git workflows, PR creation, and branch management. +--- + +# Reviewing & Shipping + +Claude Kit provides structured workflows for code review, committing, creating PRs, and finishing development branches. + +## Code Review + +### Requesting Reviews + +**Triggers on**: completing features, before PRs, before merging + +The requesting-code-review skill prepares code for review with: + +- Clear scope of what changed and why +- Areas of concern flagged for reviewers +- Context on architectural decisions + +### Receiving Reviews + +**Triggers on**: review feedback, PR comments, review rejections + +The receiving-code-review skill processes feedback systematically: + +1. **Categorize** — Critical vs. important vs. minor +2. **Prioritize** — Fix critical issues first +3. **Implement** — Address feedback with evidence +4. **Re-request** — Summary of changes made + +### Review Agents + +| Agent | Focus | +|-------|-------| +| `code-reviewer` | Quality, security, performance, maintainability | +| `security-auditor` | OWASP compliance, vulnerability detection | + +## Git Workflows + +**Triggers on**: "commit", "push", "PR", "ship", "changelog" + +The git-workflows skill enforces: + +### Conventional Commits + +``` +type(scope): subject + +feat(auth): add JWT token refresh endpoint +fix(cart): handle empty cart total calculation +docs(api): update OpenAPI spec for v2 endpoints +``` + +Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore` + +### Branch Naming + +``` +feature/AUTH-123-jwt-refresh +fix/CART-456-empty-total +hotfix/critical-payment-bug +chore/upgrade-dependencies +``` + +### PR Creation + +Claude Kit generates well-structured PRs: + +```markdown +## Summary +- Added JWT token refresh endpoint +- Tokens auto-refresh 5 minutes before expiry + +## Test Plan +- [ ] Unit tests for token refresh logic +- [ ] Integration test for refresh endpoint +- [ ] Manual test: login → wait → verify auto-refresh +``` + +## Finishing a Branch + +**Triggers on**: "ship it", "ready to merge", "branch is done", "create a PR" + +The finishing-a-development-branch skill runs a completion checklist: + +1. **Verify** — All tests pass, build succeeds +2. **Review** — Run final code review +3. **Options** — Present merge strategies: + - Create PR for team review + - Merge directly (if authorized) + - Clean up worktree (if using git worktrees) + +## Git Worktrees + +**Triggers on**: "worktree", "isolated branch", "parallel branches" + +The using-git-worktrees skill creates isolated working copies for: + +- Feature work that shouldn't affect the main workspace +- Parallel development on multiple branches +- Safe experimentation without risk to in-progress work + +``` +main workspace: d:/project/ (main branch) +feature worktree: d:/project-feature/ (feature/auth branch) +hotfix worktree: d:/project-hotfix/ (hotfix/payment branch) +``` + +## Changelog Generation + +The git-workflows skill generates changelogs from conventional commits: + +```markdown +## [1.2.0] - 2026-04-19 + +### Added +- JWT token refresh endpoint (AUTH-123) +- Auto-refresh 5 minutes before expiry + +### Fixed +- Empty cart total calculation (CART-456) +``` + +## Supporting Skills + +| Skill | When It Helps | +|-------|---------------| +| `documentation` | Generating/updating docs after code changes | +| `refactoring` | Improving code structure before shipping | +| `writing-concisely` | Token-efficient mode for high-volume review sessions | + +## Supporting Agents + +| Agent | Role | +|-------|------| +| `git-manager` | Stage, commit, push with conventional commits | +| `code-reviewer` | Comprehensive code review | +| `copywriter` | Release notes, changelogs, PR descriptions | +| `docs-manager` | Keep documentation in sync with code | + +## Related Pages + +- [Planning & Building](/claudekit/workflows/planning-and-building/) — Brainstorm, plan, execute +- [Testing & Debugging](/claudekit/workflows/testing-and-debugging/) — TDD and debugging workflows +- [Skills Reference](/claudekit/reference/skills/) — All 43 skills diff --git a/website/src/content/docs/workflows/testing-and-debugging.md b/website/src/content/docs/workflows/testing-and-debugging.md new file mode 100644 index 0000000..6e6f3e6 --- /dev/null +++ b/website/src/content/docs/workflows/testing-and-debugging.md @@ -0,0 +1,145 @@ +--- +title: Testing & Debugging +description: How Claude Kit enforces test-driven development, systematic debugging, and verification. +--- + +# Testing & Debugging + +Claude Kit enforces quality through three connected workflows: **TDD for building**, **systematic debugging for fixing**, and **verification before completion**. + +## Test-Driven Development + +**Triggers on**: "implement", "add feature", "fix bug", "write code", "build" + +The TDD skill enforces a strict red-green-refactor cycle for all production code changes: + +``` +1. Write a failing test → Run it → Confirm it fails (RED) +2. Write minimal code → Run it → Confirm it passes (GREEN) +3. Refactor if needed → Run it → Confirm it still passes +4. Commit +``` + +### Why TDD by Default? + +- Tests document intent, not just behavior +- Catches regressions immediately +- Forces small, focused changes +- Creates natural commit points + +### Stack-Specific Commands + +| Stack | Test Command | Full Verify | +|-------|-------------|-------------| +| Python/FastAPI | `pytest tests/test_.py -v` | `pytest -v && ruff check .` | +| TypeScript/NestJS | `npm test -- --testPathPattern=` | `npm test && npm run lint && npm run build` | +| Next.js/React | `npx vitest run ` | `npm test && next lint && next build` | + +## Systematic Debugging + +**Triggers on**: "bug", "error", "failing", "broken", "doesn't work", "TypeError", stack traces + +The systematic-debugging skill follows a four-phase investigation: + +### Phase 1: Observe + +Gather evidence before forming hypotheses: +- Read the error message and stack trace +- Reproduce the issue +- Check logs and recent changes + +### Phase 2: Hypothesize + +Form specific, testable theories: +- "The null check on line 42 doesn't handle the empty array case" +- Not: "Something is wrong with the data" + +### Phase 3: Test + +Verify each hypothesis systematically: +- Add logging or breakpoints +- Write a test that reproduces the bug +- Isolate the failing component + +### Phase 4: Fix + +Apply the minimal fix: +- Fix the root cause, not the symptom +- Add a regression test +- Verify the original error is gone + +### Root Cause Tracing + +**Triggers on**: deep bugs where the error location differs from the bug origin + +For bugs that manifest far from their source, the root-cause-tracing skill traces the data flow backward to find where things first went wrong: + +``` +Error: NullPointerException at OrderService.getTotal() + ↓ trace backward +OrderService.getTotal() receives null item + ↓ trace backward +CartService.getItems() returns null for empty cart + ↓ root cause +CartRepository.findByUserId() returns null instead of [] +``` + +## Verification Before Completion + +**Auto-triggers on**: "done", "fixed", "tests pass", "build succeeds" + +The verification skill prevents false completion claims. Before saying "done", Claude must: + +1. **Run the test suite** and read the output +2. **Run the build** and confirm it succeeds +3. **Check for regressions** in related functionality +4. **Show evidence** — actual command output, not assumptions + +### What Gets Caught + +``` +Without verification: + "I've fixed the bug" → Actually introduced a new failing test + +With verification: + Run pytest → See 2 failures → Fix both → Run again → All green → "Fixed" +``` + +## Testing Anti-Patterns + +**Triggers on**: "mock", "flaky test", "test passes but bug ships", "false positive" + +The testing-anti-patterns skill catches common mistakes: + +| Anti-Pattern | Problem | Fix | +|-------------|---------|-----| +| Heavy mocking | Tests pass but production breaks | Test real integrations | +| Testing implementation | Tests break on refactor | Test behavior, not internals | +| No edge cases | Happy path works, edge cases crash | Test boundaries and errors | +| Flaky tests | Random failures erode trust | Fix or delete, never ignore | + +## Defense in Depth + +**Triggers on**: data validation bugs, "it slipped through", bypass scenarios + +The defense-in-depth skill adds validation at multiple layers so a single-point failure can't cause data corruption: + +``` +API layer: Validate input shape (Pydantic/Zod) +Service layer: Validate business rules +Database layer: Constraints (NOT NULL, UNIQUE, CHECK) +``` + +## Supporting Agents + +| Agent | Role | +|-------|------| +| `tester` | Run test suites, analyze coverage, validate error handling | +| `debugger` | Investigate bugs, check logs, reproduce issues | +| `security-auditor` | Security-focused code review | + +## Related Pages + +- [Planning & Building](/claudekit/workflows/planning-and-building/) — Brainstorm, plan, execute +- [Reviewing & Shipping](/claudekit/workflows/reviewing-and-shipping/) — Code review and git workflows +- [Skills Reference](/claudekit/reference/skills/) — All 43 skills