Content is user-generated and unverified.
#!/bin/bash # Claude Code Development Workflow Setup Script # This script initializes all custom commands for your development workflow set -e echo "🚀 Setting up Claude Code Development Workflow Agents..." # Create directory structure echo "📁 Creating directory structure..." mkdir -p .claude/commands mkdir -p .claude/templates mkdir -p .claude/workflows mkdir -p analysis mkdir -p stories mkdir -p design/lld mkdir -p reviews mkdir -p src mkdir -p tests mkdir -p e2e-tests mkdir -p reports mkdir -p docs mkdir -p standards # Create PRD Analyzer Command echo "📝 Creating PRD Analyzer command..." cat > .claude/commands/analyze-prd.md << 'EOF' --- name: analyze-prd description: Analyze Product Requirements Document against existing codebase parameters: - name: prd description: Path to PRD document default: ./docs/prd.md - name: codebase description: Path to codebase default: ./src - name: output description: Output path for analysis default: ./analysis/prd-analysis.md --- You are a Senior Business Analyst specializing in requirements analysis. Your task is to analyze the Product Requirements Document and create a comprehensive analysis report. ## Instructions 1. **Read and Parse the PRD** - Location: `{prd}` - Extract all functional requirements - Extract all non-functional requirements - Identify user stories and acceptance criteria - Note any ambiguities or unclear requirements 2. **Analyze Existing Codebase** - Location: `{codebase}` - Map existing implementations to requirements - Identify which requirements are fully implemented - Find partially implemented requirements - List completely missing features 3. **Create Requirements Traceability Matrix** ```markdown | Requirement ID | Description | Status | Implementation Location | Notes | |----------------|-------------|---------|------------------------|--------| | REQ-001 | User Login | Partial | /src/auth/login.ts | Missing 2FA | ``` 4. **Gap Analysis** - List all unimplemented requirements - Prioritize by business impact - Estimate implementation effort (T-shirt sizes: S, M, L, XL) 5. **Generate Clarifying Questions** Categorize questions as: - **Technical**: Implementation details, integrations - **Business**: Logic, rules, edge cases - **UX/UI**: User experience, design specifics - **Performance**: Scale, response times, load 6. **Risk Assessment** - Technical risks - Timeline risks - Resource risks - Integration risks ## Output Format Save the analysis to `{output}` with this structure: ```markdown # PRD Analysis Report ## Executive Summary [Brief overview of findings] ## Requirements Coverage [Table showing implementation status] ## Gap Analysis [Detailed list of missing features] ## Risk Assessment [Identified risks and mitigation strategies] ## Questions for Product Team ### High Priority [Critical clarifications needed] ### Medium Priority [Important but not blocking] ### Low Priority [Nice to have clarifications] ## Recommendations [Next steps and suggestions] ## Appendices ### A. Detailed Requirements Mapping ### B. Technical Debt Identified ### C. Suggested Architecture Changes ``` Please proceed with the analysis. EOF # Create Requirements Validator Command echo "✅ Creating Requirements Validator command..." cat > .claude/commands/validate-requirements.md << 'EOF' --- name: validate-requirements description: Validate and decompose requirements into manageable user stories parameters: - name: input description: Path to requirements or PRD analysis default: ./analysis/prd-analysis.md - name: output description: Output directory for user stories default: ./stories --- You are a Requirements Engineer expert in breaking down complex requirements into actionable user stories. ## Your Tasks 1. **Validate Requirements Against SMART Criteria** - **S**pecific: Is it clear and unambiguous? - **M**easurable: Can we verify when it's done? - **A**chievable: Is it technically feasible? - **R**elevant: Does it align with project goals? - **T**ime-bound: Is there a clear timeline? 2. **Decomposition Strategy Selection** Choose the most appropriate strategy: - **Functional Decomposition**: For feature-heavy requirements - **Layered Approach**: For architectural requirements - **User Journey Based**: For UX-focused requirements - **Data Flow Based**: For data processing requirements - **Risk-Based**: For high-risk or critical requirements 3. **Create User Stories** For each requirement, create stories following this template: ``` As a [user type] I want to [action/feature] So that [benefit/value] Acceptance Criteria: - [ ] Criterion 1 - [ ] Criterion 2 - [ ] Criterion 3 Technical Notes: - Implementation considerations - Dependencies - Constraints Story Points: [1-13] Priority: [High/Medium/Low] ``` 4. **Complexity Estimation** - Story Points: 1, 2, 3, 5, 8, 13 - T-shirt sizes: XS, S, M, L, XL - Include justification for estimates 5. **Dependency Mapping** Create a dependency graph showing story relationships 6. **Output Structure** Create separate files in `{output}` directory: - `epic-001-user-authentication.md` - `epic-002-data-management.md` - `story-map.md` (visual story map) - `dependencies.md` (dependency graph) Please read the requirements from `{input}` and create the user stories. EOF # Create Technical Design Command echo "🏗️ Creating Technical Design command..." cat > .claude/commands/design-architecture.md << 'EOF' --- name: design-architecture description: Create technical architecture and design documents parameters: - name: stories description: Path to user stories default: ./stories - name: constraints description: Path to technical constraints file default: ./docs/constraints.md - name: output description: Output directory for design docs default: ./design --- You are a Senior Software Architect designing a robust, scalable system. ## Design Process 1. **Analyze Requirements** - Read all user stories from `{stories}` - Understand functional requirements - Extract non-functional requirements - Review technical constraints from `{constraints}` 2. **Architecture Design Decisions** Consider and document decisions for: - **Architecture Style**: Microservices vs Monolithic vs Serverless - **Communication**: REST vs GraphQL vs gRPC vs Events - **Data Storage**: SQL vs NoSQL, partitioning strategy - **Caching**: Redis vs Memcached, caching layers - **Security**: Authentication, authorization, encryption - **Scalability**: Horizontal vs vertical, auto-scaling - **Deployment**: Containers vs VMs, orchestration 3. **Create Architecture Documents** ### High-Level Design (HLD) Save to `{output}/hld.md`: - System overview - Component architecture (C4 Level 1 & 2) - Data flow diagrams - Integration points - Technology stack decisions Use mermaid diagrams: ```mermaid graph TB subgraph "Frontend" UI[React UI] Mobile[Mobile App] end subgraph "API Gateway" GW[Kong/Nginx] end subgraph "Services" Auth[Auth Service] User[User Service] Data[Data Service] end subgraph "Data Layer" PG[(PostgreSQL)] Redis[(Redis)] S3[S3 Storage] end UI --> GW Mobile --> GW GW --> Auth GW --> User GW --> Data Auth --> Redis User --> PG Data --> PG Data --> S3 ``` ### Low-Level Design (LLD) For each service, create `{output}/lld/[service-name].md`: - Class diagrams - Sequence diagrams - Database schemas - API specifications - Error handling flows ### Technical Requirements Document (TRD) Save to `{output}/trd.md`: - Technical specifications - Performance requirements - Security requirements - Infrastructure requirements - Monitoring and observability 4. **API Design** Create OpenAPI specification at `{output}/api-spec.yml` Please proceed with the architecture design. EOF # Create Architecture Review Command echo "🔍 Creating Architecture Review command..." cat > .claude/commands/review-architecture.md << 'EOF' --- name: review-architecture description: Review and validate technical architecture parameters: - name: design description: Path to design documents default: ./design - name: standards description: Path to architecture standards default: ./standards/architecture.md - name: output description: Output path for review report default: ./reviews/architecture-review.md --- You are a Principal Architect conducting a thorough architecture review. ## Review Checklist 1. **Architecture Principles** - [ ] SOLID principles adherence - [ ] DRY (Don't Repeat Yourself) - [ ] KISS (Keep It Simple, Stupid) - [ ] YAGNI (You Aren't Gonna Need It) - [ ] Separation of Concerns 2. **Non-Functional Requirements** - [ ] **Performance**: Response times < 200ms, throughput > 1000 req/s - [ ] **Scalability**: Can handle 10x current load? - [ ] **Security**: OWASP Top 10, encryption at rest/transit - [ ] **Reliability**: 99.9% uptime, fault tolerance - [ ] **Maintainability**: Complexity metrics, documentation - [ ] **Observability**: Logging, monitoring, distributed tracing 3. **Technical Evaluation** - Technology choices appropriateness - Integration complexity - Data consistency approach - Error handling strategy - Testing strategy 4. **Risk Assessment** Rate each risk as: Critical/High/Medium/Low - Single points of failure - Performance bottlenecks - Security vulnerabilities - Scalability limits - Technical debt - Vendor lock-in 5. **Cost Analysis** - Infrastructure costs (monthly estimate) - Licensing costs - Operational costs - Development effort (person-months) ## Review Output Format Create review report at `{output}`: ```markdown # Architecture Review Report ## Summary - Review Date: [Date] - Reviewer: Architecture Review Agent - Decision: [Approved/Needs Revision/Rejected] ## Findings by Severity ### 🔴 Critical (Must Fix) [Issues that block approval] ### 🟡 High (Should Fix) [Important improvements needed] ### 🟢 Medium (Consider Fixing) [Recommended enhancements] ### 🔵 Low (Nice to Have) [Minor suggestions] ## Detailed Analysis ### Architecture Principles [Assessment of each principle] ### Non-Functional Requirements [Evaluation of each NFR] ### Technical Design [Review of design decisions] ### Risk Assessment [Detailed risk analysis] ### Cost Analysis [Breakdown of estimated costs] ## Recommendations 1. [Specific actionable item] 2. [Specific actionable item] 3. [Specific actionable item] ## Approval Checklist - [ ] All critical issues resolved - [ ] Security review passed - [ ] Performance targets achievable - [ ] Cost within budget - [ ] Team has required skills ## Next Steps [Actions required before/after approval] ``` Please review the architecture in `{design}`. EOF # Create TDD Developer Command echo "💻 Creating TDD Developer command..." cat > .claude/commands/implement-tdd.md << 'EOF' --- name: implement-tdd description: Implement features using Test-Driven Development parameters: - name: story description: User story file to implement default: ./stories/current-story.md - name: language description: Programming language default: typescript - name: framework description: Test framework default: jest - name: output description: Output directory for code default: ./src --- You are a Senior Developer practicing strict Test-Driven Development. ## TDD Process Follow the Red-Green-Refactor cycle: ### 1. 🔴 Red: Write Failing Tests First Read the user story from `{story}` and create comprehensive tests: ```{language} // tests/[feature].test.{language} describe('[Feature Name]', () => { describe('[Scenario]', () => { it('should [expected behavior]', async () => { // Arrange const input = {...}; // Act const result = await functionUnderTest(input); // Assert expect(result).toEqual(expectedOutput); }); it('should handle error case', async () => { // Test error scenarios }); it('should validate input', async () => { // Test input validation }); }); }); ``` Include: - Positive test cases (happy path) - Negative test cases (error handling) - Edge cases (boundaries, nulls, empty) - Integration tests ### 2. 🟢 Green: Write Minimal Code Implement just enough code to make tests pass: - Start with the simplest implementation - Don't add features not required by tests - Focus on making tests green ### 3. 🔵 Refactor: Improve Code Quality Once tests pass, refactor for: - Remove duplication (DRY) - Improve naming - Extract methods/classes - Apply design patterns - Optimize performance - Add helpful comments ## Definition of Done - [ ] All tests passing - [ ] Code coverage > 80% - [ ] No linting errors - [ ] Code reviewed - [ ] Documentation updated - [ ] Performance benchmarks met - [ ] Security scan passed - [ ] Integration tests written - [ ] API documentation updated - [ ] Error handling complete - [ ] Logging implemented ## Code Quality Standards ```{language} // Follow these standards: // - SOLID principles // - Maximum function length: 20 lines // - Maximum file length: 200 lines // - Cyclomatic complexity < 10 // - Clear, self-documenting code // - Meaningful variable/function names // - Proper error handling // - Comprehensive logging ``` ## Output Structure Create files in the following structure: ``` {output}/ ├── services/ │ └── [feature].service.{language} ├── controllers/ │ └── [feature].controller.{language} ├── models/ │ └── [feature].model.{language} ├── utils/ │ └── [feature].utils.{language} └── types/ └── [feature].types.{language} tests/ ├── unit/ │ └── [feature].test.{language} ├── integration/ │ └── [feature].integration.test.{language} └── fixtures/ └── [feature].fixtures.{language} ``` Please implement the story following strict TDD practices. EOF # Create Code Review Command echo "👀 Creating Code Review command..." cat > .claude/commands/review-code.md << 'EOF' --- name: review-code description: Perform comprehensive code review parameters: - name: path description: Path to code to review default: ./src - name: pr description: Pull request number (optional) - name: output description: Output path for review default: ./reviews/code-review.md --- You are a Senior Software Engineer conducting a thorough code review. ## Review Areas ### 1. Code Quality 📝 - **Readability**: Clear variable/function names, appropriate comments - **Maintainability**: DRY principle, modular design, single responsibility - **Complexity**: Functions under 20 lines, cyclomatic complexity < 10 - **Standards**: Follows language idioms and team conventions - **Documentation**: JSDoc/comments for public APIs ### 2. Security 🔒 - [ ] Input validation (never trust user input) - [ ] SQL injection prevention (parameterized queries) - [ ] XSS protection (output encoding) - [ ] Authentication/authorization checks - [ ] Sensitive data handling (no logs, encryption) - [ ] Dependency vulnerabilities (npm audit) - [ ] CSRF protection - [ ] Rate limiting implementation ### 3. Performance ⚡ - [ ] Algorithm efficiency (Big O analysis) - [ ] Database query optimization (N+1 problems) - [ ] Caching implementation - [ ] Memory management (leaks, large objects) - [ ] Async operations handling - [ ] Resource pooling - [ ] Lazy loading where appropriate ### 4. Testing 🧪 - [ ] Test coverage adequacy (>80%) - [ ] Test quality and meaningful assertions - [ ] Edge cases covered - [ ] Mocks used appropriately - [ ] Integration tests present - [ ] Test data isolation - [ ] Performance tests for critical paths ### 5. Architecture Compliance 🏛️ - [ ] Follows defined patterns (MVC, Repository, etc.) - [ ] Respects layer boundaries - [ ] Proper dependency injection - [ ] No circular dependencies - [ ] Interface segregation - [ ] Proper error propagation ## Review Process 1. **Static Analysis** - Run linters and code analyzers - Check for common anti-patterns - Verify coding standards 2. **Logic Review** - Verify business logic correctness - Check edge case handling - Validate algorithm choices 3. **Security Scan** - Look for OWASP Top 10 issues - Check authentication/authorization - Review data validation 4. **Performance Check** - Identify potential bottlenecks - Review database queries - Check for memory leaks ## Review Output Format Create report at `{output}`: ```markdown # Code Review Report ## Overview - Reviewer: Code Review Agent - Date: [Current Date] - Files Reviewed: [count] - Lines of Code: [count] - Test Coverage: [percentage] - Overall Status: [Approved/Needs Changes/Rejected] ## Summary | Severity | Count | Status | |----------|-------|--------| | 🔴 Critical | 0 | Must fix before merge | | 🟡 High | 2 | Should fix | | 🟢 Medium | 5 | Consider fixing | | 🔵 Low | 8 | Nice to have | ## Issues by File ### `src/services/auth.service.ts` **Line 45** - 🔴 **Critical: SQL Injection Vulnerability** ```typescript // Current (Vulnerable) const query = `SELECT * FROM users WHERE username = '${username}'`; // Suggested Fix const query = 'SELECT * FROM users WHERE username = ?'; const result = await db.query(query, [username]); ``` **Impact**: Allows attackers to execute arbitrary SQL **References**: [OWASP SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection) **Line 67-89** - 🟡 **High: Performance Issue** ```typescript // Current (O(n²) complexity) for (const user of users) { for (const permission of permissions) { // ... } } // Suggested Fix (O(n) complexity) const permissionMap = new Map(permissions.map(p => [p.id, p])); for (const user of users) { const permission = permissionMap.get(user.permissionId); // ... } ``` ### `src/controllers/user.controller.ts` **Line 23** - 🟢 **Medium: Missing Error Handling** ```typescript // Add try-catch block try { const user = await userService.create(userData); return res.status(201).json(user); } catch (error) { logger.error('User creation failed:', error); return res.status(500).json({ error: 'Internal server error' }); } ``` ## Good Practices Observed ✅ - Consistent code formatting - Good test coverage in most modules - Proper use of TypeScript types - Clear separation of concerns ## Recommendations 1. **Immediate Actions** - Fix SQL injection vulnerability in auth.service.ts - Add input validation middleware 2. **Short-term Improvements** - Optimize nested loops in permission checking - Add comprehensive error handling 3. **Long-term Considerations** - Consider implementing caching layer - Add performance monitoring ## Checklist for Approval - [ ] All critical issues resolved - [ ] High priority issues addressed or ticketed - [ ] Tests updated for changes - [ ] Documentation updated - [ ] No new linting errors ``` Please review the code at `{path}` and generate the detailed report. EOF # Create E2E Testing Command echo "🧪 Creating E2E Testing command..." cat > .claude/commands/test-e2e.md << 'EOF' --- name: test-e2e description: Create and run end-to-end tests parameters: - name: stories description: Path to user stories default: ./stories - name: env description: Test environment default: staging - name: framework description: E2E test framework default: cypress - name: output description: Output directory for tests default: ./e2e-tests --- You are a Senior QA Automation Engineer creating comprehensive E2E tests. ## Test Strategy ### 1. Test Scenario Generation From each user story in `{stories}`, create: - Happy path scenarios (primary user flows) - Alternative paths (secondary flows) - Error scenarios (validation, errors) - Edge cases (boundaries, limits) - Cross-functional scenarios ### 2. Test Implementation Structure #### API Tests ```javascript // {output}/api/[feature].spec.js describe('API: [Feature Name]', () => { const baseUrl = Cypress.env('apiUrl'); beforeEach(() => { // Setup test data cy.task('db:seed'); }); afterEach(() => { // Cleanup cy.task('db:clean'); }); describe('POST /api/[resource]', () => { it('should create resource with valid data', () => { cy.request({ method: 'POST', url: `${baseUrl}/api/resource`, headers: { 'Authorization': `Bearer ${Cypress.env('authToken')}` }, body: { name: 'Test Resource', type: 'test' } }).then((response) => { expect(response.status).to.eq(201); expect(response.body).to.have.property('id'); expect(response.body.name).to.eq('Test Resource'); }); }); it('should validate required fields', () => { cy.request({ method: 'POST', url: `${baseUrl}/api/resource`, failOnStatusCode: false, body: {} }).then((response) => { expect(response.status).to.eq(400); expect(response.body.errors).to.include('name is required'); }); }); }); }); ``` #### UI Tests ```javascript // {output}/ui/[feature].spec.js describe('UI: [Feature Name]', () => { beforeEach(() => { cy.visit('/'); cy.login(); // Custom command }); describe('User Flow: [Flow Name]', () => { it('should complete full user journey', () => { // Navigate to feature cy.get('[data-cy=nav-feature]').click(); cy.url().should('include', '/feature'); // Interact with UI cy.get('[data-cy=input-name]').type('Test Name'); cy.get('[data-cy=select-type]').select('Type A'); cy.get('[data-cy=submit-button]').click(); // Verify results cy.get('[data-cy=success-message]') .should('be.visible') .and('contain', 'Successfully created'); // Verify data persistence cy.reload(); cy.get('[data-cy=item-list]').should('contain', 'Test Name'); }); it('should handle errors gracefully', () => { // Simulate network error cy.intercept('POST', '/api/resource', { statusCode: 500, body: { error: 'Server error' } }).as('createError'); cy.get('[data-cy=submit-button]').click(); cy.wait('@createError'); cy.get('[data-cy=error-message]') .should('be.visible') .and('contain', 'Something went wrong'); }); }); }); ``` ### 3. Test Categories #### Functional Tests - Feature functionality verification - Business logic validation - User workflow completion - Data integrity checks #### Performance Tests ```javascript // {output}/performance/load.spec.js it('should load page within 3 seconds', () => { cy.visit('/', { onBeforeLoad: (win) => { win.performance.mark('start'); }, onLoad: (win) => { win.performance.mark('end'); win.performance.measure('pageLoad', 'start', 'end'); const measure = win.performance.getEntriesByName('pageLoad')[0]; expect(measure.duration).to.be.lessThan(3000); } }); }); ``` #### Security Tests - Authentication verification - Authorization checks - Input sanitization - XSS prevention - CSRF protection #### Accessibility Tests ```javascript // {output}/accessibility/a11y.spec.js it('should be accessible', () => { cy.visit('/'); cy.injectAxe(); cy.checkA11y(null, { rules: { 'color-contrast': { enabled: true }, 'valid-lang': { enabled: true } } }); }); ``` ### 4. Test Data Management ```javascript // {output}/fixtures/users.json { "validUser": { "email": "test@example.com", "password": "Test123!", "name": "Test User" }, "adminUser": { "email": "admin@example.com", "password": "Admin123!", "name": "Admin User", "role": "admin" } } ``` ### 5. Custom Commands ```javascript // {output}/support/commands.js Cypress.Commands.add('login', (userType = 'validUser') => { cy.fixture('users').then((users) => { const user = users[userType]; cy.request('POST', '/api/auth/login', user).then((response) => { window.localStorage.setItem('authToken', response.body.token); }); }); }); ``` ### 6. Test Reports Generate comprehensive test report at `{output}/reports/e2e-report.md`: ```markdown # E2E Test Report ## Test Execution Summary - Total Tests: [count] - Passed: [count] ✅ - Failed: [count] ❌ - Skipped: [count] ⏭️ - Duration: [time] ## Test Coverage by Feature | Feature | Tests | Pass Rate | Notes | |---------|-------|-----------|-------| | Authentication | 15 | 100% | All scenarios covered | | User Management | 23 | 95.6% | 1 flaky test | ## Failed Tests [Details of any failures] ## Performance Metrics - Average page load: 1.8s - API response time (p95): 180ms - Largest Contentful Paint: 2.1s ## Recommendations [Suggestions for improvement] ``` Please create comprehensive E2E tests based on the user stories. EOF # Create Configuration File echo "⚙️ Creating configuration file..." cat > .claude/config.json << 'EOF' { "project": "Development Workflow Agents", "version": "1.0.0", "commands": { "searchPaths": [".claude/commands"], "aliases": { "prd": "analyze-prd", "req": "validate-requirements", "arch": "design-architecture", "review-arch": "review-architecture", "dev": "implement-tdd", "review": "review-code", "test": "test-e2e" } }, "workflows": { "full-cycle": { "description": "Complete development cycle from PRD to testing", "steps": [ { "command": "analyze-prd", "description": "Analyze product requirements", "continueOnError": false }, { "command": "validate-requirements", "description": "Validate and decompose requirements", "continueOnError": false }, { "command": "design-architecture", "description": "Create technical design", "continueOnError": false }, { "command": "review-architecture", "description": "Review architecture design", "continueOnError": false, "requiresApproval": true }, { "command": "implement-tdd", "description": "Implement using TDD", "continueOnError": false }, { "command": "review-code", "description": "Review implementation", "continueOnError": false }, { "command": "test-e2e", "description": "Run E2E tests", "continueOnError": true } ] }, "quick-review": { "description": "Quick code review workflow", "steps": [ { "command": "review-code", "parameters": { "path": "./src" } }, { "command": "test-e2e", "parameters": { "framework": "jest" } } ] } }, "defaults": { "language": "typescript", "testFramework": "jest", "e2eFramework": "cypress", "outputFormat": "markdown", "codeQuality": { "maxFunctionLength": 20, "maxFileLength": 200, "minTestCoverage": 80, "maxCyclomaticComplexity": 10 } }, "integrations": { "confluence": { "enabled": false, "baseUrl": "https://your-domain.atlassian.net/wiki", "space": "DEV" }, "jira": { "enabled": false, "baseUrl": "https://your-domain.atlassian.net", "project": "PROJ" }, "github": { "enabled": true, "autoCreatePR": false } } } EOF # Create sample templates echo "📄 Creating templates..." mkdir -p .claude/templates cat > .claude/templates/user-story.md << 'EOF' # User Story: [Feature Name] ## Story As a [user type] I want to [action/feature] So that [benefit/value] ## Acceptance Criteria - [ ] Given [context], when [action], then [outcome] - [ ] Given [context], when [action], then [outcome] - [ ] Given [context], when [action], then [outcome] ## Technical Notes - Implementation considerations - API endpoints needed - Database changes - Dependencies ## Definition of Done - [ ] Code complete and reviewed - [ ] Unit tests written and passing - [ ] Integration tests complete - [ ] Documentation updated - [ ] Deployed to staging - [ ] Acceptance criteria verified ## Story Points: [1-13] ## Priority: [High/Medium/Low] ## Sprint: [Sprint number] EOF cat > .claude/templates/test-case.md << 'EOF' # Test Case: [Test Name] ## Test Information - **ID**: TC-[number] - **Feature**: [Feature name] - **Type**: [Unit/Integration/E2E] - **Priority**: [High/Medium/Low] ## Prerequisites - [Required setup] - [Test data needed] ## Test Steps 1. [Action] - Expected: [Result] 2. [Action] - Expected: [Result] 3. [Action] - Expected: [Result] ## Test Data ```json { "input": {}, "expected": {} } ``` ## Cleanup - [Cleanup steps] EOF # Create sample files echo "📋 Creating sample files..." cat > ./docs/prd.md << 'EOF' # Product Requirements Document ## Project: User Management System ### Overview Build a comprehensive user management system with authentication, authorization, and profile management. ### Functional Requirements #### FR1: User Registration - Users can register with email and password - Email verification required - Password strength requirements enforced #### FR2: User Authentication - Login with email/password - Support for 2FA - Password reset functionality #### FR3: User Profiles - Users can update profile information - Profile picture upload - Privacy settings ### Non-Functional Requirements #### NFR1: Performance - Page load time < 3 seconds - API response time < 200ms #### NFR2: Security - HTTPS everywhere - Encrypted password storage - OWASP Top 10 compliance #### NFR3: Scalability - Support 10,000 concurrent users - Horizontal scaling capability EOF cat > ./docs/constraints.md << 'EOF' # Technical Constraints ## Technology Stack - Backend: Node.js with TypeScript - Frontend: React with TypeScript - Database: PostgreSQL - Cache: Redis - Cloud: AWS ## Compliance Requirements - GDPR compliance - SOC 2 Type II - HIPAA ready ## Performance Constraints - 99.9% uptime SLA - < 200ms API response time - < 3s page load time ## Security Constraints - All data encrypted at rest - TLS 1.3 minimum - Regular security audits EOF cat > ./standards/architecture.md << 'EOF' # Architecture Standards ## Design Principles 1. **Microservices Architecture** - Service boundaries by business domain - Independent deployment - API-first design 2. **Security First** - Zero trust architecture - Defense in depth - Principle of least privilege 3. **Cloud Native** - Container-based deployment - Kubernetes orchestration - 12-factor app principles ## Code Standards - TypeScript for type safety - ESLint + Prettier for formatting - Jest for testing - 80% minimum code coverage ## API Standards - RESTful design - OpenAPI 3.0 specification - Versioning via URL path - Standard HTTP status codes ## Database Standards - Migrations for schema changes - Read replicas for scaling - Regular backups - Connection pooling EOF # Create workflow execution script echo "🔄 Creating workflow execution script..." cat > ./claude-workflow.sh << 'EOF' #!/bin/bash # Claude Code Workflow Executor set -e echo "🚀 Claude Code Development Workflow" echo "==================================" # Function to run command and check status run_command() { local cmd=$1 local desc=$2 echo "" echo "▶️ $desc" echo "Running: claude-code $cmd" if claude-code $cmd; then echo "✅ $desc completed successfully" return 0 else echo "❌ $desc failed" return 1 fi } # Function to ask for continuation ask_continue() { read -p "Continue to next step? (y/n) " -n 1 -r echo if [[ ! $REPLY =~ ^[Yy]$ ]]; then echo "Workflow paused. You can resume by running individual commands." exit 0 fi } # Main workflow echo "Starting full development cycle workflow..." # Step 1: PRD Analysis run_command "analyze-prd" "PRD Analysis" ask_continue # Step 2: Requirements Validation run_command "validate-requirements" "Requirements Validation and Decomposition" ask_continue # Step 3: Technical Design run_command "design-architecture" "Technical Architecture Design" ask_continue # Step 4: Architecture Review run_command "review-architecture" "Architecture Review" echo "⚠️ Architecture review requires approval before proceeding." ask_continue # Step 5: TDD Implementation echo "Select a story to implement:" ls ./stories/*.md 2>/dev/null || echo "No stories found" read -p "Enter story filename: " story_file run_command "implement-tdd --story ./stories/$story_file" "TDD Implementation" ask_continue # Step 6: Code Review run_command "review-code" "Code Review" ask_continue # Step 7: E2E Testing run_command "test-e2e" "End-to-End Testing" echo "" echo "✅ Workflow completed!" echo "" echo "📊 Generated Artifacts:" echo " - PRD Analysis: ./analysis/prd-analysis.md" echo " - User Stories: ./stories/" echo " - Architecture: ./design/" echo " - Code: ./src/" echo " - Tests: ./tests/ and ./e2e-tests/" echo " - Reviews: ./reviews/" EOF chmod +x ./claude-workflow.sh # Create README echo "📚 Creating README..." cat > ./README-CLAUDE-WORKFLOW.md << 'EOF' # Claude Code Development Workflow This project uses Claude Code custom commands to implement a complete development workflow from requirements to testing. ## Setup 1. Ensure Claude Code is installed 2. Run the setup script: `./setup-claude-workflow.sh` 3. Customize `.claude/config.json` for your project ## Available Commands ### Individual Commands - `claude-code analyze-prd` - Analyze product requirements - `claude-code validate-requirements` - Validate and decompose requirements - `claude-code design-architecture` - Create technical design - `claude-code review-architecture` - Review architecture - `claude-code implement-tdd` - Implement using TDD - `claude-code review-code` - Perform code review - `claude-code test-e2e` - Run E2E tests ### Aliases (shortcuts) - `claude-code prd` - Same as analyze-prd - `claude-code req` - Same as validate-requirements - `claude-code arch` - Same as design-architecture - `claude-code dev` - Same as implement-tdd - `claude-code review` - Same as review-code - `claude-code test` - Same as test-e2e ### Workflows - `claude-code workflow full-cycle` - Run complete development cycle - `claude-code workflow quick-review` - Quick review workflow ## Interactive Workflow Run `./claude-workflow.sh` for an interactive workflow with prompts between steps. ## Directory Structure ``` .claude/ ├── commands/ # Command definitions ├── templates/ # Reusable templates └── config.json # Configuration Project outputs: ├── analysis/ # PRD analysis results ├── stories/ # User stories ├── design/ # Architecture documents ├── src/ # Implementation code ├── tests/ # Unit/integration tests ├── e2e-tests/ # End-to-end tests ├── reviews/ # Review reports └── reports/ # Test reports ``` ## Customization 1. Edit commands in `.claude/commands/` to match your workflow 2. Update `.claude/config.json` for project-specific settings 3. Add custom templates to `.claude/templates/` ## Tips - Commands accept parameters: `claude-code analyze-prd --prd ./specs/new-prd.md` - View command help: `claude-code help [command-name]` - List all commands: `claude-code list-commands` - Chain commands: `claude-code prd && claude-code req && claude-code arch` ## Integration Configure integrations in `.claude/config.json`: - Confluence for documentation - JIRA for issue tracking - GitHub for version control ## Support For issues or questions: 1. Check command output for detailed error messages 2. Review generated artifacts for insights 3. Modify commands as needed for your use case EOF echo "" echo "✅ Setup complete!" echo "" echo "🎉 Your Claude Code Development Workflow is ready!" echo "" echo "📖 Quick Start:" echo " 1. Review/edit the sample PRD: ./docs/prd.md" echo " 2. Run your first command: claude-code analyze-prd" echo " 3. Or run the full workflow: ./claude-workflow.sh" echo "" echo "📚 For more info, see: ./README-CLAUDE-WORKFLOW.md" echo "" echo "💡 Tips:" echo " - Use 'claude-code help [command]' to see command details" echo " - Commands are in .claude/commands/ - customize them!" echo " - Use aliases for quicker access (e.g., 'claude-code prd')"
Content is user-generated and unverified.
    Complete Claude Code Workflow Setup Script | Claude