From dd5e5e768d84d70b3955709c0e68790bbfd21157 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 23 Jan 2026 21:29:29 +0000 Subject: [PATCH 1/5] Initial plan From 82685a74323f7105db1d5abf6265f2526597cc75 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 23 Jan 2026 21:34:41 +0000 Subject: [PATCH 2/5] Add comprehensive development patterns documentation Co-authored-by: burtbyproxy <1827866+burtbyproxy@users.noreply.github.com> --- .vibe/claude.instructions.md | 20 + .vibe/templates/claude-context.md.template | 221 +++++++ README.md | 26 + docs/development-patterns.md | 731 +++++++++++++++++++++ docs/tasking-claude.md | 406 ++++++++++++ 5 files changed, 1404 insertions(+) create mode 100644 .vibe/templates/claude-context.md.template create mode 100644 docs/development-patterns.md create mode 100644 docs/tasking-claude.md diff --git a/.vibe/claude.instructions.md b/.vibe/claude.instructions.md index f5fe2df..f449a86 100644 --- a/.vibe/claude.instructions.md +++ b/.vibe/claude.instructions.md @@ -164,3 +164,23 @@ Options: Which would you prefer? ``` + +--- + +## Development Patterns + +VibeScript defines governance (what/where you can modify). Your project may also define **development patterns** (how to write code). + +Check for these optional pattern files: +- `docs/development-patterns.md` - Reference guide of common patterns (YAGNI, DRY, SOLID, testing, etc.) +- `docs/tasking-claude.md` - Quick start templates for applying patterns +- `.vibe/claude-context.md` - Project-specific pattern configuration + +If these files exist, follow the patterns specified within them. They define: +- Code organization and architecture +- Testing strategies and coverage requirements +- Documentation standards +- Error handling approaches +- Commit and change scope preferences + +When patterns conflict with VibeScript governance, governance wins. When uncertain, ask the user. diff --git a/.vibe/templates/claude-context.md.template b/.vibe/templates/claude-context.md.template new file mode 100644 index 0000000..ff8dbe2 --- /dev/null +++ b/.vibe/templates/claude-context.md.template @@ -0,0 +1,221 @@ +# Claude Context Template + +**Purpose**: Customize this template with your preferred development patterns and provide it to Claude at the start of a project or task. This creates consistent behavior across AI coding sessions. + +--- + +## Project Information + +**Project Name**: `{{PROJECT_NAME}}` + +**Technology Stack**: `{{TECH_STACK}}` + +**Project Phase**: `[ ] Prototype [ ] MVP [ ] Production [ ] Maintenance` + +--- + +## Selected Development Patterns + +Reference patterns from `development-patterns.md`. Check boxes to indicate which patterns apply: + +### Core Philosophy + +- [ ] **YAGNI**: `[ ] Strict [ ] Moderate [ ] Relaxed` +- [ ] **DRY**: `[ ] Strict [ ] Moderate [ ] Relaxed` +- [ ] **SOLID**: `[ ] Full SOLID [ ] Pragmatic [ ] Minimal OOP` + +### Code Organization + +- [ ] **Module Structure**: `[ ] Domain-Driven [ ] Layer-Based [ ] Feature-Based` +- [ ] **Naming**: `[ ] Verbose [ ] Balanced [ ] Terse` + +### Testing Approach + +- [ ] **Method**: `[ ] Strict TDD [ ] Test-After [ ] Critical-Path Only` +- [ ] **Coverage**: `[ ] High (80%+) [ ] Pragmatic (60%+) [ ] Smoke Tests` + +### Error Handling + +- [ ] **Strategy**: `[ ] Fail-Fast [ ] Graceful Degradation [ ] Result Types` + +### Documentation + +- [ ] **Level**: `[ ] Full JSDoc [ ] Public APIs Only [ ] Self-Documenting [ ] README-Driven` + +### Performance + +- [ ] **Strategy**: `[ ] Avoid Premature [ ] Proactive [ ] Performance-Critical` + +### Security + +- [ ] **Validation**: `[ ] Strict [ ] Standard [ ] Basic` +- [ ] **Auth/Authz**: `[ ] Defense in Depth [ ] Standard Checks [ ] Basic` + +### Commit Style + +- [ ] **Size**: `[ ] Atomic [ ] Feature-Based [ ] As Needed` +- [ ] **Scope**: `[ ] Surgical [ ] Opportunistic Improvements` + +--- + +## Custom Instructions + +Add any project-specific patterns, conventions, or requirements: + +``` +{{CUSTOM_INSTRUCTIONS}} +``` + +--- + +## Architectural Constraints + +List any architectural decisions or constraints Claude must follow: + +- `{{CONSTRAINT_1}}` +- `{{CONSTRAINT_2}}` +- `{{CONSTRAINT_3}}` + +--- + +## Things to Avoid + +List specific anti-patterns or approaches to avoid in this project: + +- ❌ `{{AVOID_1}}` +- ❌ `{{AVOID_2}}` +- ❌ `{{AVOID_3}}` + +--- + +## Project-Specific Vocabulary + +Define domain-specific terms and concepts: + +- **`{{TERM_1}}`**: `{{DEFINITION_1}}` +- **`{{TERM_2}}`**: `{{DEFINITION_2}}` +- **`{{TERM_3}}`**: `{{DEFINITION_3}}` + +--- + +## Integration with VibeScript + +VibeScript governance is `[ ] Enabled [ ] Disabled` for this project. + +If enabled, Claude must: +1. Read `.vibe/claude.instructions.md` before making changes +2. Create `.vibe.*` files with all required directives +3. Declare all touched files in `@vibe:touch` directives +4. Run `vibe:check` and `vibe:guard` before committing +5. Follow file ownership rules + +--- + +## Quick Reference + +**One-Line Summary**: +``` +{{PATTERN_SUMMARY}} +``` + +Example: `"Strict YAGNI, Moderate DRY, TDD with 80% coverage, Full JSDoc, Fail-fast errors, Atomic commits"` + +--- + +## Example Filled Template + +Here's an example of how to fill this template: + +### Project Information +- **Project Name**: E-Commerce API +- **Technology Stack**: Node.js, TypeScript, PostgreSQL, Express +- **Project Phase**: ✓ Production + +### Selected Development Patterns + +**Core Philosophy**: +- ✓ YAGNI: Moderate +- ✓ DRY: Moderate +- ✓ SOLID: Pragmatic + +**Testing Approach**: +- ✓ Method: Test-After Development +- ✓ Coverage: Pragmatic (60%+) + +**Error Handling**: +- ✓ Strategy: Fail-Fast at boundaries, graceful degradation internally + +**Documentation**: +- ✓ Level: Full JSDoc for public APIs, inline comments for complex logic + +**Commit Style**: +- ✓ Size: Atomic +- ✓ Scope: Surgical + +### Custom Instructions +``` +- All database queries must use the repository pattern +- API responses must match the JSON:API specification +- All external API calls must have retry logic with exponential backoff +- Use Zod for runtime validation of all inputs +- Prefer functional programming style where appropriate +``` + +### Architectural Constraints +- No business logic in controllers (must be in services) +- Database schema changes require migration files +- All secrets must be in environment variables, never hardcoded + +### Things to Avoid +- ❌ Don't use `any` type in TypeScript +- ❌ Don't query database from controllers +- ❌ Don't add dependencies without checking for vulnerabilities + +### Project-Specific Vocabulary +- **SKU**: Stock Keeping Unit, unique product identifier +- **Cart**: User's shopping cart, stored in Redis with 24hr TTL +- **Fulfillment**: Process of packing and shipping orders + +--- + +## Usage Instructions + +1. **Fill out this template** with your project's patterns and constraints +2. **Save it** as `.vibe/claude-context.md` in your project +3. **Reference it** when tasking Claude: + + ``` + "Claude, read .vibe/claude-context.md for this project's + development patterns, then implement the user registration feature." + ``` + +4. **Update it** as patterns evolve or as you learn what works + +--- + +## Template for Copy-Paste + +```markdown +# Project Development Context + +## Quick Instructions +Claude, use: {{YAGNI_LEVEL}} YAGNI, {{DRY_LEVEL}} DRY, {{TEST_METHOD}}, +{{DOC_LEVEL}} docs, {{ERROR_STRATEGY}} errors, {{COMMIT_STYLE}} commits + +## Custom Rules +- {{RULE_1}} +- {{RULE_2}} +- {{RULE_3}} + +## Must Avoid +- ❌ {{AVOID_1}} +- ❌ {{AVOID_2}} + +## VibeScript +Read .vibe/claude.instructions.md and follow all governance rules. +``` + +--- + +**Version**: 1.0.0 +**Last Updated**: 2026-01-23 diff --git a/README.md b/README.md index a2af0e3..ef20d90 100644 --- a/README.md +++ b/README.md @@ -251,6 +251,26 @@ The vibes are nice. The scripts make sure nobody gets hurt. > *"If we're going to hand the codebase to AI, we should at least make them suffer through code review first."* +## Development Patterns & Best Practices + +VibeScript tells Claude **what** and **where** it can modify. But you might also want to control **how** it writes code. + +We've created a comprehensive recipe of development patterns (YAGNI, DRY, SOLID, testing strategies, etc.) that you can mix and match when tasking Claude: + +- **[Development Patterns Reference](docs/development-patterns.md)** - Complete guide to common patterns with strict/moderate/relaxed levels +- **[Tasking Claude Guide](docs/tasking-claude.md)** - Quick start templates for assigning work to Claude +- **[Claude Context Template](.vibe/templates/claude-context.md.template)** - Customizable template for your project's patterns + +**Example usage:** +``` +"Claude, implement user authentication using: +- VibeScript governance (read .vibe/claude.instructions.md) +- Development patterns: Production Ready template (see docs/development-patterns.md) +- YAGNI: Moderate, DRY: Moderate, Testing: TDD with 80% coverage" +``` + +These patterns let you define development philosophy that's consistent across tasks and team members (human or AI). + ## For Humans Setting This Up If you're a human reading this and want to install VibeScript for your AI assistant: @@ -262,6 +282,12 @@ pnpm vibescript init Then tell Claude: *"Before making any changes, read `.vibe/claude.instructions.md` and follow the VibeScript governance rules."* +For consistent code style and patterns, also set up your development patterns: +``` +"Claude, also read docs/development-patterns.md and apply the 'Production Ready' +template (or customize .vibe/templates/claude-context.md.template for your preferences)." +``` + ## License MIT diff --git a/docs/development-patterns.md b/docs/development-patterns.md new file mode 100644 index 0000000..b7f3c8d --- /dev/null +++ b/docs/development-patterns.md @@ -0,0 +1,731 @@ +# Development Patterns Recipe for VibeScript Projects + +**For Humans**: Use this document to customize Claude's behavior when working on your VibeScript projects. Mix and match patterns to create the perfect instructions for your team's coding standards. + +**For Claude**: When a human references this document, apply the specified patterns to your work. These patterns complement VibeScript's governance framework by defining *how* you write code, while VibeScript defines *where* and *what* you can modify. + +--- + +## How to Use This Recipe + +This document provides a menu of common development patterns. When starting a project, select the patterns that match your team's philosophy: + +``` +"Claude, follow these patterns from development-patterns.md: +- YAGNI (strict) +- DRY (moderate) +- Testing: TDD approach +- Documentation: inline only +- Error handling: fail-fast" +``` + +Or create your own custom combination. Each pattern has multiple levels you can choose from. + +--- + +## Core Development Philosophies + +### YAGNI (You Aren't Gonna Need It) + +**Strict Mode** - Only implement exactly what's requested, nothing more: +``` +- No "future-proofing" or "what if" code +- No unused parameters or optional features +- No abstraction layers until third use case +- No helper functions until needed twice +- Single-purpose modules only +``` + +**Moderate Mode** - Balance current needs with obvious next steps: +``` +- Implement requested features fully +- Add reasonable extension points (interfaces, hooks) +- Include one level of abstraction if pattern is clear +- Document obvious future considerations +- No speculative code, but leave room to grow +``` + +**Relaxed Mode** - Design for known roadmap: +``` +- Implement current requirements +- Add abstraction for planned features +- Include configuration hooks for variants +- Build with next quarter's roadmap in mind +- Balance current simplicity with near-term needs +``` + +**When to apply**: Reference YAGNI level in your initial instructions to Claude. + +--- + +### DRY (Don't Repeat Yourself) + +**Strict Mode** - Eliminate all duplication: +``` +- Extract any code repeated more than once +- Create abstractions for similar patterns +- Unify all related logic into single modules +- Factor out all magic numbers and strings +- Share utilities across all modules +``` + +**Moderate Mode** - Balance DRY with readability: +``` +- Extract code repeated three or more times +- Create abstractions for clear patterns +- Keep related logic together even if slightly duplicated +- Allow some duplication if abstraction is complex +- Prefer clarity over maximum reuse +``` + +**Relaxed Mode** - Optimize for local clarity: +``` +- Extract only obvious reusable utilities +- Prefer explicit code over clever abstractions +- Allow duplication if it improves readability +- Keep code self-contained in modules +- Optimize for understanding over brevity +``` + +**When to apply**: Specify DRY level when you want to control abstraction vs. explicitness tradeoff. + +--- + +### SOLID Principles + +**Full SOLID** - Apply all five principles strictly: +``` +Single Responsibility: One class, one reason to change +Open/Closed: Extend via composition, not modification +Liskov Substitution: Subtypes fully substitutable +Interface Segregation: Small, focused interfaces +Dependency Inversion: Depend on abstractions, not concretions +``` + +**Pragmatic SOLID** - Apply where it adds value: +``` +- Use SRP for large modules (>200 lines) +- Use OCP for plugin systems and extensions +- Use LSP when inheritance is necessary +- Use ISP for public APIs and contracts +- Use DIP for external dependencies only +``` + +**Minimal OOP** - Functional-first approach: +``` +- Prefer functions over classes +- Use classes only for stateful entities +- Avoid inheritance hierarchies +- Use composition and interfaces sparingly +- Focus on data transformations +``` + +**When to apply**: Reference when working in OOP-heavy codebases or when architectural consistency matters. + +--- + +## Code Organization Patterns + +### Module Structure + +**Domain-Driven** - Organize by business domain: +``` +src/ + users/ + users.service.ts + users.repository.ts + users.types.ts + orders/ + orders.service.ts + orders.repository.ts + shared/ + database.ts + utils.ts +``` + +**Layer-Based** - Organize by technical layer: +``` +src/ + controllers/ + services/ + repositories/ + models/ + utils/ +``` + +**Feature-Based** - Organize by user-facing feature: +``` +src/ + features/ + auth/ + checkout/ + profile/ + shared/ +``` + +**When to apply**: Specify structure when adding new modules to ensure consistency. + +--- + +### Naming Conventions + +**Verbose & Explicit**: +```typescript +getUserByEmailAddressFromDatabase() +isUserAuthenticatedAndActive() +convertRawAPIResponseToUserModel() +``` + +**Balanced & Clear**: +```typescript +getUserByEmail() +isUserActive() +parseUserResponse() +``` + +**Terse & Conventional**: +```typescript +getUser() +isActive() +parse() +``` + +**When to apply**: Reference at project start to establish naming philosophy. + +--- + +## Testing Patterns + +### Test-Driven Development (TDD) + +**Strict TDD** - Write tests first, always: +``` +1. Write failing test for new behavior +2. Implement minimal code to pass test +3. Refactor while keeping tests green +4. Never write production code without a failing test +5. Commit test and implementation together +``` + +**Test-After Development (TAD)**: +``` +1. Implement feature +2. Write comprehensive tests +3. Refactor based on test insights +4. Ensure high coverage before committing +``` + +**Critical-Path Testing**: +``` +- Test all public APIs and exports +- Test error conditions and edge cases +- Skip testing private implementation details +- Focus on behavior, not implementation +``` + +**When to apply**: Specify testing approach for each task or globally for project. + +--- + +### Test Coverage Philosophy + +**High Coverage** (80%+ lines, 100% branches): +``` +- Test all public functions +- Test all error paths +- Test edge cases and boundaries +- Include integration tests +- Mock external dependencies +``` + +**Pragmatic Coverage** (60%+ critical paths): +``` +- Test core business logic thoroughly +- Test API contracts and interfaces +- Test known edge cases +- Skip trivial getters/setters +- Integration tests for critical flows +``` + +**Smoke Testing** (happy paths only): +``` +- Test that main features work +- Test API endpoints return 200 +- Test critical user flows +- Skip error handling tests +- Skip edge cases +``` + +**When to apply**: Specify coverage expectations per module or feature. + +--- + +## Error Handling Patterns + +### Fail-Fast + +**Strict Validation**: +```typescript +function processPayment(amount: number) { + if (amount <= 0) throw new Error('Invalid amount'); + if (amount > MAX_AMOUNT) throw new Error('Amount too large'); + if (!isConnected()) throw new Error('Service unavailable'); + // ... process +} +``` + +**Fail-fast at boundaries, handle internally elsewhere** + +--- + +### Graceful Degradation + +**Handle and Continue**: +```typescript +function processPayment(amount: number) { + try { + return chargeCard(amount); + } catch (error) { + logError(error); + return fallbackPayment(amount); + } +} +``` + +**Degrade functionality rather than crash** + +--- + +### Return Error Values + +**Result Type Pattern**: +```typescript +type Result = { ok: true; value: T } | { ok: false; error: string }; + +function processPayment(amount: number): Result { + if (amount <= 0) return { ok: false, error: 'Invalid amount' }; + // ... + return { ok: true, value: receipt }; +} +``` + +**Explicit success/failure without exceptions** + +--- + +**When to apply**: Specify error handling strategy per module or project-wide. + +--- + +## Documentation Patterns + +### Inline Comments + +**Verbose Inline**: +```typescript +// Calculate the user's total order value by iterating through +// all items in their cart and summing the price * quantity for each. +// Apply any active discount codes before returning the final total. +function calculateTotal(cart: Cart): number { + // ... +} +``` + +--- + +### JSDoc/Documentation Comments + +**Full API Documentation**: +```typescript +/** + * Calculates the total cost of items in a shopping cart. + * + * @param cart - The shopping cart containing items to total + * @param discountCode - Optional discount code to apply + * @returns The total cost after discounts + * @throws {InvalidCartError} If cart is empty or invalid + * @example + * ```ts + * const total = calculateTotal(cart, 'SAVE10'); + * ``` + */ +function calculateTotal(cart: Cart, discountCode?: string): number { + // ... +} +``` + +--- + +### Self-Documenting Code + +**Minimal Documentation**: +```typescript +// Code structure and naming explain intent +// Only comment why, not what +function calculateTotal(cart: Cart): number { + // Apply loyalty discount for premium members (business rule as of Q4 2024) + const discount = cart.user.isPremium ? 0.1 : 0; + return cart.items.reduce((sum, item) => sum + item.price, 0) * (1 - discount); +} +``` + +--- + +### README-Driven + +**Comprehensive README files**: +```markdown +## Module: Payment Processing + +### Purpose +Handles all payment transactions for orders. + +### API +- `processPayment(order)` - Charges customer for order +- `refundPayment(orderId)` - Issues refund + +### Dependencies +- Stripe API (external) +- Orders service (internal) + +### Testing +Run: `npm test src/payment` +``` + +--- + +**When to apply**: Specify documentation level at project start or per-module. + +--- + +## Performance Patterns + +### Optimization Strategy + +**Premature Optimization** (avoid unless specified): +``` +- Don't optimize without profiling +- Don't add caching until needed +- Don't use complex algorithms without measuring +- Optimize only proven bottlenecks +``` + +**Proactive Performance**: +``` +- Use efficient data structures from start +- Avoid N+1 queries in database code +- Batch network requests where obvious +- Cache expensive computations +- Profile after implementation +``` + +**Performance-Critical**: +``` +- Profile before implementing +- Optimize all data access patterns +- Minimize allocations and copies +- Use appropriate algorithms (O(n) vs O(n²)) +- Benchmark all changes +``` + +**When to apply**: Specify performance expectations for computationally intensive features. + +--- + +## Security Patterns + +### Input Validation + +**Strict Validation**: +```typescript +- Validate all user inputs +- Whitelist allowed values +- Sanitize before use +- Validate types and ranges +- Reject invalid input immediately +``` + +### Authentication & Authorization + +**Defense in Depth**: +```typescript +- Verify authentication at every endpoint +- Check authorization before all operations +- Don't trust client-side validation +- Log all security-relevant events +- Use parameterized queries (SQL injection) +- Escape outputs (XSS prevention) +``` + +**When to apply**: Always apply in production code; specify level for prototypes. + +--- + +## Commit & Change Patterns + +### Commit Size + +**Atomic Commits** - One logical change per commit: +``` +✓ "Add user email validation" +✓ "Fix off-by-one error in pagination" +✗ "Add feature, fix bugs, refactor utilities" +``` + +**Feature Commits** - Complete features per commit: +``` +✓ "Implement user registration flow" +✓ "Add payment processing module" +``` + +**When to apply**: Specify commit granularity expectations. + +--- + +### Change Scope + +**Surgical Changes** - Minimal modifications only: +``` +- Change only files necessary for the feature +- Don't refactor unrelated code +- Don't fix unrelated bugs +- Don't update formatting in unchanged code +- One concern per pull request +``` + +**Opportunistic Improvements**: +``` +- Fix obvious bugs you encounter +- Update related documentation +- Refactor code you're modifying +- Improve tests for affected code +``` + +**When to apply**: Default to surgical for VibeScript; specify if broader changes allowed. + +--- + +## Code Review Patterns + +### Review Readiness + +**Pre-Review Checklist**: +``` +- [ ] All tests pass +- [ ] Code follows style guide +- [ ] No commented-out code +- [ ] No debug logging +- [ ] Documentation updated +- [ ] Commit messages clear +- [ ] VibeScript checks pass +``` + +--- + +## Mix & Match Templates + +### Template: Strict & Safe +``` +"Claude, use these patterns: +- YAGNI: Strict +- DRY: Moderate +- Testing: Strict TDD +- Error Handling: Fail-fast +- Documentation: Full JSDoc +- Changes: Surgical only +- Security: Defense in depth" +``` + +### Template: Move Fast +``` +"Claude, use these patterns: +- YAGNI: Moderate +- DRY: Relaxed +- Testing: Critical-path only +- Error Handling: Graceful degradation +- Documentation: Self-documenting code +- Changes: Feature commits +- Performance: Don't optimize early" +``` + +### Template: Production Ready +``` +"Claude, use these patterns: +- YAGNI: Moderate +- DRY: Moderate +- SOLID: Pragmatic +- Testing: High coverage (80%+) +- Error Handling: Fail-fast at boundaries +- Documentation: JSDoc for public APIs +- Security: Strict validation +- Changes: Atomic commits" +``` + +### Template: Prototype/MVP +``` +"Claude, use these patterns: +- YAGNI: Strict (no speculation) +- DRY: Relaxed (optimize for speed) +- Testing: Smoke tests only +- Error Handling: Basic try-catch +- Documentation: Inline comments only +- Changes: Feature commits +- Performance: Premature optimization forbidden" +``` + +--- + +## Custom Pattern Definition + +Create your own patterns: + +``` +"Claude, for this project: + +Code Style: +- Use functional programming style +- Prefer immutability +- Use pipe operators for transforms + +Architecture: +- Hexagonal architecture pattern +- Domain at core, adapters at edges +- No business logic in controllers + +Testing: +- Contract testing for APIs +- Property-based testing for algorithms +- Integration tests for user flows + +When uncertain: +- Ask before abstracting +- Prefer explicit over clever +- Choose readability over brevity" +``` + +--- + +## VibeScript Integration + +**Important**: These patterns work *within* VibeScript's governance framework: + +- VibeScript controls **what** and **where** you can modify +- These patterns control **how** you write the code +- Both must be satisfied + +**Example Task**: +``` +"Claude, implement user authentication using: +- VibeScript governance (read .vibe/claude.instructions.md) +- Development patterns: Production Ready template +- Create .vibe.ts files with all directives +- Follow SOLID pragmatic approach +- Write tests first (TDD) +- Document all public APIs with JSDoc" +``` + +--- + +## Anti-Patterns to Avoid + +Unless explicitly permitted, avoid: + +- ❌ **Premature abstraction** - Wait for third use case +- ❌ **God objects** - Classes with too many responsibilities +- ❌ **Magic numbers** - Use named constants +- ❌ **Copy-paste programming** - Extract to functions +- ❌ **Shotgun surgery** - Changes scattered across many files +- ❌ **Yo-yo problem** - Deep inheritance chains +- ❌ **Golden hammer** - Using same solution for everything +- ❌ **Not invented here** - Use existing libraries +- ❌ **Reinventing the wheel** - Don't rewrite standard functionality +- ❌ **Analysis paralysis** - Perfect is the enemy of done + +--- + +## Pattern Selection Guide + +**Choose patterns based on**: + +1. **Project Phase**: + - Prototype: Relaxed patterns, move fast + - MVP: Moderate patterns, balance speed and quality + - Production: Strict patterns, prioritize reliability + - Maintenance: Surgical changes, high test coverage + +2. **Team Size**: + - Solo: Fewer constraints, optimize for personal preference + - Small team: Moderate structure, some flexibility + - Large team: Strict patterns, enforce consistency + +3. **Domain Criticality**: + - Experimental: Relaxed patterns + - Business logic: Moderate to strict + - Financial/medical: Strictest patterns, full testing + - Infrastructure: Strict, high reliability + +4. **Technical Debt Status**: + - Green field: Establish patterns from start + - Legacy with debt: Surgical changes, gradual improvement + - Well-maintained: Match existing patterns + +--- + +## For Future Claude Instances + +**Self-Specification**: When starting a new project, you can define patterns for future instances: + +```markdown +# Project Development Patterns + +Based on my experience with this codebase, I recommend: + +**Patterns That Worked**: +- YAGNI Strict: Kept codebase focused +- DRY Moderate: Good balance of reuse and clarity +- Test-After Development: Team preference +- JSDoc for public APIs only: Sufficient documentation + +**Patterns to Avoid**: +- Don't extract utilities until third use +- Don't add abstractions in the auth module (already complex) +- Keep database queries in repositories only + +**Project-Specific Rules**: +- All API routes must have integration tests +- All external calls must have retry logic +- Configuration must be in config/ folder +``` + +Save this as `.vibe/development-patterns.md` for the project. + +--- + +## Quick Reference Card + +| Pattern | Strict | Moderate | Relaxed | +|---------|--------|----------|---------| +| **YAGNI** | Only requested | Reasonable extension points | Design for roadmap | +| **DRY** | No duplication | Extract at 3+ uses | Optimize for clarity | +| **Testing** | TDD, 80%+ coverage | Test-after, 60%+ | Smoke tests | +| **Docs** | Full JSDoc | Public APIs only | Self-documenting | +| **Error** | Fail-fast | Graceful degradation | Basic try-catch | +| **Commits** | Atomic | Feature-based | As needed | + +--- + +## Conclusion + +This recipe provides a menu of proven development patterns. Mix and match to create the perfect instructions for your project's needs. Remember: + +- **VibeScript** enforces governance and safety +- **These patterns** guide implementation style +- **Together** they create high-quality, maintainable AI-assisted code + +When in doubt, ask your human collaborators which patterns they prefer. Every team has preferences, and these patterns adapt to your workflow. + +--- + +**Version**: 1.0.0 +**Last Updated**: 2026-01-23 +**Maintained By**: VibeScript Team diff --git a/docs/tasking-claude.md b/docs/tasking-claude.md new file mode 100644 index 0000000..2991bac --- /dev/null +++ b/docs/tasking-claude.md @@ -0,0 +1,406 @@ +# Quick Start: Tasking Claude with Development Patterns + +This guide shows you how to use the development patterns recipe when assigning tasks to Claude in VibeScript projects. + +--- + +## The Basics + +**VibeScript** provides governance (what files can be modified, what directives are required). + +**Development Patterns** provide coding philosophy (how to write the code, what principles to follow). + +Together, they create consistent, high-quality AI-assisted development. + +--- + +## Quick Tasking Templates + +Copy and customize these templates when assigning work to Claude: + +### Template 1: Quick Task (Use Built-in Defaults) + +``` +Claude, implement {{FEATURE_NAME}}: + +1. Follow VibeScript governance (read .vibe/claude.instructions.md) +2. Use the "Production Ready" pattern from docs/development-patterns.md +3. Create tests before implementation (TDD) +4. Document all public APIs with JSDoc + +Acceptance criteria: +- {{CRITERIA_1}} +- {{CRITERIA_2}} +- {{CRITERIA_3}} +``` + +### Template 2: Custom Pattern Mix + +``` +Claude, implement {{FEATURE_NAME}} using: + +Patterns from docs/development-patterns.md: +- YAGNI: Strict (only what's requested) +- DRY: Moderate (extract at 3rd use) +- Testing: Test-After with 70% coverage +- Documentation: Self-documenting code + README +- Error Handling: Fail-fast at boundaries +- Commits: Atomic + +VibeScript: Follow all governance rules in .vibe/ + +Specific requirements: +- {{REQUIREMENT_1}} +- {{REQUIREMENT_2}} +``` + +### Template 3: Use Project Context File + +``` +Claude, implement {{FEATURE_NAME}}: + +1. Read .vibe/claude-context.md for this project's patterns +2. Follow VibeScript governance rules +3. Ask before deviating from established patterns + +The feature should: +- {{SPECIFICATION_1}} +- {{SPECIFICATION_2}} +``` + +### Template 4: Ad-hoc Simple Task + +``` +Claude: +- Fix bug in {{FILE_NAME}} +- Use Surgical change scope (minimal modifications) +- Follow existing code style +- Add regression test +- VibeScript: Create .vibe.ts file if needed +``` + +### Template 5: Greenfield Feature + +``` +Claude, create {{NEW_FEATURE}} from scratch: + +Use "Move Fast" template from docs/development-patterns.md: +- YAGNI: Moderate +- Testing: Critical-path only +- Documentation: Inline comments +- Commits: Feature-based + +Architecture: +- {{ARCHITECTURE_DECISION_1}} +- {{ARCHITECTURE_DECISION_2}} + +VibeScript: Create .vibe.ts files with all directives +``` + +--- + +## Pre-Made Pattern Bundles + +Reference these bundles from `docs/development-patterns.md`: + +### "Strict & Safe" +Best for: Production features, financial/medical systems, critical infrastructure +``` +Use patterns: Strict YAGNI, Moderate DRY, Strict TDD, Full JSDoc, +Fail-fast errors, Defense in depth security, Surgical changes +``` + +### "Production Ready" +Best for: Standard production features, most business logic +``` +Use patterns: Moderate YAGNI, Moderate DRY, Pragmatic SOLID, +High test coverage (80%+), JSDoc for public APIs, Atomic commits +``` + +### "Move Fast" +Best for: MVPs, prototypes, internal tools +``` +Use patterns: Moderate YAGNI, Relaxed DRY, Critical-path testing, +Self-documenting code, Feature commits +``` + +### "Prototype/MVP" +Best for: Proof of concepts, demos, throwaway code +``` +Use patterns: Strict YAGNI, Relaxed DRY, Smoke tests only, +Inline comments, No premature optimization +``` + +--- + +## Step-by-Step: Setting Up a New Project + +1. **Install VibeScript** in your project: + ```bash + pnpm add -D @ddnet-repo/vibescript + pnpm vibescript init + ``` + +2. **Choose your development patterns**: + - Review `docs/development-patterns.md` + - Select patterns that match your team's philosophy + - Consider project phase and criticality + +3. **Create project context** (optional but recommended): + - Copy `.vibe/templates/claude-context.md.template` + - Fill in your selected patterns + - Save as `.vibe/claude-context.md` + +4. **Task Claude**: + ``` + Claude, I've set up VibeScript with custom patterns. + + Read: + - .vibe/claude.instructions.md (governance rules) + - .vibe/claude-context.md (development patterns) + + Then implement user authentication. + ``` + +5. **Iterate and refine**: + - Update `.vibe/claude-context.md` as you learn what works + - Add project-specific rules and constraints + - Document things to avoid + +--- + +## Common Scenarios + +### Scenario 1: New Team Member (Human or AI) + +``` +Welcome! This project uses VibeScript for governance. + +Quick orientation: +1. Read .vibe/spec.md (5 min) - Full governance spec +2. Read .vibe/claude.instructions.md (3 min) - Your operating manual +3. Read .vibe/claude-context.md (2 min) - Project patterns +4. Read docs/development-patterns.md (scan, 5 min) - Pattern reference + +When tasked, follow the patterns in claude-context.md. +``` + +### Scenario 2: Changing Project Phase + +**From Prototype to Production**: +``` +Claude, the project is moving from prototype to production. + +Update development patterns: +- Change: YAGNI from Relaxed to Moderate +- Change: Testing from Smoke to High coverage (80%+) +- Change: Documentation from Inline to Full JSDoc +- Add: Strict input validation +- Add: Defense in depth security + +Apply these patterns to all new code. +Update .vibe/claude-context.md to reflect changes. +``` + +### Scenario 3: Refactoring Legacy Code + +``` +Claude, refactor the {{MODULE_NAME}} module: + +Special instructions: +- Use Surgical change scope (minimal modifications) +- Match existing code patterns (even if not ideal) +- Add tests before refactoring (safety net) +- One module at a time +- Each refactor must pass all existing tests + +Don't: +- Change APIs or interfaces +- Modify other modules +- Add new features while refactoring +``` + +### Scenario 4: Hotfix Production Bug + +``` +Claude, urgent bug fix needed: + +Bug: {{BUG_DESCRIPTION}} + +Requirements: +- MINIMAL changes only (surgical scope) +- Add regression test +- NO refactoring, NO improvements +- Fix ONLY the reported bug +- Atomic commit +- Full test suite must pass + +Patterns: Fastest path to fix while maintaining safety +``` + +--- + +## Mixing Patterns Effectively + +You can mix different pattern levels for different aspects: + +**Example: Balanced Approach** +``` +YAGNI: Strict (no speculation) ++ DRY: Moderate (some abstraction) ++ Testing: High coverage (80%+) ++ Documentation: Public APIs only += Fast but safe development +``` + +**Example: Experimental Feature** +``` +YAGNI: Moderate (design for known next steps) ++ DRY: Relaxed (optimize for learning) ++ Testing: Critical-path (main flows only) ++ Documentation: README-driven += Rapid experimentation with minimal overhead +``` + +**Example: Critical Infrastructure** +``` +YAGNI: Strict (no future-proofing) ++ DRY: Strict (eliminate duplication) ++ Testing: Full TDD with 100% coverage ++ Documentation: Full JSDoc + architecture docs ++ Security: Defense in depth += Maximum safety and maintainability +``` + +--- + +## Pattern Anti-Combinations + +Some pattern combinations don't work well: + +❌ **Strict YAGNI + Strict DRY**: Contradictory (YAGNI says don't abstract, DRY says eliminate duplication) + - Better: Strict YAGNI + Moderate DRY + +❌ **Relaxed patterns + High-risk domain**: Dangerous (insufficient safety) + - Better: Use Strict/Moderate for financial, medical, auth code + +❌ **Strict TDD + Move Fast**: Contradictory goals + - Better: Test-After or Critical-Path testing for speed + +❌ **Minimal documentation + Complex algorithms**: Hard to maintain + - Better: Document complex logic even if rest is self-documenting + +--- + +## Troubleshooting + +### "Claude is over-engineering solutions" +→ Specify: `Strict YAGNI, Surgical changes, only implement what's requested` + +### "Claude's code is hard to understand" +→ Specify: `Verbose naming, Full JSDoc, Explain complex logic with comments` + +### "Claude isn't writing tests" +→ Specify: `Strict TDD, Write failing test first, 80%+ coverage required` + +### "Claude is modifying too many files" +→ Specify: `Surgical change scope, Atomic commits, Touch only files listed` + +### "Code is duplicated everywhere" +→ Specify: `Moderate DRY, Extract at 3rd use, Create utility modules` + +### "Changes break existing features" +→ Specify: `Full test suite must pass, Add regression tests, Integration tests` + +--- + +## For Claude: Understanding Pattern Priorities + +When patterns conflict, use this priority: + +1. **VibeScript governance** (highest priority - file ownership, directives) +2. **Security patterns** (strict validation, defense in depth) +3. **Explicit user instructions** (what the user specifically requested) +4. **Project context patterns** (from .vibe/claude-context.md) +5. **Development pattern defaults** (from docs/development-patterns.md) +6. **Your best judgment** (lowest priority - only when no guidance given) + +When uncertain, ask. Don't guess. + +--- + +## Creating a Team Pattern Guide + +Share this template with your team: + +```markdown +# Our Team's Development Patterns + +## Default Patterns for New Features +- YAGNI: Moderate +- DRY: Moderate +- Testing: Test-After, 70% coverage +- Docs: JSDoc for public APIs +- Commits: Atomic + +## When to Deviate +- Use Strict YAGNI for customer-facing features +- Use High Coverage (80%+) for payment/auth code +- Use Relaxed patterns for internal tools + +## Project-Specific Rules +- [Your custom rules here] + +## When Tasking Claude +Copy this: "Claude, use our team patterns from [link to this doc]" +``` + +--- + +## Further Reading + +- **Full Pattern Reference**: `docs/development-patterns.md` +- **VibeScript Governance**: `.vibe/spec.md` +- **Claude Instructions**: `.vibe/claude.instructions.md` +- **Template Customization**: `.vibe/templates/claude-context.md.template` + +--- + +## Quick Decision Tree + +``` +┌─ What am I building? ─────────────────────────┐ +│ │ +├─ Prototype/POC ────────► Use "Move Fast" │ +├─ MVP ──────────────────► Use "Moderate" mix │ +├─ Production feature ───► Use "Production Ready"│ +├─ Critical system ─────► Use "Strict & Safe" │ +└───────────────────────────────────────────────┘ + +┌─ What's the risk? ────────────────────────────┐ +│ │ +├─ Low (internal tool) ──► Relaxed patterns │ +├─ Medium (standard) ────► Moderate patterns │ +├─ High (user-facing) ───► Strict patterns │ +├─ Critical (money/data)─► Strictest patterns │ +└───────────────────────────────────────────────┘ + +┌─ How fast do I need to move? ────────────────┐ +│ │ +├─ Very fast (demo) ─────► Minimal tests/docs │ +├─ Fast (sprint) ────────► Pragmatic coverage │ +├─ Normal (feature) ─────► Standard patterns │ +├─ Careful (migration) ──► Full TDD, high cov │ +└───────────────────────────────────────────────┘ +``` + +Choose patterns based on where you land in these categories. + +--- + +**Quick Start Complete!** + +You now have everything needed to task Claude with consistent, project-appropriate development patterns. Start with the pre-made bundles and customize as you learn what works for your team. + +**Version**: 1.0.0 +**Last Updated**: 2026-01-23 From 90a8ce901c9ee42c814bf64a741c9f91f54a100b Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 23 Jan 2026 21:37:25 +0000 Subject: [PATCH 3/5] Add practical example for development patterns setup Co-authored-by: burtbyproxy <1827866+burtbyproxy@users.noreply.github.com> --- docs/example-setup.md | 377 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 377 insertions(+) create mode 100644 docs/example-setup.md diff --git a/docs/example-setup.md b/docs/example-setup.md new file mode 100644 index 0000000..b0686ff --- /dev/null +++ b/docs/example-setup.md @@ -0,0 +1,377 @@ +# Example: Setting Up Development Patterns for Your Project + +This example demonstrates how to use the development patterns recipe in a real-world VibeScript project. + +--- + +## Scenario + +You're building an e-commerce API with the following requirements: +- **Phase**: Production-ready +- **Team**: 3 developers + AI assistance +- **Criticality**: High (handles payments) +- **Tech**: Node.js, TypeScript, PostgreSQL, Express + +--- + +## Step 1: Install VibeScript + +```bash +pnpm add -D @ddnet-repo/vibescript +pnpm vibescript init +``` + +This creates: +- `.vibe/` directory with governance files +- `.vibe/claude.instructions.md` - Operating rules for Claude +- `.vibe/spec.md` - Complete VibeScript specification + +--- + +## Step 2: Choose Development Patterns + +Review `docs/development-patterns.md` and select patterns for your team: + +**Selected Patterns for E-Commerce API:** +- **YAGNI**: Moderate (plan for known features, not speculation) +- **DRY**: Moderate (extract at 3rd use) +- **SOLID**: Pragmatic (apply where it adds value) +- **Testing**: TDD with 80% coverage (high-value code) +- **Documentation**: JSDoc for public APIs +- **Error Handling**: Fail-fast at boundaries, graceful internally +- **Security**: Defense in depth +- **Commits**: Atomic + +--- + +## Step 3: Create Your Project Context + +Copy and customize the template: + +```bash +cp .vibe/templates/claude-context.md.template .vibe/claude-context.md +``` + +**Filled Example** (`.vibe/claude-context.md`): + +```markdown +# E-Commerce API Development Context + +## Quick Instructions +Claude, use: Moderate YAGNI, Moderate DRY, TDD with 80% coverage, +JSDoc for public APIs, Fail-fast at boundaries, Atomic commits + +## Custom Rules +- All database queries must use the repository pattern +- API responses must follow JSON:API specification +- All external API calls require retry logic with exponential backoff +- Use Zod for runtime input validation +- No business logic in controllers (must be in services) +- All async operations must have proper error handling +- Use functional programming style where appropriate + +## Architecture Constraints +- Hexagonal architecture: domain at core, adapters at edges +- Database schema changes require migration files +- All secrets in environment variables (never hardcoded) +- External dependencies must be mockable for testing +- Rate limiting on all public endpoints + +## Must Avoid +- ❌ Don't use `any` type in TypeScript +- ❌ Don't query database directly from controllers +- ❌ Don't add npm packages without checking vulnerabilities +- ❌ Don't expose internal error details to clients +- ❌ Don't skip input validation + +## Project-Specific Vocabulary +- **SKU**: Stock Keeping Unit, unique product identifier +- **Cart**: Shopping cart stored in Redis with 24hr TTL +- **Fulfillment**: Order packing and shipping process +- **Inventory Reserve**: Temporary hold on stock during checkout + +## Security Requirements +- Strict input validation using Zod schemas +- Parameterized queries (prevent SQL injection) +- Rate limiting and request throttling +- Authentication on all endpoints except public health check +- Authorization checks before all data access +- Audit logging for sensitive operations (payments, user data changes) + +## Testing Requirements +- Write tests before implementation (TDD) +- 80%+ code coverage for services and repositories +- 100% coverage for payment and auth modules +- Integration tests for all API endpoints +- Unit tests must be fast (<100ms each) +- Mock external services (payment gateway, email, etc.) + +## VibeScript Compliance +Read .vibe/claude.instructions.md and follow all governance rules. +Create .vibe.ts files with all required directives. +Run vibe:check before committing. +``` + +--- + +## Step 4: Task Claude with Context + +Now when you assign work to Claude, reference the context: + +### Example Task 1: New Feature + +``` +Claude, implement user registration with email verification: + +1. Read .vibe/claude-context.md for project patterns +2. Follow VibeScript governance (.vibe/claude.instructions.md) + +Requirements: +- POST /api/users endpoint +- Validate email format and uniqueness +- Hash passwords with bcrypt +- Send verification email +- Return JWT on successful registration + +Acceptance Criteria: +- All inputs validated with Zod +- TDD approach (write tests first) +- 80%+ code coverage +- Integration test for full flow +- Error handling for duplicate emails +- Audit logging for new registrations +``` + +### Example Task 2: Bug Fix + +``` +Claude, fix the cart expiration bug: + +Context: .vibe/claude-context.md (Surgical changes mode) + +Bug: Carts aren't expiring after 24 hours in Redis + +Requirements: +- Minimal changes only +- Add regression test +- Fix only the reported issue +- No refactoring +- Full test suite must pass + +Follow project patterns for error handling and testing. +``` + +### Example Task 3: Refactoring + +``` +Claude, refactor the payment service: + +1. Read .vibe/claude-context.md +2. Use TDD approach (tests first for safety) +3. Apply Moderate DRY (extract repeated logic) + +Goals: +- Extract duplicate Stripe API code +- Improve error handling consistency +- Add retry logic for failed transactions +- Maintain 100% test coverage + +Constraints: +- Don't change payment APIs or interfaces +- One service at a time +- All existing tests must pass +``` + +--- + +## Step 5: Monitor and Adjust + +After a few tasks, review what's working: + +**What Worked Well:** +- ✅ TDD caught bugs early +- ✅ Moderate YAGNI kept codebase focused +- ✅ Zod validation prevented bad data + +**Adjustments Needed:** +- 📝 Add pattern: All errors must include correlation IDs +- 📝 Update: Increase test coverage to 85% for new code +- 📝 Add: Require performance tests for endpoints handling >1000 req/min + +Update `.vibe/claude-context.md` with these learnings. + +--- + +## Step 6: Onboard New Team Members + +Share your context with new developers (human or AI): + +``` +Welcome to the E-Commerce API project! + +Setup: +1. Clone repo +2. Read docs/development-patterns.md (10 min) +3. Read .vibe/claude-context.md (5 min) +4. Read .vibe/claude.instructions.md (5 min) + +When working with Claude: +"Claude, read .vibe/claude-context.md and implement [feature]" + +Our patterns are documented and Claude will follow them consistently. +``` + +--- + +## Real Task Example + +Here's what a complete task looks like: + +``` +Claude, implement shopping cart abandonment notifications: + +## Context +- Read .vibe/claude-context.md for project patterns +- Follow VibeScript governance rules +- This is a production feature (moderate risk) + +## Requirements +POST endpoint to send cart reminder emails after 2 hours + +## Specifications +1. Background job checks for carts abandoned >2 hours +2. Send email with cart contents and checkout link +3. Mark cart as "reminder sent" (send only once) +4. Log all email attempts for debugging + +## Acceptance Criteria +- [ ] TDD approach (tests first) +- [ ] Zod validation for all inputs +- [ ] Repository pattern for data access +- [ ] Retry logic for email service failures +- [ ] 80%+ code coverage +- [ ] Integration test with mocked email service +- [ ] Error handling for all edge cases +- [ ] Audit log for privacy compliance + +## Out of Scope +- Don't add cart analytics (separate feature) +- Don't modify cart expiration logic +- Don't change email templates (use existing) + +## VibeScript +- Create .vibe.ts files with all directives +- Declare all touched files in @vibe:touch +- Run vibe:check before committing +``` + +**Claude's Response:** + +Claude will: +1. Read the project context +2. Apply Moderate YAGNI (implement only what's requested) +3. Write tests first (TDD) +4. Use repository pattern (project convention) +5. Add Zod validation (project requirement) +6. Implement retry logic (project standard) +7. Achieve 80%+ coverage (project threshold) +8. Create proper VibeScript directives +9. Use atomic commits + +The result: consistent, high-quality code that matches your team's standards. + +--- + +## Common Patterns Usage + +### Pattern: Quick Bug Fix +``` +Claude: +- Context: .vibe/claude-context.md (Surgical changes) +- Fix bug in src/cart/redis.service.ts +- Add regression test +- Minimal changes only +``` + +### Pattern: New Module +``` +Claude: +- Context: .vibe/claude-context.md (Full patterns) +- Create inventory management module +- Follow hexagonal architecture +- TDD with 80% coverage +- JSDoc for all public APIs +``` + +### Pattern: Security Enhancement +``` +Claude: +- Context: .vibe/claude-context.md (Security: Defense in Depth) +- Add rate limiting to /api/checkout +- Implement sliding window algorithm +- Test under load +- Add monitoring metrics +``` + +--- + +## Benefits Achieved + +**Consistency**: All code follows same patterns, whether written by humans or AI + +**Quality**: High standards enforced automatically (TDD, coverage, validation) + +**Onboarding**: New team members reference same docs as AI + +**Evolution**: Update patterns in one place, all future work adapts + +**Audit Trail**: VibeScript tracks what was changed and why + +**Safety**: Multiple layers prevent accidental breaking changes + +--- + +## Advanced: Pattern Evolution + +As your project matures, update patterns: + +```markdown +# .vibe/claude-context.md + +## Phase: Production → Maintenance + +**Updated Patterns (2026-02-01):** +- Changed: YAGNI from Moderate → Strict (codebase is stable) +- Changed: Testing from TDD → Test-After (faster iterations) +- Changed: Coverage from 80% → 70% (focus on critical paths) +- Added: Performance testing for high-traffic endpoints +- Added: Database query optimization review + +**New Constraints:** +- All DB queries must use indexes +- Cache frequently accessed data (Redis) +- Monitor P95 latency for all endpoints + +**Project Maturity Notes:** +Architecture is stable. Focus on performance and stability over new features. +``` + +Update tasks to reference the new patterns automatically. + +--- + +## Conclusion + +This example demonstrates: +1. How to set up development patterns for a real project +2. How to task Claude with consistent expectations +3. How to evolve patterns as your project matures +4. How patterns and VibeScript work together + +Result: **Consistent, maintainable, high-quality AI-assisted development**. + +--- + +**Created**: 2026-01-23 +**Project**: VibeScript Examples +**Type**: Complete Tutorial From b6cdac5968bb9fbbc3a511374681c94900864ef3 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 23 Jan 2026 21:38:31 +0000 Subject: [PATCH 4/5] Add quick reference card for development patterns Co-authored-by: burtbyproxy <1827866+burtbyproxy@users.noreply.github.com> --- README.md | 2 + docs/patterns-quick-reference.md | 249 +++++++++++++++++++++++++++++++ 2 files changed, 251 insertions(+) create mode 100644 docs/patterns-quick-reference.md diff --git a/README.md b/README.md index ef20d90..70a35be 100644 --- a/README.md +++ b/README.md @@ -257,8 +257,10 @@ VibeScript tells Claude **what** and **where** it can modify. But you might also We've created a comprehensive recipe of development patterns (YAGNI, DRY, SOLID, testing strategies, etc.) that you can mix and match when tasking Claude: +- **[Quick Reference Card](docs/patterns-quick-reference.md)** - Print-friendly cheat sheet for tasking Claude - **[Development Patterns Reference](docs/development-patterns.md)** - Complete guide to common patterns with strict/moderate/relaxed levels - **[Tasking Claude Guide](docs/tasking-claude.md)** - Quick start templates for assigning work to Claude +- **[Example Setup](docs/example-setup.md)** - Real-world example of setting up patterns for an e-commerce API - **[Claude Context Template](.vibe/templates/claude-context.md.template)** - Customizable template for your project's patterns **Example usage:** diff --git a/docs/patterns-quick-reference.md b/docs/patterns-quick-reference.md new file mode 100644 index 0000000..bfaf022 --- /dev/null +++ b/docs/patterns-quick-reference.md @@ -0,0 +1,249 @@ +# Development Patterns Quick Reference Card + +**Keep this handy when tasking Claude!** + +--- + +## Quick Command Templates + +### Instant Task (Use Defaults) +``` +Claude, implement {{FEATURE}} following "Production Ready" +patterns from docs/development-patterns.md +``` + +### Custom Mix +``` +Claude, implement {{FEATURE}} using: +- {{YAGNI_LEVEL}} YAGNI +- {{DRY_LEVEL}} DRY +- Testing: {{TEST_APPROACH}} +- Docs: {{DOC_LEVEL}} +``` + +### Project Context +``` +Claude, read .vibe/claude-context.md and implement {{FEATURE}} +``` + +--- + +## Pattern Levels Quick Picker + +### YAGNI +- **Strict**: Only what's requested, zero speculation +- **Moderate**: Room for obvious extensions +- **Relaxed**: Design for known roadmap + +### DRY +- **Strict**: Extract all duplication +- **Moderate**: Extract at 3+ uses +- **Relaxed**: Optimize for clarity over reuse + +### Testing +- **TDD**: Tests first, 80%+ coverage +- **Test-After**: Implement then test, 60%+ +- **Critical-Path**: Main flows only, smoke tests + +### Documentation +- **Full**: JSDoc everywhere +- **Public APIs**: Document interfaces only +- **Self-Doc**: Clear code + inline comments + +### Error Handling +- **Fail-Fast**: Validate early, throw on invalid +- **Graceful**: Try/catch, degrade functionality +- **Result Types**: Explicit success/failure objects + +### Commits +- **Atomic**: One logical change per commit +- **Feature**: Complete features per commit +- **As Needed**: Flexible commit strategy + +--- + +## Pre-Made Bundles + +### "Strict & Safe" → Critical Systems +``` +Strict YAGNI + Moderate DRY + TDD + Full Docs + Fail-Fast + Defense in Depth +Use for: Finance, Medical, Auth, Infrastructure +``` + +### "Production Ready" → Standard Features +``` +Moderate YAGNI + Moderate DRY + Pragmatic SOLID + High Coverage + Public API Docs +Use for: Most production features +``` + +### "Move Fast" → MVPs & Prototypes +``` +Moderate YAGNI + Relaxed DRY + Critical-Path Tests + Self-Doc Code +Use for: MVPs, Internal Tools, Demos +``` + +### "Prototype/MVP" → Throwaway Code +``` +Strict YAGNI + Relaxed DRY + Smoke Tests + Inline Comments +Use for: POCs, Experiments, Learning +``` + +--- + +## Pattern Selection Grid + +| Project Phase | Risk Level | Speed Need | Recommended Bundle | +|--------------|------------|------------|-------------------| +| Prototype | Low | Very Fast | Prototype/MVP | +| MVP | Low-Med | Fast | Move Fast | +| Production | Medium | Normal | Production Ready | +| Critical | High | Careful | Strict & Safe | +| Maintenance | Varies | Normal | Surgical + Existing patterns | + +--- + +## Troubleshooting Quick Fix + +| Problem | Solution Pattern | +|---------|-----------------| +| Claude over-engineers | → Strict YAGNI + Surgical changes | +| Hard to understand code | → Verbose naming + Full docs | +| Not writing tests | → Specify TDD + Coverage % | +| Too many file changes | → Surgical scope + Atomic commits | +| Code duplication | → Moderate DRY + Extract at 3rd use | +| Breaking existing features | → High test coverage + Integration tests | + +--- + +## Anti-Patterns Warning ⚠️ + +**Never combine:** +- ❌ Strict YAGNI + Strict DRY (contradictory) +- ❌ Relaxed patterns + High-risk domain (dangerous) +- ❌ Strict TDD + Move Fast (conflicts) +- ❌ Minimal docs + Complex algorithms (unmaintainable) + +--- + +## Priority Order (When Patterns Conflict) + +1. **VibeScript governance** (file ownership, directives) +2. **Security patterns** (validation, auth) +3. **User's explicit instructions** +4. **Project context** (.vibe/claude-context.md) +5. **Pattern defaults** (docs/development-patterns.md) +6. **Claude's judgment** (last resort) + +--- + +## Essential Files Checklist + +- [ ] `.vibe/claude.instructions.md` - VibeScript governance +- [ ] `docs/development-patterns.md` - Pattern reference +- [ ] `docs/tasking-claude.md` - Quick start guide +- [ ] `.vibe/claude-context.md` - Your project's patterns (optional but recommended) + +--- + +## One-Liner Examples + +**Quick bug fix:** +``` +Claude: Fix bug in {{FILE}}, Surgical changes, Add test +``` + +**New feature:** +``` +Claude: Build {{FEATURE}} using Production Ready patterns +``` + +**Refactor:** +``` +Claude: Refactor {{MODULE}}, Moderate DRY, TDD for safety, Match existing style +``` + +**Hotfix:** +``` +Claude: URGENT fix {{BUG}}, Minimal changes only, Full tests +``` + +**Prototype:** +``` +Claude: Prototype {{IDEA}}, Move Fast patterns, Smoke tests only +``` + +--- + +## Copy-Paste Templates + +### Template A: Standard Task +``` +Claude, implement {{FEATURE_NAME}}: + +Patterns: Production Ready (docs/development-patterns.md) +- Moderate YAGNI +- Moderate DRY +- TDD with 80% coverage +- JSDoc for public APIs + +Requirements: +- {{REQ_1}} +- {{REQ_2}} + +VibeScript: Follow .vibe/claude.instructions.md +``` + +### Template B: High-Risk Feature +``` +Claude, implement {{CRITICAL_FEATURE}}: + +Patterns: Strict & Safe (docs/development-patterns.md) +- Strict YAGNI +- Strict validation +- TDD with 100% coverage +- Full documentation +- Defense in depth security + +This is {{CRITICAL_DOMAIN}} code - maximum safety. + +VibeScript: Follow all governance rules. +``` + +### Template C: Quick Prototype +``` +Claude: + +Prototype {{IDEA}} using Move Fast patterns. +- Moderate YAGNI +- Critical-path tests only +- Self-documenting code +- One commit + +Show me if it works, we'll polish later. +``` + +--- + +## URLs for Reference + +- Full Patterns: `docs/development-patterns.md` +- Quick Start: `docs/tasking-claude.md` +- Example Setup: `docs/example-setup.md` +- Project Template: `.vibe/templates/claude-context.md.template` + +--- + +## Remember + +**VibeScript** = What & Where (governance) +**Patterns** = How (code style & quality) +**Together** = Consistent AI-assisted development + +When uncertain: **Ask, don't guess** + +--- + +**Print this page and keep it by your keyboard!** + +**Version**: 1.0.0 +**Updated**: 2026-01-23 From 0dbb4af2030d9b40f62e12ec8574bcf7c8aadf4e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 23 Jan 2026 22:56:22 +0000 Subject: [PATCH 5/5] Update documentation to include 5 new production directives from main branch Co-authored-by: burtbyproxy <1827866+burtbyproxy@users.noreply.github.com> --- .vibe/templates/claude-context.md.template | 11 +- docs/development-patterns.md | 135 +++++++++++++++++++++ docs/example-setup.md | 1 + docs/patterns-quick-reference.md | 9 ++ docs/tasking-claude.md | 9 ++ 5 files changed, 164 insertions(+), 1 deletion(-) diff --git a/.vibe/templates/claude-context.md.template b/.vibe/templates/claude-context.md.template index ff8dbe2..87ac777 100644 --- a/.vibe/templates/claude-context.md.template +++ b/.vibe/templates/claude-context.md.template @@ -104,11 +104,13 @@ VibeScript governance is `[ ] Enabled [ ] Disabled` for this project. If enabled, Claude must: 1. Read `.vibe/claude.instructions.md` before making changes -2. Create `.vibe.*` files with all required directives +2. Create `.vibe.*` files with all 13 required directives (goal, touch, inputs, outputs, constraints, tests, risk, rollback, security, performance, dependencies, observability, breaking) 3. Declare all touched files in `@vibe:touch` directives 4. Run `vibe:check` and `vibe:guard` before committing 5. Follow file ownership rules +**Note**: VibeScript now requires 5 additional production-focused directives. See `docs/development-patterns.md` for guidance on how to fill these out at different pattern levels. + --- ## Quick Reference @@ -152,6 +154,13 @@ Here's an example of how to fill this template: - ✓ Size: Atomic - ✓ Scope: Surgical +**Production Directives**: +- ✓ Security: Defense in depth - validate all inputs, require auth, prevent injection +- ✓ Performance: Document complexity and scale requirements +- ✓ Dependencies: List all external services and version requirements +- ✓ Observability: Include logging, metrics, and traces for debugging +- ✓ Breaking: Explicitly state breaking changes or "none" + ### Custom Instructions ``` - All database queries must use the repository pattern diff --git a/docs/development-patterns.md b/docs/development-patterns.md index b7f3c8d..cf6e626 100644 --- a/docs/development-patterns.md +++ b/docs/development-patterns.md @@ -626,6 +626,141 @@ When uncertain: --- +## Production-Focused Directives + +VibeScript now requires 13 directives (previously 8). The 5 new production-focused directives help prevent shipping code that works but has hidden problems. When applying development patterns, these directives ensure you consider critical production concerns: + +### @vibe:security - Security Implications + +Document security considerations aligned with your security patterns: + +**Defense in Depth** (Strict): +```typescript +// @vibe:security Validates all input with Zod schema, requires Bearer token auth with role-based access control, SQL injection prevented via parameterized queries, rate-limited at 100 req/min per IP, credentials never logged, HTTPS only +``` + +**Standard Checks** (Moderate): +```typescript +// @vibe:security Validates input, requires authentication, uses parameterized queries, rate-limited +``` + +**Basic** (Relaxed): +```typescript +// @vibe:security none - pure calculation function, no user input or external data +``` + +### @vibe:performance - Performance Characteristics + +Document performance aligned with your optimization patterns: + +**Performance-Critical**: +```typescript +// @vibe:performance O(log n) binary search with B-tree index, < 10ms p99 latency target, handles 50k req/sec, memory-mapped for large datasets +``` + +**Proactive Performance**: +```typescript +// @vibe:performance O(n) single pass, Redis cache with 5min TTL, paginated results (50 per page), indexed database queries +``` + +**Avoid Premature Optimization**: +```typescript +// @vibe:performance O(n) iteration, adequate for expected dataset size (< 1000 items) +// @vibe:performance none - called infrequently (< 10/day), negligible impact +``` + +### @vibe:dependencies - External Dependencies + +Document dependencies aligned with your architecture: + +**Production Ready**: +```typescript +// @vibe:dependencies Redis 6.0+ for rate limiting, PostgreSQL 13+ with pg_trgm extension, @auth/core@^2.1.0, requires network access for OAuth callbacks, fallback to in-memory cache if Redis unavailable +``` + +**Move Fast**: +```typescript +// @vibe:dependencies PostgreSQL, axios@^1.0.0 +``` + +**Pure/Isolated**: +```typescript +// @vibe:dependencies none - pure TypeScript, no external services +``` + +### @vibe:observability - Monitoring & Debugging + +Document observability aligned with your debugging strategy: + +**High Observability**: +```typescript +// @vibe:observability Structured logging with request_id/user_id/trace_id, emits auth_duration_ms and auth_failure_count metrics, exports traces to Jaeger, logs all errors with stack traces, adds X-Trace-Id to response headers +``` + +**Standard Monitoring**: +```typescript +// @vibe:observability Logs errors with context, emits duration_ms metric, includes trace_id +``` + +**Deterministic Functions**: +```typescript +// @vibe:observability none - pure function, deterministic output, nothing to monitor +``` + +### @vibe:breaking - Breaking Changes + +Document breaking changes for API stability: + +**Backward Compatible**: +```typescript +// @vibe:breaking none - new functionality, backward compatible +// @vibe:breaking none - internal implementation change, same interface +``` + +**Has Breaking Changes**: +```typescript +// @vibe:breaking Renamed getUserById() to getUser(), removed deprecated legacy_auth field from User type, changed error status from 401 to 403 for insufficient permissions +// @vibe:breaking Changed function signature: added required 'options' parameter, removed 'callback' (use Promise instead) +``` + +### Pattern Integration Examples + +**"Strict & Safe" with New Directives**: +```typescript +// @vibe:goal Validate and process payment transaction +// @vibe:touch src/payment/*.ts +// @vibe:inputs PaymentRequest with amount, currency, customer_id +// @vibe:outputs PaymentResult with transaction_id or error +// @vibe:constraints Amount must be > 0, currency in [USD, EUR, GBP] +// @vibe:tests payment.test.ts with 100% coverage including fraud scenarios +// @vibe:risk high +// @vibe:rollback Revert commit, transactions are idempotent +// @vibe:security Validates amount/currency format, requires authenticated customer, PCI-compliant via Stripe API, no card data stored locally, rate-limited at 10 payments/min per customer +// @vibe:performance O(1) API call, 200ms p99 latency, handles 1000 concurrent transactions +// @vibe:dependencies Stripe API v2023-10-16, PostgreSQL for transaction log, Redis for idempotency keys (24hr TTL) +// @vibe:observability Logs all payment attempts with customer_id/amount/status, emits payment_duration_ms and payment_failure_count metrics, traces enabled, alerts on failure rate > 5% +// @vibe:breaking none - new payment method, existing methods unchanged +``` + +**"Move Fast" with New Directives**: +```typescript +// @vibe:goal Add user profile avatar upload +// @vibe:touch src/profile/*.ts +// @vibe:inputs File upload (< 5MB), user_id +// @vibe:outputs Avatar URL +// @vibe:constraints JPEG/PNG only, max 5MB +// @vibe:tests Upload test with valid/invalid files +// @vibe:risk low +// @vibe:rollback Delete uploaded files, revert commit +// @vibe:security Validates file type and size, requires authentication, scans for malware via ClamAV +// @vibe:performance Uploads to S3, async processing, < 2sec for typical images +// @vibe:dependencies AWS S3, ClamAV daemon, sharp@^0.32.0 for image processing +// @vibe:observability Logs upload attempts and failures, emits upload_duration_ms metric +// @vibe:breaking none - new feature +``` + +--- + ## Anti-Patterns to Avoid Unless explicitly permitted, avoid: diff --git a/docs/example-setup.md b/docs/example-setup.md index b0686ff..21d78a2 100644 --- a/docs/example-setup.md +++ b/docs/example-setup.md @@ -253,6 +253,7 @@ POST endpoint to send cart reminder emails after 2 hours - [ ] Integration test with mocked email service - [ ] Error handling for all edge cases - [ ] Audit log for privacy compliance +- [ ] All 13 VibeScript directives completed (including security, performance, dependencies, observability, breaking) ## Out of Scope - Don't add cart analytics (separate feature) diff --git a/docs/patterns-quick-reference.md b/docs/patterns-quick-reference.md index bfaf022..2535625 100644 --- a/docs/patterns-quick-reference.md +++ b/docs/patterns-quick-reference.md @@ -2,6 +2,8 @@ **Keep this handy when tasking Claude!** +**Note**: VibeScript now requires 13 directives (up from 8). The 5 new production-focused directives are: security, performance, dependencies, observability, breaking. See full guide for examples at each pattern level. + --- ## Quick Command Templates @@ -60,6 +62,13 @@ Claude, read .vibe/claude-context.md and implement {{FEATURE}} - **Feature**: Complete features per commit - **As Needed**: Flexible commit strategy +### New: Production Directives +- **Security**: Document auth, validation, vulnerabilities +- **Performance**: Document complexity, scale, latency +- **Dependencies**: Document external services, versions +- **Observability**: Document logging, metrics, traces +- **Breaking**: Document API/interface changes + --- ## Pre-Made Bundles diff --git a/docs/tasking-claude.md b/docs/tasking-claude.md index 2991bac..c85a8f8 100644 --- a/docs/tasking-claude.md +++ b/docs/tasking-claude.md @@ -12,6 +12,15 @@ This guide shows you how to use the development patterns recipe when assigning t Together, they create consistent, high-quality AI-assisted development. +**Important Update**: VibeScript now requires 13 directives (up from 8), including 5 new production-focused directives: +- `@vibe:security` - Security implications and mitigations +- `@vibe:performance` - Performance characteristics and scale requirements +- `@vibe:dependencies` - External services and version requirements +- `@vibe:observability` - How to monitor and debug in production +- `@vibe:breaking` - Breaking changes to APIs or interfaces + +When tasking Claude, these directives ensure production concerns are documented upfront. See `docs/development-patterns.md` for examples of how to fill these out at different pattern levels (strict/moderate/relaxed). + --- ## Quick Tasking Templates