diff --git a/references/examples/greenfield-examples.md b/references/examples/greenfield-examples.md new file mode 100644 index 0000000..daadf91 --- /dev/null +++ b/references/examples/greenfield-examples.md @@ -0,0 +1,370 @@ +# Greenfield Workflow Examples + +Real-world examples of complete greenfield workflows. + +## Token Budget + +**Tier 1**: 100 tokens (already loaded) +**Tier 2**: 2,000 tokens (already loaded) +**Tier 3 (this guide)**: ~500 tokens + +**Current total**: 2,600 tokens +**Remaining budget**: 7,400 tokens ✅ + +--- + +## Example 1: Photo Album Organizer (React + TypeScript) + +### Complete Workflow + +```bash +# Step 1: Initialize +specify init photo-organizer --ai claude + +# Step 2: Constitution +``` + +``` +/speckit.constitution Create principles focused on: +- Modern React best practices (hooks, functional components) +- TypeScript strict mode for type safety +- Performance (60fps interactions, <3s initial load) +- Accessibility (WCAG 2.1 AA) +- Testing coverage 80%+ +``` + +Generated constitution emphasizes: +- Component reusability and composition +- Minimal dependencies (prefer platform APIs) +- Progressive Web App capabilities +- Offline-first architecture + +``` +# Step 3: Specify +``` + +``` +/speckit.specify Build a photo album organizer with these features: +- Import photos from local device +- Auto-group photos by date (EXIF data) +- Manual album creation and editing +- Drag-and-drop photo reorganization +- Grid thumbnail view with lazy loading +- Support up to 10,000 photos per album +- Export albums as zip files +- Offline functionality with local storage +``` + +Generated specify.md includes: +- 8 user stories covering photographer workflows +- 15 functional requirements with acceptance criteria +- Success metrics (upload <2s, drag latency <100ms) +- Constraints (browser support, storage limits) + +``` +# Step 4: Plan +``` + +``` +/speckit.plan Technology stack: +- React 18 with TypeScript 5 +- Vite for fast development and builds +- Tailwind CSS for styling +- dnd-kit for drag-and-drop +- IndexedDB for local storage +- Vitest + React Testing Library for tests +- Virtualized list (react-window) for performance + +Architecture: +- Component-based with presentational/container split +- Zustand for state management +- Custom hooks for photo operations +- Service layer for IndexedDB operations +``` + +Generated plan.md defines: +- Component hierarchy (App → AlbumList → Album → PhotoGrid → PhotoTile) +- State management strategy (albums, photos, UI state) +- Data model (Album, Photo, Tag entities) +- Implementation phases (4 phases over 3 days) + +``` +# Step 5: Tasks +``` + +Generated tasks.md with 28 tasks: + +**Scaffolding (Tasks 1-6)**: +1. Initialize Vite + React + TypeScript +2. Install Tailwind, dnd-kit, zustand, react-window +3. Set up folder structure +4. Configure Vitest +5. Create IndexedDB wrapper utilities +6. Set up ESLint + Prettier + +**Core UI (Tasks 7-16)**: +7. Build PhotoGrid with virtualization +8. Create PhotoTile component +9. Implement drag-and-drop +10. Build Album component +11. Create AlbumList navigation +12. Add photo upload functionality +... (16 total UI tasks) + +**Features (Tasks 17-24)**: +17. EXIF data extraction +18. Auto-grouping by date +19. Search functionality +20. Zip export feature +21. Offline sync logic +... (8 total feature tasks) + +**Testing & Polish (Tasks 25-28)**: +25. Unit tests for components +26. Integration tests for workflows +27. Performance optimization +28. Accessibility audit + +``` +# Step 6: Implement +``` + +``` +/speckit.implement +``` + +Result: Working photo organizer app with all features implemented. + +--- + +## Example 2: Task Management API (Node.js + Express) + +### Complete Workflow + +```bash +specify init task-api --ai claude +``` + +**Constitution**: +``` +/speckit.constitution API design principles: +- RESTful resource-based endpoints +- OpenAPI 3.1 documentation +- JWT authentication + role-based access +- PostgreSQL for data persistence +- Redis for caching and sessions +- 99.9% uptime SLA +- <100ms average response time +- Comprehensive error handling +``` + +**Specification**: +``` +/speckit.specify Build a task management API with: +- User authentication (register, login, JWT refresh) +- Task CRUD (create, read, update, delete) +- Task assignment to users +- Task status workflow (todo → in_progress → done) +- Due date reminders +- Task filtering and pagination +- Rate limiting (100 req/min per user) +- API versioning (v1) +``` + +**Plan**: +``` +/speckit.plan Stack: +- Node.js 20+ with TypeScript +- Express 4.x for routing +- Prisma ORM for PostgreSQL +- ioredis for Redis +- Passport.js for auth +- express-rate-limit for rate limiting +- Winston for logging +- Jest for testing + +Architecture: +- Layered architecture (routes → controllers → services → repositories) +- Middleware chain (auth → validation → rate-limit → routes) +- Database migrations with Prisma +- Environment-based configuration +``` + +**Tasks** (32 tasks): +1. Initialize Node.js + TypeScript project +2. Set up Express server with basic middleware +3. Configure Prisma + PostgreSQL +4. Create database schema (users, tasks tables) +5. Implement JWT authentication +6. Build user registration endpoint +7. Build user login endpoint +8. Create task CRUD endpoints +9. Add task assignment logic +10. Implement status workflow validation +... (32 total) + +**Implement**: +``` +/speckit.implement +``` + +Result: Production-ready task API with documentation. + +--- + +## Example 3: E-commerce Product Catalog (Vue.js) + +### Abbreviated Workflow + +**Constitution**: Focus on SEO, performance, mobile-first design + +**Specification**: +- Product listing with filtering (price, category, rating) +- Product detail pages with image gallery +- Shopping cart (add, remove, update quantities) +- Checkout flow (guest + registered users) +- Order history for registered users + +**Plan**: +- Vue 3 with Composition API + TypeScript +- Nuxt 3 for SSR/SEO +- Pinia for state management +- Tailwind for responsive design +- Stripe for payments +- MongoDB for product catalog + +**Key Tasks**: +- SSR setup with Nuxt +- Product listing with server-side filters +- Image optimization and lazy loading +- Shopping cart state management +- Stripe payment integration +- Order confirmation emails + +**Result**: SEO-optimized e-commerce site + +--- + +## Example 4: Real-Time Chat Application (WebSockets) + +### Abbreviated Workflow + +**Constitution**: Real-time performance, scalability, security + +**Specification**: +- User authentication and profiles +- One-on-one messaging +- Group chat rooms +- Typing indicators +- Read receipts +- Message history and search +- File sharing (images, documents) + +**Plan**: +- React + TypeScript frontend +- Node.js + Socket.io backend +- PostgreSQL for message persistence +- Redis for pub/sub and presence +- MinIO for file storage +- JWT + refresh tokens for auth + +**Key Tasks**: +- WebSocket connection management +- Real-time message delivery +- Typing indicator implementation +- Message read status tracking +- File upload and streaming +- Reconnection and offline handling + +**Result**: Production-grade chat app + +--- + +## Example 5: Mobile Fitness Tracker (React Native) + +### Abbreviated Workflow + +**Constitution**: Cross-platform (iOS + Android), offline-first, battery efficient + +**Specification**: +- Activity tracking (steps, distance, calories) +- Workout logging (runs, gym sessions) +- Progress charts and analytics +- Goal setting and notifications +- Social features (share workouts, challenges) +- Integration with health APIs (Apple Health, Google Fit) + +**Plan**: +- React Native + TypeScript +- Expo for build tooling +- SQLite for local data +- AsyncStorage for settings +- React Navigation for routing +- Victory Native for charts +- expo-notifications for reminders + +**Key Tasks**: +- Pedometer integration +- Workout tracking UI +- Chart components with Victory +- Health API integration +- Background location tracking +- Push notifications +- Data sync to cloud + +**Result**: Cross-platform fitness app + +--- + +## Common Patterns Across Examples + +### Constitution Themes +- Testing requirements (80%+ coverage common) +- Performance targets (load time, response time, fps) +- Technology constraints (versions, platforms) +- Quality standards (accessibility, security, documentation) + +### Specification Patterns +- User stories in "As a [role], I want [goal], so that [benefit]" format +- Functional requirements with measurable acceptance criteria +- Non-functional requirements (performance, security, scalability) +- Constraints and assumptions explicitly stated + +### Planning Patterns +- Clear technology stack with rationale +- Layered or component-based architecture +- Implementation phases (scaffolding → core → polish) +- Risk assessment and mitigation strategies + +### Task Breakdown Patterns +- 20-40 tasks typical for medium features +- Grouped by category (scaffolding, UI, features, testing) +- Dependencies explicitly noted +- Complexity estimates (simple, medium, complex) + +--- + +## Lessons Learned + +### What Works Well +1. **Detailed specifications** lead to clearer plans and implementations +2. **Technology constraints in constitution** prevent plan conflicts +3. **Phase-based task organization** leads to logical implementation order +4. **Explicit success criteria** enable validation and testing + +### Common Pitfalls +1. **Vague specifications** → AI guesses, may not match intent +2. **Over-constrained constitution** → Limits flexibility in planning +3. **Too many tasks** → Overwhelming, hard to track progress +4. **Skipping optional commands** → Miss opportunities for clarification and validation + +--- + +## Next Steps + +- **Try a greenfield workflow** yourself with a small feature +- **Compare your results** to these examples +- **Iterate on prompts** to get better specifications and plans +- **Load feature management guide** if working with multiple features + +→ Feature management: `references/guides/feature-management-quick.md` diff --git a/references/guides/codebase-analysis.md b/references/guides/codebase-analysis.md new file mode 100644 index 0000000..e9c65bf --- /dev/null +++ b/references/guides/codebase-analysis.md @@ -0,0 +1,414 @@ +# Codebase Analysis Guide + +How to analyze existing codebases before applying Spec-Driven Development. + +## Token Budget + +**Tier 1**: 100 tokens (already loaded) +**Tier 2**: 2,000 tokens (already loaded) +**Tier 3 (this guide)**: ~1,250 tokens + +**Current total**: 3,350 tokens +**Remaining budget**: 6,650 tokens ✅ + +--- + +## Analysis Depth Options + +Choose analysis depth based on project size and goals: + +### Surface Analysis (~5 minutes) + +**What it covers**: +- File structure and organization +- Technology stack identification +- Basic pattern recognition (MVC, layered, etc.) +- Dependency overview + +**Best for**: +- Quick overview needed +- Small codebases (<5,000 lines) +- Familiar tech stack +- Simple feature additions + +**Command**: +``` +/speckit.brownfield --depth surface +``` + +**Output example**: +```markdown +## Surface Analysis Report + +### Project Structure +- Backend: src/server/ (Node.js + Express) +- Frontend: src/client/ (React + TypeScript) +- Tests: tests/ (Jest) + +### Tech Stack +- Runtime: Node.js 18 +- Framework: Express 4.x +- Database: PostgreSQL via Prisma +- Frontend: React 18, Vite + +### Patterns Detected +- Layered architecture (routes → controllers → services) +- RESTful API design +- JWT authentication +``` + +--- + +### Moderate Analysis (~15 minutes) + +**What it covers**: +- Everything in Surface Analysis, plus: +- Architecture patterns in detail +- Coding standards extraction +- Dependency mapping and versions +- Technical debt identification +- Performance baseline +- Security practices + +**Best for**: +- Standard brownfield adoption +- Medium codebases (5,000-50,000 lines) +- Complex feature additions +- Modernization projects + +**Command**: +``` +/speckit.brownfield --depth moderate +``` + +**Output example**: +```markdown +## Moderate Analysis Report + +[... Surface analysis content ...] + +### Architecture Details +- **Routes Layer**: Express routers with route-level middleware +- **Controller Layer**: Request/response handling, input validation +- **Service Layer**: Business logic, orchestrates repositories +- **Repository Layer**: Data access via Prisma ORM +- **Middleware**: Auth, logging, error handling, rate limiting + +### Coding Standards +- **TypeScript**: Strict mode enabled, no implicit any +- **Testing**: Jest + Supertest, ~70% coverage +- **Linting**: ESLint (Airbnb config), Prettier +- **Documentation**: JSDoc for public APIs + +### Dependencies (32 total) +**Production**: +- express@4.18.2 +- prisma@5.2.0 +- jsonwebtoken@9.0.1 +- bcrypt@5.1.0 +[... more dependencies ...] + +**Development**: +- typescript@5.1.6 +- jest@29.6.2 +- eslint@8.46.0 +[... more dependencies ...] + +### Technical Debt +1. **High Priority**: + - Missing error handling in authentication middleware + - No retry logic for database operations + - Hardcoded configuration values + +2. **Medium Priority**: + - Inconsistent error response formats + - Some controllers are too large (>200 lines) + - Limited test coverage in service layer + +3. **Low Priority**: + - Outdated dependencies (5 minor version updates available) + - Missing API documentation (no OpenAPI spec) + +### Performance Baseline +- Average response time: 120ms +- Database query time: 40ms average +- Memory usage: 250MB steady state +- No caching layer detected +``` + +--- + +### Deep Analysis (~30+ minutes) + +**What it covers**: +- Everything in Moderate Analysis, plus: +- Comprehensive feature inventory +- Complete reverse-engineering +- Integration point mapping +- Data flow analysis +- Security audit +- Compliance check +- Migration path recommendations + +**Best for**: +- Large migration projects +- Enterprise adoption +- Complex legacy systems +- Comprehensive documentation needed + +**Command**: +``` +/speckit.brownfield --depth deep +``` + +**Output example**: +```markdown +## Deep Analysis Report + +[... Moderate analysis content ...] + +### Feature Inventory (12 features discovered) + +**Authentication Module**: +- User registration +- Login/logout +- JWT token management +- Password reset flow + +**User Management**: +- User profile CRUD +- Role-based access control +- User search and filtering + +**Task Management**: +- Task CRUD +- Task assignment +- Status workflow +- Due date reminders +- Task search/filter + +**Notification System**: +- Email notifications +- In-app notifications +- Notification preferences + +### Integration Point Mapping + +**External Services**: +- SendGrid (email delivery) +- AWS S3 (file storage) +- Stripe (payments) - partially integrated + +**Internal Dependencies**: +``` +User Module + ↓ + ├─→ Auth Module (dependency) + ├─→ Notification Module (uses) + └─→ Task Module (references) + +Task Module + ↓ + ├─→ User Module (references) + └─→ Notification Module (uses) +``` + +### Data Flow Analysis + +**User Registration Flow**: +1. POST /api/users/register +2. Controller validates input +3. Service checks for existing user +4. Service hashes password (bcrypt) +5. Repository creates user in DB +6. Service triggers welcome email (SendGrid) +7. Controller returns JWT token + +**Critical Flows**: +- Authentication: 15 requests/second peak +- Task creation: 8 requests/second average +- File upload: 2 requests/second average + +### Security Audit + +**Strengths**: +- JWT authentication with refresh tokens +- Password hashing with bcrypt (salt rounds: 10) +- SQL injection prevention (Prisma ORM) +- HTTPS enforced +- Rate limiting on auth endpoints + +**Vulnerabilities**: +- ⚠️ **High**: Missing CSRF protection +- ⚠️ **High**: JWT tokens never expire (no max lifetime) +- ⚠️ **Medium**: No input sanitization for file uploads +- ⚠️ **Medium**: Sensitive data in logs (tokens, passwords) +- ⚠️ **Low**: Missing security headers (HSTS, CSP) + +### Compliance Check + +**GDPR**: +- ✅ User data deletion endpoint exists +- ✅ Data export functionality +- ❌ Missing consent tracking +- ❌ No data retention policy + +**Accessibility (WCAG 2.1)**: +- ⚠️ Limited analysis (backend-only project) +- Recommend frontend audit + +### Migration Path Recommendations + +**Short Term (1-2 weeks)**: +1. Fix high-priority security vulnerabilities +2. Add CSRF protection +3. Implement JWT expiration +4. Update critical dependencies + +**Medium Term (1-2 months)**: +1. Improve test coverage to 85%+ +2. Extract configuration to environment variables +3. Add OpenAPI documentation +4. Implement caching layer (Redis) + +**Long Term (3-6 months)**: +1. Migrate to microservices architecture (if scaling needed) +2. Add event-driven architecture for notifications +3. Implement comprehensive audit logging +4. GDPR compliance enhancements +``` + +--- + +## Choosing the Right Depth + +### Decision Matrix + +| Codebase Size | Feature Complexity | Goal | Recommended Depth | +|--------------|-------------------|------|------------------| +| <5k lines | Simple addition | Add feature | Surface | +| <5k lines | Major refactor | Modernize | Moderate | +| 5k-50k lines | Simple addition | Add feature | Moderate | +| 5k-50k lines | Major refactor | Modernize | Deep | +| 50k+ lines | Any change | Any goal | Deep | +| Legacy system | Unknown | Document | Deep | + +### Time vs. Value Tradeoff + +**Surface** (5 min): +- Value: Basic understanding, quick start +- Limitation: May miss technical debt, integration complexity + +**Moderate** (15 min): +- Value: Comprehensive overview, identifies risks +- Limitation: May not discover all integration points + +**Deep** (30+ min): +- Value: Complete picture, migration planning +- Limitation: Time-consuming, may be overkill for simple features + +--- + +## Analysis Report Sections + +### Every Report Includes + +1. **Project Structure**: Directory layout, organization +2. **Tech Stack**: Languages, frameworks, tools +3. **Architecture Patterns**: High-level design patterns +4. **Next Steps**: Recommended actions based on findings + +### Moderate Reports Add + +5. **Coding Standards**: Style guides, conventions +6. **Dependencies**: Full dependency tree with versions +7. **Technical Debt**: Prioritized list of issues +8. **Performance Baseline**: Current metrics + +### Deep Reports Add + +9. **Feature Inventory**: Complete list of existing features +10. **Integration Mapping**: Internal and external dependencies +11. **Data Flow**: Critical business flows +12. **Security Audit**: Vulnerabilities and recommendations +13. **Compliance**: Regulatory requirements (GDPR, HIPAA, etc.) +14. **Migration Path**: Phased modernization plan + +--- + +## After Analysis + +### Use Report to Generate Constitution + +``` +/speckit.analyze-codebase --from-analysis report.md +``` + +This creates `.speckit/constitution.md` that: +- Acknowledges existing patterns and standards +- Identifies improvement opportunities +- Sets direction for new features + +### Use Report to Plan Integration + +When specifying new features: +- Reference integration points from analysis +- Account for discovered technical debt +- Align with existing architecture patterns +- Plan for identified security vulnerabilities + +--- + +## Troubleshooting + +### Analysis Fails + +**Codebase too large (>100k lines)**: +- Use `--scope` to analyze specific directories +- Example: `/speckit.brownfield --scope src/api --depth moderate` + +**Permissions errors**: +- Ensure read access to all files +- Check if any files are locked or encrypted + +**Unclear architecture**: +- Start with surface analysis +- Manually explore key files +- Re-run with moderate depth after understanding + +### Analysis Incomplete + +**Missing features**: +- Deep analysis may still miss undocumented features +- Supplement with interviews, user stories, or manual exploration + +**Wrong technology identified**: +- Verify analysis output against known facts +- Correct in constitution.md if needed + +**Outdated dependencies not flagged**: +- Run `npm outdated` or equivalent separately +- Add findings to technical debt list manually + +--- + +## Integration with Greenfield Workflow + +After brownfield analysis and constitution generation, the workflow converges with greenfield: + +``` +[Brownfield Analysis] → [Constitution from Code] → +[Specify New Feature] → [Plan] → [Tasks] → [Implement] + ↑ + └─── Same workflow as greenfield from here +``` + +Key difference: Constitution acknowledges existing patterns, new features integrate with existing code. + +--- + +## Next Steps + +- After analysis, load: `references/workflows/brownfield-quick-start.md` +- For integration planning, load: `references/guides/integration-planning.md` +- For reverse engineering features, load: `references/guides/reverse-engineering.md` diff --git a/references/guides/feature-management-quick.md b/references/guides/feature-management-quick.md new file mode 100644 index 0000000..6b3e292 --- /dev/null +++ b/references/guides/feature-management-quick.md @@ -0,0 +1,349 @@ +# Feature Management Quick Guide + +Natural language feature management for SDD projects. + +## Token Budget + +**Tier 1**: 100 tokens (already loaded) +**Tier 2**: 2,000 tokens (already loaded) +**Tier 3 (this guide)**: ~1,000 tokens + +**Current total**: 3,100 tokens +**Remaining budget**: 6,900 tokens ✅ + +--- + +## Overview + +Claude automatically tracks features and provides natural language management - no manual tracking needed. + +**Works for**: Both greenfield and brownfield projects +**When**: After first `/speckit.specify` or when planning multiple features + +--- + +## Natural Language Commands + +### Add Features + +**Just describe what you want**: +- "Add a new feature for user notifications" +- "We need email integration" +- "Let's add an admin dashboard" + +**Claude will**: +1. Detect the feature request +2. Ask: Priority? Dependencies? Description? +3. Create feature entry +4. Show updated status + +**Example**: +``` +You: "Add a feature for user notifications" + +Claude: I'll add "user-notifications". A few questions: +1. Priority: High/Medium/Low? +2. Dependencies: Depends on any existing features? +3. Brief description? + +[You answer...] + +Claude: +✅ Feature added: user-notifications + +📊 Updated Feature List: +1. user-authentication (In Progress - 80%) +2. profile-management (Pending) +3. user-notifications (Pending) ← NEW +``` + +--- + +### Reorder Features + +**Natural commands**: +- "Move user-notifications before profile-management" +- "Let's do admin-dashboard first" +- "Prioritize email integration" + +**Example**: +``` +You: "Let's do user-notifications before profile-management" + +Claude: +Current: auth → profile → notifications +Proposed: auth → notifications → profile ← MOVED UP + +This will update dependencies if needed. +Confirm? (yes/no) + +[You: yes] + +✅ Feature order updated! +📊 Next: user-notifications +``` + +--- + +### Remove Features + +**Natural commands**: +- "Remove the reporting feature" +- "Delete admin-dashboard" +- "We don't need email integration" + +**Example**: +``` +You: "Remove the reporting feature" + +Claude: +⚠️ Warning: Remove 'reporting'? + +Impact: +- Depending features: None +- Progress lost: 0% (not started) +- Artifacts: None + +Confirm? (yes/no) + +[You: yes] + +✅ Feature 'reporting' removed +``` + +--- + +### Show Status + +**Natural commands**: +- "Show feature status" +- "What's the current progress?" +- "Show me the feature dashboard" + +**Displays**: +``` +📊 Project Feature Status Dashboard + +🎯 CURRENT FEATURE +├─ profile-management (Planning - 40%) +│ ├─ ✅ Requirements specified +│ ├─ 🔄 Implementation plan in progress +│ ├─ ⏸️ Tasks not started +│ └─ ⏸️ Implementation not started +│ Blockers: None + +📋 FEATURE PIPELINE +┌─────────────┬───────┬──────────┬─────────────┐ +│ Feature │ Phase │ Progress │ Status │ +├─────────────┼───────┼──────────┼─────────────┤ +│ auth │ Done │ [●●●●●●]│ ✅ Complete │ +│ profile │ Plan │ [●●○○○○]│ 🔄 Active │ +│ notifications│ Queue│ [○○○○○○]│ ⏹️ Queued │ +│ admin │ Queue │ [○○○○○○]│ ⏹️ Queued │ +└─────────────┴───────┴──────────┴─────────────┘ + +🔗 DEPENDENCIES +- notifications depends on auth (satisfied ✅) +- admin depends on auth (satisfied ✅) + +⚠️ BLOCKERS: None +``` + +--- + +## Automatic Tracking + +### After Every SDD Command + +Claude automatically: +1. Detects which feature you're working on +2. Updates progress based on completed step +3. Shows brief status line in summary + +**Example after `/speckit.plan`**: +``` +## Technical Plan Summary + +📊 Feature Status: profile-management (Planned) → Next: notifications +Progress: [●●●○○○] 50% | Completed: 1 of 3 features + +[rest of summary...] +``` + +--- + +## Progress Tracking + +### Workflow Phases + +**Greenfield** (6 steps = 100%): +- Constitution: 17% +- Specify: 33% +- Plan: 50% +- Tasks: 67% +- Implement start: 83% +- Implement complete: 100% + +**Brownfield** (8 steps = 100%): +- Analyze: 12% +- Constitution: 25% +- Reverse-engineer: 37% +- Specify: 50% +- Integration plan: 62% +- Tasks: 75% +- Implement start: 87% +- Implement complete: 100% + +### Multiple Features + +**Overall progress** = Average across all features + +Example: +- Feature 1: 100% (complete) +- Feature 2: 50% (planning) +- Feature 3: 0% (queued) +- **Average**: 50% project complete + +--- + +## Feature Dependencies + +### Declaring Dependencies + +When adding feature, specify dependencies: +``` +You: "Add social sharing feature" + +Claude: Dependencies? + +You: "Depends on user-authentication" + +Claude: +✅ Feature added with dependency + +⚠️ Note: social-sharing blocked until auth complete +``` + +### Auto-Detection + +Claude also detects implicit dependencies: +- Reading from same database tables +- Calling same services +- Similar integration points + +**Example**: +``` +Claude: I noticed 'social-sharing' and 'notifications' both + use the Email Service. Consider implementing + notifications first to establish email patterns. + +Would you like to reorder? (yes/no) +``` + +--- + +## Best Practices + +### Start Small +- 1st project: 1-2 features maximum +- Learn workflow before scaling +- Add more features once comfortable + +### Plan Dependencies +- Authentication usually first +- Core features before enhancements +- Data models before UI + +### Review Before Reordering +- Check dependency impact +- Consider implementation complexity +- Balance business value vs. technical foundation + +### Use Status Dashboard +- Request after each completed feature +- Track before starting new feature +- Monitor blockers proactively + +--- + +## Integration with Workflows + +### Greenfield +``` +specify init → +/speckit.constitution → +/speckit.specify [Feature 1] → + "Add features: [F2], [F3]" ← Feature management starts + /speckit.plan [Feature 1] → + /speckit.tasks [Feature 1] → + /speckit.implement [Feature 1] → +"Show status" → [F1 complete, start F2] +/speckit.specify [Feature 2] → +... +``` + +### Brownfield +``` +/speckit.brownfield → +specify init --here → +/speckit.analyze-codebase → +/speckit.specify [New Feature 1] → + "Add features: [NF2], [NF3]" ← Feature management + /speckit.integration-plan [Feature 1] → + /speckit.tasks [Feature 1] → + /speckit.implement [Feature 1] → +... +``` + +--- + +## Troubleshooting + +### Features Not Tracked + +**Problem**: Claude doesn't show feature status +**Solution**: +1. Explicitly mention multiple features: "I want to build auth, profile, and admin features" +2. Or ask: "Can you track these features?" + +### Wrong Feature Active + +**Problem**: Claude working on wrong feature +**Solution**: "Let's switch to [feature-name]" or "Let's work on [feature-name] next" + +### Lost Feature List + +**Problem**: Feature list disappeared after restart +**Solution**: +- Features stored in `.speckit/features/` directory +- Ask: "Show feature status" to rebuild list +- Or: "What features have we specified?" + +### Dependency Conflicts + +**Problem**: Feature X depends on Y, but Y depends on X +**Solution**: +1. Identify circular dependency +2. Refactor: Extract shared logic to new feature Z +3. Both X and Y depend on Z (no cycle) + +--- + +## Feature Metadata + +Features tracked with: +- **Name**: Slug format (user-authentication) +- **Priority**: High/Medium/Low +- **Dependencies**: List of feature names +- **Phase**: Constitution/Specify/Plan/Tasks/Implement/Complete +- **Progress**: 0-100% +- **Blockers**: Any blocking issues +- **Artifacts**: Generated `.speckit/features/` files + +--- + +## Next Steps + +- **For detailed dashboard format**: Load `references/templates/feature-status-dashboard.md` +- **For brief status format**: Load `references/templates/feature-status-brief.md` +- **Return to workflow**: `references/workflows/greenfield-quick-start.md` or `brownfield-quick-start.md` diff --git a/references/guides/greenfield-step-details.md b/references/guides/greenfield-step-details.md new file mode 100644 index 0000000..17bea81 --- /dev/null +++ b/references/guides/greenfield-step-details.md @@ -0,0 +1,456 @@ +# Greenfield Step-by-Step Details + +Complete reference for each step in the greenfield workflow. + +## Token Budget + +**Tier 1**: 100 tokens (already loaded) +**Tier 2**: 2,000 tokens (already loaded) +**Tier 3 (this guide)**: ~750 tokens + +**Current total**: 2,850 tokens +**Remaining budget**: 7,150 tokens ✅ + +--- + +## Step 1: Initialize Project + +### Basic Initialization + +```bash +# Create new project directory +specify init my-project --ai claude + +# Initialize in current directory +specify init --here --ai claude +``` + +### Advanced Options + +```bash +# With specific AI assistant +specify init my-project --ai cursor-agent +specify init my-project --ai windsurf +specify init my-project --ai copilot + +# With PowerShell scripts (Windows/cross-platform) +specify init my-project --ai copilot --script ps + +# Skip git initialization +specify init my-project --ai gemini --no-git + +# Debug mode (verbose output) +specify init my-project --ai claude --debug + +# With GitHub token (corporate environments) +specify init my-project --ai claude --github-token ghp_your_token_here +``` + +### What Gets Created + +``` +my-project/ +├── .speckit/ +│ ├── constitution.md.template +│ └── features/ +├── .claude/ +│ └── commands/ +│ ├── speckit.constitution.md +│ ├── speckit.specify.md +│ ├── speckit.plan.md +│ ├── speckit.tasks.md +│ └── speckit.implement.md +└── .git/ (unless --no-git specified) +``` + +### Troubleshooting + +| Problem | Solution | +|---------|----------| +| Command not found | Install specify-cli: `uv tool install specify-cli --from git+https://github.com/github/spec-kit.git` | +| Permission denied | Check directory permissions, try with sudo (not recommended) or in user directory | +| Git initialization fails | Use `--no-git` flag, initialize git manually later | +| AI agent not recognized | Check supported agents list, use generic name if your agent not listed | + +--- + +## Step 2: Establish Project Principles + +### Command + +``` +/speckit.constitution +``` + +### Purpose + +Define your project's governing principles, coding standards, and quality expectations. This becomes the foundation for all future decisions. + +### Example Prompts + +**For Web Apps**: +``` +/speckit.constitution Create principles focused on: +- Modern web standards (ES2024+, Web Components) +- Accessibility (WCAG 2.1 AA minimum) +- Performance (Core Web Vitals targets) +- Testing (unit + integration + e2e) +``` + +**For APIs**: +``` +/speckit.constitution Create principles focused on: +- RESTful design patterns +- OpenAPI 3.1 documentation +- Authentication/authorization standards +- Performance SLAs (99.9% uptime, <100ms response) +``` + +**For Mobile Apps**: +``` +/speckit.constitution Create principles focused on: +- Cross-platform (iOS + Android) +- Offline-first architecture +- Battery efficiency +- App store compliance (Apple HIG, Material Design) +``` + +### What Gets Generated + +`.speckit/constitution.md` containing: +- Core development principles +- Technology constraints and standards +- Quality expectations +- Testing requirements +- Performance targets + +### After This Command + +Use `references/templates/10-point-summary-template.md` to summarize the constitution for the user. + +--- + +## Step 3: Create the Specification + +### Command + +``` +/speckit.specify +``` + +### Purpose + +Describe WHAT to build, focusing on requirements and user needs, not technical implementation. + +### Example Prompts + +**Feature Description**: +``` +/speckit.specify Build a photo album organizer that: +- Groups photos by date automatically +- Allows drag-and-drop reorganization +- Displays thumbnails in grid layout +- Supports albums up to 10,000 photos +- Works offline with local storage +``` + +**User Story Format**: +``` +/speckit.specify As a photographer, I want to organize my photos into albums by event and date, so I can quickly find and share specific photo collections. Key requirements: +- Auto-grouping by EXIF date +- Manual album creation and editing +- Fast search across all albums +- Export album as zip file +``` + +### What Gets Generated + +`.speckit/features/001-[feature-name]/specify.md` containing: +- Feature description +- User stories +- Functional requirements +- Success criteria +- Constraints and assumptions + +### Key Guidelines + +**Do Focus On**: +- What users need to accomplish +- Business requirements and goals +- Success metrics +- Constraints (performance, compatibility, etc.) + +**Don't Focus On**: +- Technology choices (save for planning step) +- Implementation details +- Database schemas or API designs +- Library or framework selections + +### After This Command + +Use `references/templates/10-point-summary-template.md` to summarize the specification. + +If you have multiple features planned, ask: "Do you have additional features to specify?" + +--- + +## Step 4: Create Technical Implementation Plan + +### Command + +``` +/speckit.plan +``` + +### Purpose + +Define HOW to build the feature: technology stack, architecture, dependencies, and implementation approach. + +### Example Prompts + +**Tech Stack Specification**: +``` +/speckit.plan Use: +- React 18+ with TypeScript +- Vite for build tooling +- Tailwind CSS for styling +- IndexedDB for local storage +- Vitest for testing +Keep dependencies minimal, avoid unnecessary abstractions +``` + +**Architecture Guidance**: +``` +/speckit.plan Design a component-based architecture with: +- Presentational/Container component split +- Context API for state management +- Custom hooks for business logic +- Service layer for data access +Focus on testability and maintainability +``` + +### What Gets Generated + +`.speckit/features/001-[feature-name]/plan.md` containing: +- Technology stack choices with rationale +- Architecture and design patterns +- Key dependencies +- Implementation phases +- Risk assessment + +### Key Guidelines + +**Technology Choices Should Consider**: +- Constitution constraints +- Team expertise +- Project requirements +- Performance needs +- Maintainability + +**Architecture Should Define**: +- Component/module structure +- Data flow patterns +- State management approach +- API/service boundaries +- Testing strategy + +### After This Command + +Use `references/templates/10-point-summary-template.md` to summarize the plan. + +--- + +## Step 5: Break Down into Tasks + +### Command + +``` +/speckit.tasks +``` + +### Purpose + +Create an actionable task list with clear implementation steps, dependencies, and complexity estimates. + +### What Gets Generated + +`.speckit/features/001-[feature-name]/tasks.md` containing: +- Numbered task list +- Task categories (scaffolding, UI, backend, testing, etc.) +- Dependencies between tasks +- Complexity estimates +- Acceptance criteria per task + +### Task Organization + +Tasks typically organized by: +1. **Scaffolding** - Project setup, dependencies, folder structure +2. **Core Implementation** - Main feature functionality +3. **Polish** - Error handling, edge cases, performance +4. **Testing** - Unit tests, integration tests, e2e tests + +### Example Task Structure + +```markdown +## Scaffolding (Tasks 1-5) +1. Initialize Vite + React + TypeScript project +2. Install and configure Tailwind CSS +3. Set up IndexedDB wrapper utilities +4. Create folder structure (components/, hooks/, services/) +5. Configure Vitest and testing library + +## Core UI (Tasks 6-12) +6. Build PhotoGrid component with virtualization +7. Implement drag-and-drop with dnd-kit +8. Create Album component with thumbnail view +9. Build AlbumList navigation component +... +``` + +### After This Command + +Use `references/templates/10-point-summary-template.md` to summarize the tasks. + +--- + +## Step 6: Execute Implementation + +### Command + +``` +/speckit.implement +``` + +### Purpose + +Execute all tasks in sequence, writing code according to the plan and constitution. + +### What Happens + +The AI agent: +1. Works through tasks sequentially +2. Writes code files +3. Installs dependencies +4. Runs tests +5. Handles errors and edge cases +6. Verifies against success criteria + +### Monitoring Progress + +Watch for: +- Task completion messages +- Test results +- Build output +- Error messages or warnings + +### Intervention Points + +You may need to: +- Clarify ambiguous requirements +- Provide missing credentials or API keys +- Resolve unexpected errors +- Adjust plans based on discovered constraints + +### After Implementation + +1. Run the application locally +2. Verify all requirements met +3. Review code quality +4. Consider next feature (if multi-feature project) + +--- + +## Optional Enhancement Commands + +### Clarify Underspecified Areas + +``` +/speckit.clarify +``` + +**When**: After `/speckit.specify`, before `/speckit.plan` +**Purpose**: Identify and clarify ambiguous or incomplete requirements + +### Analyze Consistency & Coverage + +``` +/speckit.analyze +``` + +**When**: After `/speckit.tasks`, before `/speckit.implement` +**Purpose**: Cross-artifact consistency check and coverage analysis +**Uses**: Analysis scripts from `scripts/` directory + +### Generate Quality Checklists + +``` +/speckit.checklist +``` + +**Purpose**: Create custom quality validation checklists + +--- + +## Best Practices + +### For New Users + +1. **Start small** - One simple feature first to learn the workflow +2. **Review each artifact** - Don't rush through steps +3. **Use examples** - Provide concrete example prompts to AI +4. **Iterate** - Regenerate if first pass doesn't match your vision + +### For Experienced Users + +1. **Leverage constitution** - Strong principles lead to consistent implementations +2. **Be specific in plans** - Detailed tech stack guidance prevents surprises +3. **Group tasks logically** - Well-organized tasks lead to cleaner code +4. **Use optional commands** - Clarify, analyze, and checklist add quality + +### For Enterprise Teams + +1. **Establish team constitution** - Shared principles across projects +2. **Document architecture patterns** - Consistent designs across features +3. **Integrate with CI/CD** - Automate quality checks from SDD artifacts +4. **Version control artifacts** - Commit `.speckit/` alongside code + +--- + +## Troubleshooting + +### Commands Not Working + +**Problem**: `/speckit.*` commands not recognized +**Solutions**: +1. Verify `specify init` ran successfully +2. Check `.claude/commands/` directory exists +3. Restart AI agent +4. Re-run `specify init` if needed + +### Artifacts Not Generated + +**Problem**: Constitution or specs not created +**Solutions**: +1. Check `.speckit/` directory exists and has write permissions +2. Review AI agent output for error messages +3. Verify command syntax (correct slash command) +4. Try with `--debug` flag during init + +### Implementation Fails + +**Problem**: `/speckit.implement` encounters errors +**Solutions**: +1. Review task clarity - vague tasks lead to errors +2. Check constitution for conflicts with plan +3. Verify all tools and dependencies available +4. Break complex tasks into smaller steps +5. Provide more specific technical guidance in plan + +--- + +## Next Steps + +After completing first feature: +- **Multiple features?** Load `references/guides/feature-management-quick.md` +- **Need examples?** Load `references/examples/greenfield-examples.md` +- **Existing codebase?** Switch to `references/workflows/brownfield-quick-start.md` diff --git a/references/guides/integration-planning.md b/references/guides/integration-planning.md new file mode 100644 index 0000000..dc722de --- /dev/null +++ b/references/guides/integration-planning.md @@ -0,0 +1,474 @@ +# Integration Planning for Brownfield Projects + +How to plan integration of new features with existing codebases. + +## Token Budget + +**Tier 1**: 100 tokens (already loaded) +**Tier 2**: 2,000 tokens (already loaded) +**Tier 3 (this guide)**: ~1,250 tokens + +**Current total**: 3,350 tokens +**Remaining budget**: 6,650 tokens ✅ + +--- + +## When to Create Integration Plans + +Use integration planning when: +- Adding new feature to existing codebase +- New feature depends on existing features +- New feature will be consumed by existing code +- Modifying existing features as part of implementation +- Risk of breaking existing functionality + +**Skip integration planning** when: +- Greenfield project (no existing code) +- Fully isolated microservice (no shared code) +- POC/prototype that won't interact with production code + +--- + +## Integration Plan Command + +``` +/speckit.integration-plan +``` + +**Run after**: `/speckit.specify` (requirements defined) +**Run before**: `/speckit.tasks` (task breakdown) + +**Purpose**: Identify and plan how new feature integrates with existing codebase. + +--- + +## Integration Plan Contents + +### 1. Integration Points + +**Where new code touches existing code**: + +```markdown +## Integration Points + +### Consumes Existing Code +- **User Service** (`services/userService.js`) + - Calls: `userService.findById(userId)` + - Reason: New feature needs authenticated user data + - Risk: Medium (user service is stable, widely used) + +- **Email Service** (`services/emailService.js`) + - Calls: `emailService.send(template, recipient, data)` + - Reason: Send notification emails for new feature + - Risk: Low (well-documented API) + +### Consumed By Existing Code +- **Dashboard** (`components/Dashboard.tsx`) + - Integration: Dashboard will display new feature's data + - Modification needed: Add new widget component + - Risk: Low (additive change only) + +- **API Gateway** (`routes/api.js`) + - Integration: Register new feature's routes + - Modification needed: Add route imports + - Risk: Low (standard pattern) + +### Shared Resources +- **Database** (PostgreSQL via Prisma) + - New tables: `tasks`, `task_assignments` + - Foreign keys: References `users` table + - Migrations: Required before deployment + - Risk: Medium (schema changes require coordination) + +- **Redis Cache** + - New keys: `task:${id}`, `user:${id}:tasks` + - Namespace: `tasks:*` for feature-specific keys + - TTL: 5 minutes for task data + - Risk: Low (separate namespace) +``` + +### 2. Required Modifications to Existing Code + +**Changes to existing files**: + +```markdown +## Modifications to Existing Code + +### High Priority (Blocking) + +**1. User Model** (`models/User.js`) +- **Change**: Add `hasTasks()` method +- **Why**: Dashboard needs to check if user has tasks +- **Impact**: Low (additive method, no breaking changes) +- **Files affected**: 1 +- **Tests needed**: Unit test for new method + +**2. Database Schema** (`prisma/schema.prisma`) +- **Change**: Add `Task` and `TaskAssignment` models +- **Why**: New feature requires task storage +- **Impact**: Medium (requires migration, affects production DB) +- **Files affected**: 1 +- **Migration script**: `prisma migrate dev --name add_tasks` +- **Tests needed**: Integration tests for new relationships + +### Medium Priority (Important) + +**3. API Gateway** (`routes/api.js`) +- **Change**: Register `/api/tasks/*` routes +- **Why**: Expose new feature's endpoints +- **Impact**: Low (additive change) +- **Files affected**: 1 +- **Tests needed**: Route registration test + +### Low Priority (Nice to Have) + +**4. Dashboard** (`components/Dashboard.tsx`) +- **Change**: Add `` component +- **Why**: Display tasks on main dashboard +- **Impact**: Low (optional UI enhancement) +- **Files affected**: 2 (Dashboard.tsx, new TaskWidget.tsx) +- **Tests needed**: Component render test +``` + +### 3. Sequencing and Dependencies + +**Implementation order**: + +```markdown +## Implementation Sequence + +### Phase 1: Database Foundation (Day 1) +1. Create Prisma migration for Task models +2. Run migration on dev database +3. Test database constraints and relationships +4. **Blocking**: Must complete before Phase 2 + +### Phase 2: Core Feature (Day 2) +5. Implement task service layer +6. Create task API endpoints +7. Add task repository +8. **Depends on**: Phase 1 (database schema) +9. **Blocking**: Must complete before Phase 3 + +### Phase 3: Integration (Day 3) +10. Modify User model to add `hasTasks()` +11. Register task routes in API gateway +12. **Depends on**: Phase 2 (task endpoints exist) + +### Phase 4: UI Integration (Day 4) +13. Create TaskWidget component +14. Integrate TaskWidget into Dashboard +15. **Depends on**: Phase 2 (API available) +16. **Optional**: Can ship without this phase + +**Critical Path**: Phase 1 → Phase 2 → Phase 3 (3 days minimum) +**Full Feature**: Phase 1 → Phase 2 → Phase 3 → Phase 4 (4 days) +``` + +### 4. Risk Assessment + +**Potential issues and mitigation**: + +```markdown +## Integration Risks + +### High Risk + +**R1: Database Migration Failure** +- **Impact**: Production downtime, data loss +- **Probability**: Low (Prisma handles migrations well) +- **Mitigation**: + 1. Test migration on staging database first + 2. Take database backup before production migration + 3. Have rollback script ready + 4. Schedule migration during low-traffic window + +**R2: Breaking Changes to User Model** +- **Impact**: 15+ files use User model, potential widespread breakage +- **Probability**: Medium (adding method is generally safe, but...) +- **Mitigation**: + 1. Make new method optional (return `null` if feature disabled) + 2. Add feature flag to control new behavior + 3. Run full test suite before merging + 4. Gradual rollout with feature flag + +### Medium Risk + +**R3: API Route Conflicts** +- **Impact**: Existing routes might conflict with `/api/tasks/*` +- **Probability**: Low (route namespace available) +- **Mitigation**: + 1. Check existing routes for conflicts + 2. Use unique prefix if needed (`/api/v2/tasks/`) + +**R4: Performance Impact on Dashboard** +- **Impact**: Adding TaskWidget may slow dashboard load +- **Probability**: Medium (additional API call + rendering) +- **Mitigation**: + 1. Lazy load TaskWidget (only render when visible) + 2. Cache task data in Redis (5 min TTL) + 3. Pagination for task list (show max 10 recent) + +### Low Risk + +**R5: Redis Key Collision** +- **Impact**: Cache keys conflict with existing features +- **Probability**: Very Low (using namespace) +- **Mitigation**: + 1. Use `tasks:*` namespace consistently + 2. Document key patterns in integration plan +``` + +--- + +## Integration Strategies + +### Strategy 1: Adapter Pattern + +**Use when**: New feature's API doesn't match existing patterns + +**Example**: +```markdown +## Integration Strategy: Adapter Pattern + +**Problem**: Existing User Service expects synchronous calls, but new Task Service is async. + +**Solution**: Create adapter layer +```typescript +// adapters/userServiceAdapter.ts +export class UserServiceAdapter { + async getUserTasks(userId: string) { + const user = await userService.findById(userId); // existing sync call + const tasks = await taskService.findByUser(userId); // new async call + return { user, tasks }; + } +} +``` + +**Benefits**: +- Isolates new feature from existing code patterns +- Easier to test +- Can be removed later if existing services refactored + +**Costs**: +- Additional layer adds complexity +- Slight performance overhead +``` + +### Strategy 2: Feature Flags + +**Use when**: Want to deploy without immediately exposing new feature + +**Example**: +```markdown +## Integration Strategy: Feature Flags + +**Implementation**: +```typescript +// config/features.ts +export const features = { + tasks: process.env.FEATURE_TASKS === 'true', +}; + +// components/Dashboard.tsx +{features.tasks && } + +// routes/api.js +if (features.tasks) { + app.use('/api/tasks', taskRoutes); +} +``` + +**Benefits**: +- Deploy code without exposing to users +- Gradual rollout (enable for 10%, 50%, 100% of users) +- Quick rollback if issues discovered + +**Deployment Plan**: +1. Day 1: Deploy with flag OFF (smoke test in production) +2. Day 2: Enable for internal users only +3. Day 3: Enable for 10% of users +4. Day 4: Enable for 50% of users +5. Day 5: Enable for 100% of users +``` + +### Strategy 3: Parallel Endpoints + +**Use when**: Replacing existing functionality with new implementation + +**Example**: +```markdown +## Integration Strategy: Parallel Endpoints + +**Problem**: Replacing old task management with new approach. + +**Solution**: Run both old and new endpoints in parallel + +**Old Endpoints** (keep during migration): +- GET /api/tasks (legacy) +- POST /api/tasks (legacy) + +**New Endpoints** (new implementation): +- GET /api/v2/tasks (new) +- POST /api/v2/tasks (new) + +**Migration Path**: +1. Deploy new endpoints (v2) +2. Update frontend to use v2 endpoints +3. Monitor both endpoints for parity +4. After 2 weeks of v2 usage, deprecate v1 +5. After 4 weeks, remove v1 endpoints + +**Validation**: Shadow traffic - send requests to both v1 and v2, compare responses +``` + +### Strategy 4: Strangler Fig Pattern + +**Use when**: Gradually migrating legacy feature to new implementation + +**Example**: +```markdown +## Integration Strategy: Strangler Fig + +**Problem**: Old task system tightly coupled to entire codebase. + +**Solution**: Gradually replace old with new, route-by-route + +**Phase 1**: New endpoints for new functionality +- `/api/tasks/assignments` (new feature, not in old system) + +**Phase 2**: Reimplement read endpoints +- `/api/tasks` GET (reimplemented, same API contract) +- `/api/tasks/:id` GET (reimplemented) + +**Phase 3**: Reimplement write endpoints +- `/api/tasks` POST (reimplemented) +- `/api/tasks/:id` PUT (reimplemented) + +**Phase 4**: Migrate data and remove old code +- Migrate legacy task data to new schema +- Remove old task system entirely + +**Timeline**: 3-6 months for complete migration +``` + +--- + +## Integration Testing + +### Test Integration Points + +```markdown +## Integration Tests Required + +### User Service Integration +```typescript +// tests/integration/user-task-integration.test.ts +test('user can retrieve their tasks', async () => { + const user = await createTestUser(); + const task = await createTestTask({ assignedTo: user.id }); + + const tasks = await user.getTasks(); // new method + + expect(tasks).toHaveLength(1); + expect(tasks[0].id).toBe(task.id); +}); +``` + +### Database Integration +```typescript +// tests/integration/database.test.ts +test('task references valid user', async () => { + const user = await createTestUser(); + + const task = await prisma.task.create({ + data: { title: 'Test', assignedTo: user.id } + }); + + expect(task.assignedTo).toBe(user.id); + + // Test foreign key constraint + await expect(prisma.task.create({ + data: { title: 'Test', assignedTo: 'invalid-id' } + })).rejects.toThrow(); +}); +``` + +### API Integration +```typescript +// tests/integration/api.test.ts +test('task API routes registered', async () => { + const response = await request(app).get('/api/tasks'); + + expect(response.status).not.toBe(404); // route exists +}); +``` +``` + +--- + +## After Integration Planning + +### Include Integration Tasks in Task Breakdown + +When running `/speckit.tasks`, ensure: +- Integration modifications are separate tasks +- Dependencies are explicit (e.g., "Depends on Task 5") +- Risk mitigation steps are included + +**Example task structure**: +```markdown +## Integration Tasks + +### Task 12: Modify User Model +**Type**: Integration +**Priority**: High +**Depends on**: Tasks 8-11 (core task service implemented) +**Files**: `models/User.js` +**Changes**: Add `async hasTasks()` method +**Tests**: `tests/models/User.test.js` +**Risk**: Low (additive change) +**Mitigation**: Make method optional, feature flag controlled + +### Task 13: Database Migration +**Type**: Integration +**Priority**: High (blocking) +**Depends on**: Nothing (can run first) +**Files**: `prisma/schema.prisma` +**Changes**: Add Task and TaskAssignment models +**Migration**: `prisma migrate dev --name add_tasks` +**Tests**: `tests/integration/database.test.js` +**Risk**: Medium (schema change) +**Mitigation**: Test on staging, backup before prod migration +``` + +--- + +## Troubleshooting + +### Integration Conflicts + +**Existing code breaks after integration**: +1. Check if modifications followed adapter pattern +2. Review test coverage for integration points +3. Use feature flags to isolate new code +4. Consider parallel endpoints during migration + +**Performance degradation**: +1. Check if new code introduces N+1 queries +2. Add caching at integration boundaries +3. Use lazy loading for UI components +4. Profile API endpoints before/after integration + +**Dependency cycles**: +1. New feature depends on existing code that depends on new feature +2. Solution: Introduce interface/abstraction to break cycle +3. Or: Refactor existing code to remove dependency + +--- + +## Next Steps + +- Return to brownfield workflow: `references/workflows/brownfield-quick-start.md` +- Create task breakdown: Run `/speckit.tasks` (will include integration tasks) +- Review reverse-engineering: `references/guides/reverse-engineering.md` (for discovering integration points) diff --git a/references/guides/reverse-engineering.md b/references/guides/reverse-engineering.md new file mode 100644 index 0000000..2eb4744 --- /dev/null +++ b/references/guides/reverse-engineering.md @@ -0,0 +1,541 @@ +# Reverse-Engineering Existing Code + +How to document existing features in SDD format for brownfield projects. + +## Token Budget + +**Tier 1**: 100 tokens (already loaded) +**Tier 2**: 2,000 tokens (already loaded) +**Tier 3 (this guide)**: ~1,250 tokens + +**Current total**: 3,350 tokens +**Remaining budget**: 6,650 tokens ✅ + +--- + +## When to Reverse-Engineer + +Use reverse-engineering when you need to: +- **Document existing features** in SDD format +- **Understand legacy code** before making changes +- **Create baseline specs** for existing functionality +- **Maintain documentation** alongside code +- **Onboard new team members** with executable specs + +**Don't reverse-engineer** when: +- Only adding small feature to existing code (use integration plan instead) +- Codebase is disposable or being replaced +- Time-constrained and only need constitution + +--- + +## Reverse-Engineering Command + +``` +/speckit.reverse-engineer +``` + +**Purpose**: Analyze existing code and generate SDD artifacts (specify.md, plan.md) for discovered features. + +### What Gets Created + +For each discovered feature: +``` +.speckit/features/ +├── 001-user-authentication/ +│ ├── specify.md # Requirements reverse-engineered from code +│ ├── plan.md # Technical details extracted from implementation +│ └── mapping.md # Links to actual source files +├── 002-task-management/ +│ ├── specify.md +│ ├── plan.md +│ └── mapping.md +└── 003-notification-system/ + ├── specify.md + ├── plan.md + └── mapping.md +``` + +--- + +## Reverse-Engineering Strategies + +### Strategy 1: Constitution Only + +**Use when**: Just adopting SDD, focusing on future features only + +**Process**: +1. Run `/speckit.analyze-codebase` to generate constitution +2. Skip `/speckit.reverse-engineer` +3. Start adding new features with SDD workflow + +**Pros**: +- Fastest approach +- Low initial investment +- Future features immediately benefit + +**Cons**: +- Existing features undocumented +- No baseline for comparison +- Integration points unclear + +--- + +### Strategy 2: Baseline Specs for Key Features + +**Use when**: Need documentation for critical features, but not entire codebase + +**Process**: +1. Generate constitution +2. Run `/speckit.reverse-engineer --features "auth,payments,core-workflow"` +3. Manually review and enhance generated specs +4. Use specs as reference for new features + +**Pros**: +- Documents critical paths +- Manageable scope +- Provides integration context + +**Cons**: +- Incomplete picture +- Manual feature selection required +- May miss important integrations + +--- + +### Strategy 3: Full Reverse-Engineering + +**Use when**: Complete documentation needed, large migration, or comprehensive modernization + +**Process**: +1. Generate constitution +2. Run `/speckit.reverse-engineer` (no filters, analyze all features) +3. Review all generated specs +4. Enhance with domain knowledge +5. Use as complete SDD baseline + +**Pros**: +- Complete documentation +- All integration points mapped +- Baseline for refactoring +- Onboarding reference + +**Cons**: +- Time-consuming +- May generate specs for trivial features +- Requires manual cleanup + +--- + +## Reverse-Engineering Process + +### Step 1: Feature Discovery + +**Automatic discovery** looks for: +- Route definitions (Express, Flask, Django, etc.) +- Controller/handler classes +- API endpoints +- UI components +- Database models/schemas +- Business logic modules + +**Example output**: +```markdown +## Discovered Features (12 total) + +### High Confidence +1. **User Authentication** (15 files, 2,300 lines) +2. **Task Management** (22 files, 3,800 lines) +3. **Notification System** (8 files, 1,200 lines) + +### Medium Confidence +4. **File Upload** (5 files, 600 lines) +5. **Search** (3 files, 400 lines) + +### Low Confidence (might be infrastructure) +6. **Database Migrations** (12 files, 800 lines) +7. **Logging Utilities** (4 files, 300 lines) +``` + +### Step 2: Requirements Extraction + +For each feature, generate `specify.md`: + +**Extracted from**: +- Route handlers → Functional requirements +- Validation logic → Constraints +- Test cases → Success criteria +- Error handling → Edge cases +- Comments/docs → User stories (if available) + +**Example** (User Authentication feature): +```markdown +# Feature: User Authentication + +## Description +System for user registration, login, and session management. + +## Functional Requirements (Extracted) + +### FR1: User Registration +**Evidence**: POST /api/users/register endpoint in routes/users.js:15 +**Logic**: Creates new user with email, password, and optional profile data +**Validation**: Email format check, password strength (8+ chars, 1 number, 1 special) +**Success**: Returns 201 with JWT token and user object + +### FR2: User Login +**Evidence**: POST /api/auth/login endpoint in routes/auth.js:42 +**Logic**: Validates credentials, generates JWT token +**Sessions**: Token valid for 24 hours, refresh token for 30 days + +### FR3: Password Reset +**Evidence**: POST /api/auth/reset endpoint in routes/auth.js:89 +**Logic**: Email-based reset flow, tokens expire in 1 hour + +## Success Criteria (From Tests) +- ✅ User can register with valid email and password (auth.test.js:23) +- ✅ Login returns valid JWT token (auth.test.js:67) +- ✅ Invalid credentials return 401 (auth.test.js:91) +- ✅ Password reset email contains valid token (auth.test.js:142) + +## Constraints +- Passwords hashed with bcrypt (10 rounds) +- JWT secret in environment variable +- Email service requires SendGrid API key +- Rate limit: 5 login attempts per minute per IP +``` + +### Step 3: Technical Plan Extraction + +For each feature, generate `plan.md`: + +**Extracted from**: +- File structure → Architecture +- Import statements → Dependencies +- Implementation → Technology choices +- Patterns → Design decisions + +**Example** (User Authentication feature): +```markdown +# Technical Plan: User Authentication + +## Architecture + +**Layered Architecture**: +``` +routes/auth.js (Express routes) + ↓ +controllers/authController.js (Request handling) + ↓ +services/authService.js (Business logic) + ↓ +repositories/userRepository.js (Data access) + ↓ +models/User.js (Prisma model) +``` + +## Technology Stack + +**Backend**: +- Express 4.18.2 (routing) +- Passport.js 0.6.0 (auth strategies) +- jsonwebtoken 9.0.1 (JWT generation) +- bcrypt 5.1.0 (password hashing) + +**Database**: +- PostgreSQL (via Prisma ORM) +- Users table with email, password_hash, created_at + +**Email**: +- SendGrid (password reset emails) + +## Key Dependencies + +**Authentication Flow**: +1. User → POST /api/auth/login +2. authController validates input +3. authService.authenticate() checks credentials +4. userRepository.findByEmail() queries DB +5. bcrypt.compare() validates password +6. jwt.sign() generates token +7. Return token + user object + +## Implementation Phases (Reconstructed) + +**Phase 1: Core Auth** (implemented) +- User model and repository +- Registration endpoint +- Login endpoint +- JWT generation + +**Phase 2: Security** (implemented) +- Password hashing +- Token refresh +- Rate limiting + +**Phase 3: Password Reset** (implemented) +- Reset token generation +- Email integration +- Reset confirmation +``` + +### Step 4: Create File Mappings + +For each feature, generate `mapping.md`: + +**Links specs to actual code**: + +```markdown +# Code Mapping: User Authentication + +## Requirements → Code + +**FR1: User Registration** +- Endpoint: `routes/users.js:15-42` +- Controller: `controllers/authController.js:23-67` +- Service: `services/authService.js:45-89` +- Validation: `middleware/validation.js:12-28` +- Tests: `tests/auth.test.js:23-56` + +**FR2: User Login** +- Endpoint: `routes/auth.js:42-58` +- Controller: `controllers/authController.js:89-132` +- Service: `services/authService.js:105-145` +- Tests: `tests/auth.test.js:67-103` + +**FR3: Password Reset** +- Endpoint: `routes/auth.js:89-112` +- Service: `services/authService.js:178-234` +- Email template: `templates/password-reset.html` +- Tests: `tests/auth.test.js:142-189` + +## Dependencies + +**Internal**: +- User model: `models/User.js` +- Email service: `services/emailService.js` +- Validation middleware: `middleware/validation.js` + +**External**: +- jsonwebtoken: Token generation +- bcrypt: Password hashing +- SendGrid: Email delivery +``` + +--- + +## Validation Commands + +After reverse-engineering, validate the output: + +### Validate Accuracy + +``` +/speckit.validate-reverse-engineering +``` + +**Checks**: +- Do specs match actual code behavior? +- Are all requirements covered by code? +- Are dependencies correctly identified? +- Do tests validate all requirements? + +### Check Coverage + +``` +/speckit.coverage-check +``` + +**Reports**: +- % of codebase documented +- Undocumented features (if any) +- Missing integration points +- Gaps in requirement mapping + +### Trace Feature to Code + +``` +/speckit.trace user-authentication +``` + +**Shows**: +- All files implementing this feature +- Integration points with other features +- Test coverage for feature +- Documentation completeness + +--- + +## Enhancing Reverse-Engineered Specs + +Automated reverse-engineering is good but not perfect. Enhance with: + +### Add Domain Knowledge + +**Automated spec says**: +```markdown +### FR1: User Registration +Creates new user with email and password. +``` + +**Enhanced with domain knowledge**: +```markdown +### FR1: User Registration +**User Story**: As a new visitor, I want to create an account so I can save my work and access it from any device. + +**Business Rule**: Email must be unique across system. Users with duplicate emails are prompted to login instead. + +**Integration**: After successful registration, user is automatically logged in and redirected to onboarding flow. + +**Rationale**: Reduces friction by avoiding separate login step after registration. +``` + +### Clarify Implicit Constraints + +**Automated spec may miss**: +- Business rules not in code +- Manual processes +- External dependencies +- Assumed knowledge + +**Add explicitly**: +```markdown +## Constraints (Enhanced) + +**From Code**: +- Password must be 8+ characters with 1 number and 1 special character + +**From Business**: +- Users under 13 cannot register (COPPA compliance) +- Email domains on blocklist rejected (spam prevention) + +**From Operations**: +- SendGrid monthly email limit: 100,000 +- Database has 1M user capacity (upgrade at 800k) +``` + +### Add Success Metrics + +**Code doesn't specify**, but business cares about: +```markdown +## Success Metrics + +**Performance**: +- Registration completes in <2 seconds +- Login response <500ms + +**Business**: +- Registration completion rate >70% +- Email verification rate >60% +- First-week retention >40% + +**Security**: +- Zero password breaches +- <0.1% fraudulent accounts +``` + +--- + +## Brownfield-Specific Considerations + +### Integration Documentation + +Unlike greenfield, brownfield features integrate with existing code: + +```markdown +## Integration Points (Critical for Brownfield) + +**Consumes**: +- Email service (for verification emails) +- Logging service (audit trail) +- Analytics service (track registrations) + +**Consumed By**: +- Task management (requires authenticated user) +- Notification system (user preferences) +- Profile management (user data CRUD) + +**Shared State**: +- JWT token (used by all protected endpoints) +- User session (stored in Redis) +``` + +### Migration Notes + +Document how feature evolved: + +```markdown +## Migration History + +**v1.0 (2020)**: Basic username/password auth +**v2.0 (2021)**: Added OAuth2 (Google, GitHub) +**v2.5 (2022)**: Added 2FA via TOTP +**v3.0 (2023)**: Migrated to Passport.js from custom auth + +**Current State**: Mixed auth strategies (legacy password + OAuth + 2FA) +**Future Plan**: Consolidate under single Passport.js strategy +``` + +--- + +## Troubleshooting + +### Reverse-Engineering Fails + +**Too many features discovered**: +- Use `--features` filter to target specific features +- Example: `/speckit.reverse-engineer --features "auth,tasks"` + +**Features not detected**: +- Codebase uses non-standard patterns +- Manually create specify.md and mapping.md +- Submit pattern examples to Spec-Kit project + +**Specs are inaccurate**: +- Validate with `/speckit.validate-reverse-engineering` +- Manually review and correct +- Add domain knowledge (see "Enhancing" section) + +### Coverage Gaps + +**Code without tests**: +- Success criteria will be incomplete +- Supplement with manual testing or user stories + +**Undocumented business rules**: +- Interview stakeholders +- Review product docs or wiki +- Add to constraints section + +**External dependencies unclear**: +- Check environment variables +- Review deployment configs +- Document in plan.md integrations section + +--- + +## After Reverse-Engineering + +### Use Specs as Reference for New Features + +When adding new features to brownfield codebase: +1. Review reverse-engineered specs for similar features +2. Identify integration points in mapping.md +3. Follow existing patterns (from plan.md) +4. Ensure consistency with constitution + +### Keep Specs Updated + +As code evolves: +- Re-run `/speckit.reverse-engineer [feature]` to refresh specs +- Update mapping.md if file structure changes +- Add new requirements to specify.md +- Track migration history in plan.md + +--- + +## Next Steps + +- **Integration planning**: Load `references/guides/integration-planning.md` +- **Feature management**: Load `references/guides/feature-management-quick.md` +- **Brownfield workflow**: Return to `references/workflows/brownfield-quick-start.md` diff --git a/references/templates/10-point-summary-template.md b/references/templates/10-point-summary-template.md new file mode 100644 index 0000000..f63dd8d --- /dev/null +++ b/references/templates/10-point-summary-template.md @@ -0,0 +1,208 @@ +# 10-Point Summary Template + +Use this template after ANY SDD command completes to summarize generated artifacts and keep users engaged. + +## Template Structure + +```markdown +## [Artifact Name] Summary + +### 🎯 What Was Created +[1-2 sentences describing the artifact that was generated] + +### 🔑 Key Decisions +1. **[Decision Category]**: [Brief decision made] +2. **[Decision Category]**: [Brief decision made] +3. **[Decision Category]**: [Brief decision made] + +### 📋 Main Sections +- **[Section Name]**: [1-line summary of section content] +- **[Section Name]**: [1-line summary of section content] +- **[Section Name]**: [1-line summary of section content] + +### ⚡ Highlights +- [Most important point from artifact] +- [Second most important point] +- [Third most important point] + +### 🔄 Next Step +[Clear statement of what happens next in the workflow] + +### 💬 Your Feedback +Would you like to: +- **[A] Proceed** - Continue to next step +- **[B] Modify** - Adjust something in this artifact +- **[C] Regenerate** - Start this step over with different input +- **[D] Explain** - Get more details about a specific section +``` + +--- + +## Example: Constitution Summary + +```markdown +## Constitution Summary + +### 🎯 What Was Created +Generated .speckit/constitution.md defining your project's core principles, coding standards, and quality expectations. + +### 🔑 Key Decisions +1. **Testing Strategy**: All features require unit tests with 80%+ coverage +2. **Code Style**: TypeScript strict mode, ESLint + Prettier enforcement +3. **Architecture**: Component-based with clear separation of concerns + +### 📋 Main Sections +- **Core Principles**: Simplicity, testability, maintainability prioritized +- **Technology Constraints**: React 18+, TypeScript 5+, Vite build tool +- **Quality Standards**: Automated testing, code review, continuous integration + +### ⚡ Highlights +- Every feature must be testable in isolation +- Dependencies kept minimal (review any new dependency) +- Performance: Target <100ms initial load, <16ms frame time + +### 🔄 Next Step +Run `/speckit.specify` to define your first feature requirements. + +### 💬 Your Feedback +Would you like to: +- **[A] Proceed** - Move to feature specification +- **[B] Modify** - Adjust principles or standards +- **[C] Regenerate** - Rewrite constitution with different focus +- **[D] Explain** - Get details about any section +``` + +--- + +## Example: Specification Summary + +```markdown +## Feature Specification Summary + +### 🎯 What Was Created +Generated .speckit/features/001-photo-albums/specify.md with functional requirements for photo organization feature. + +### 🔑 Key Decisions +1. **Core Functionality**: Album creation, photo upload, drag-and-drop reorganization +2. **User Experience**: Tile-based preview, date-based grouping, responsive layout +3. **Data Model**: Albums, Photos, Tags (many-to-many relationships) + +### 📋 Main Sections +- **User Stories**: 5 stories covering album creation, photo management, organization +- **Functional Requirements**: 12 requirements for core feature behavior +- **Success Criteria**: Measurable goals (upload <2s, drag latency <100ms) +- **Constraints**: Browser compatibility, storage limits, image formats + +### ⚡ Highlights +- Support up to 10,000 photos per album +- Lazy loading for performance with large albums +- Offline mode with local-first architecture + +### 🔄 Next Step +Run `/speckit.plan` to create technical implementation plan. + +### 💬 Your Feedback +Would you like to: +- **[A] Proceed** - Move to technical planning +- **[B] Modify** - Adjust requirements or user stories +- **[C] Regenerate** - Rewrite spec with different focus +- **[D] Explain** - Get details about specific requirements +``` + +--- + +## Example: Plan Summary + +```markdown +## Technical Plan Summary + +### 🎯 What Was Created +Generated .speckit/features/001-photo-albums/plan.md with technical architecture and implementation strategy. + +### 🔑 Key Decisions +1. **Tech Stack**: React + TypeScript + Vite + Tailwind CSS +2. **State Management**: Zustand for client state, IndexedDB for persistence +3. **File Handling**: FileReader API + Canvas API for image processing + +### 📋 Main Sections +- **Architecture**: Component hierarchy, data flow, state management +- **Key Technologies**: Full stack with rationale for each choice +- **Dependencies**: 8 npm packages (react, zustand, dnd-kit, etc.) +- **Implementation Phases**: 4 phases (scaffolding, core UI, drag-drop, optimization) + +### ⚡ Highlights +- Local-first: All data in IndexedDB, no backend required +- Performance: Virtual scrolling for 10k+ photos +- Accessibility: Full keyboard navigation, ARIA labels + +### 🔄 Next Step +Run `/speckit.tasks` to break down implementation into actionable tasks. + +### 💬 Your Feedback +Would you like to: +- **[A] Proceed** - Move to task breakdown +- **[B] Modify** - Adjust tech choices or architecture +- **[C] Regenerate** - Redesign with different stack +- **[D] Explain** - Get details about specific technologies +``` + +--- + +## Example: Tasks Summary + +```markdown +## Task Breakdown Summary + +### 🎯 What Was Created +Generated .speckit/features/001-photo-albums/tasks.md with 24 actionable tasks organized into 4 categories. + +### 🔑 Key Decisions +1. **Task Sequencing**: Scaffolding → UI → Drag-Drop → Polish +2. **Complexity Estimates**: 8 simple, 12 medium, 4 complex tasks +3. **Testing Strategy**: Unit tests + integration tests for each category + +### 📋 Main Sections +- **Scaffolding** (Tasks 1-6): Project setup, dependencies, folder structure +- **Core UI** (Tasks 7-14): Components for albums, photos, previews +- **Drag & Drop** (Tasks 15-19): dnd-kit integration, reordering logic +- **Polish & Testing** (Tasks 20-24): Performance, accessibility, tests + +### ⚡ Highlights +- Task 1: Initialize Vite + React + TypeScript project +- Task 10: Build photo tile component with lazy loading +- Task 15: Implement drag-and-drop with dnd-kit +- Task 24: End-to-end testing with 10k photos + +### 🔄 Next Step +Run `/speckit.implement` to execute all tasks and build the feature. + +### 💬 Your Feedback +Would you like to: +- **[A] Proceed** - Start implementation +- **[B] Modify** - Adjust task breakdown or sequencing +- **[C] Regenerate** - Reorganize tasks differently +- **[D] Explain** - Get details about specific tasks +``` + +--- + +## Usage Notes + +### When to Use This Template +- **After `/speckit.constitution`** - Summarize constitution.md +- **After `/speckit.specify`** - Summarize specify.md +- **After `/speckit.plan`** - Summarize plan.md +- **After `/speckit.tasks`** - Summarize tasks.md +- **After brownfield commands** - Summarize analysis, integration plan, etc. + +### Customization +- Adjust the 🔑 Key Decisions count (2-5 decisions typical) +- Expand/contract 📋 Main Sections based on artifact complexity +- Always include ⚡ Highlights (3 most important points) +- Always provide 💬 Your Feedback options (A/B/C/D) + +### Benefits +- **Keeps users engaged** - No "black box" AI behavior +- **Enables early feedback** - Catch issues before implementation +- **Maintains agility** - Quick review without deep dive +- **Builds trust** - Transparent reasoning and decision-making diff --git a/references/templates/command-reference.md b/references/templates/command-reference.md new file mode 100644 index 0000000..ed9c34d --- /dev/null +++ b/references/templates/command-reference.md @@ -0,0 +1,212 @@ +# SDD Command Reference + +Quick reference for all Spec-Kit slash commands. + +## Core Workflow Commands + +### Greenfield (New Projects) + +| Command | Purpose | When to Use | Generates | +|---------|---------|-------------|-----------| +| `/speckit.constitution` | Define project principles | After `specify init`, before first feature | `.speckit/constitution.md` | +| `/speckit.specify` | Define feature requirements | After constitution, for each new feature | `.speckit/features/NNN-name/specify.md` | +| `/speckit.plan` | Create technical plan | After specify | `.speckit/features/NNN-name/plan.md` | +| `/speckit.tasks` | Break down into tasks | After plan | `.speckit/features/NNN-name/tasks.md` | +| `/speckit.implement` | Execute implementation | After tasks | Working code | + +**Typical greenfield flow**: +```bash +specify init my-project --ai claude +# Then in AI agent: +/speckit.constitution +/speckit.specify +/speckit.plan +/speckit.tasks +/speckit.implement +``` + +--- + +### Brownfield (Existing Projects) + +| Command | Purpose | When to Use | Generates | +|---------|---------|-------------|-----------| +| `/speckit.brownfield` | Analyze existing codebase | Before init, to understand current state | Analysis report | +| `/speckit.analyze-codebase` | Generate constitution from code | After `specify init --here` | `.speckit/constitution.md` | +| `/speckit.reverse-engineer` | Document existing features | After constitution, to document legacy code | Specs for existing features | +| `/speckit.integration-plan` | Plan integration with existing code | After specify, before tasks | Integration strategy | + +**Typical brownfield flow**: +```bash +# In existing project directory: +/speckit.brownfield # Analyze first +specify init --here --force # Initialize in current dir +/speckit.analyze-codebase # Generate constitution +/speckit.specify # New feature spec +/speckit.integration-plan # How it integrates +/speckit.tasks # Break down (includes integration tasks) +/speckit.implement # Execute +``` + +--- + +## Optional Enhancement Commands + +| Command | Purpose | When to Use | +|---------|---------|-------------| +| `/speckit.clarify` | Identify ambiguous requirements | After specify, before plan | +| `/speckit.analyze` | Check consistency & coverage | After tasks, before implement | +| `/speckit.checklist` | Generate quality checklists | Any time for validation | + +--- + +## Validation Commands + +| Command | Purpose | When to Use | +|---------|---------|-------------| +| `/speckit.validate-reverse-engineering` | Verify reverse-engineered specs | After reverse-engineer (brownfield) | +| `/speckit.coverage-check` | Check documentation coverage | After reverse-engineer (brownfield) | +| `/speckit.validate-constitution` | Verify constitution consistency | After any constitution generation | +| `/speckit.trace [feature]` | Map specs to code | After implementation | + +--- + +## Feature Management Commands + +These are natural language interactions, not slash commands: + +| Action | What to Say | Effect | +|--------|-------------|--------| +| Add feature | "Add a new feature for [description]" | Adds to feature pipeline | +| Reorder | "Move [feature-x] before [feature-y]" | Reorders pipeline | +| Remove | "Remove [feature-name]" | Removes from pipeline | +| Show status | "Show feature status" or "What's the progress?" | Displays dashboard | +| Switch feature | "Let's work on [feature-name] next" | Changes active feature | + +--- + +## CLI Commands (Not Slash Commands) + +These are terminal commands, not AI agent commands: + +| Command | Purpose | When to Use | +|---------|---------|-------------| +| `specify init [project] --ai [agent]` | Initialize new project | Starting new greenfield project | +| `specify init --here --force --ai [agent]` | Initialize in existing dir | Starting brownfield in existing project | +| `specify check` | Verify installation | After installing specify-cli | +| `uv tool install specify-cli --from git+https://github.com/github/spec-kit.git` | Install specify-cli | Initial setup | + +--- + +## Command Arguments + +### Common Arguments + +**AI Agent Selection** (`--ai [agent]`): +- `--ai claude` - Claude Code +- `--ai copilot` - GitHub Copilot +- `--ai cursor` - Cursor +- `--ai windsurf` - Windsurf +- `--ai gemini` - Gemini CLI +- (See full list in installation guide) + +**Initialization Flags**: +- `--here` - Initialize in current directory (don't create subdirectory) +- `--force` - Override warnings about existing files +- `--ai [agent]` - Specify which AI agent you're using + +--- + +## Command Aliases + +Some commands have shorter aliases: + +| Full Command | Alias | Notes | +|--------------|-------|-------| +| `/speckit.constitution` | `/constitution` | If configured | +| `/speckit.specify` | `/specify` | If configured | +| `/speckit.plan` | `/plan` | If configured | +| `/speckit.tasks` | `/tasks` | If configured | +| `/speckit.implement` | `/implement` | If configured | + +**Note**: Aliases depend on your AI agent's configuration. Use full `/speckit.*` commands if unsure. + +--- + +## Command Chaining + +You can sometimes chain commands by providing explicit instructions: + +``` +/speckit.specify Create a user authentication feature with OAuth2 support + +# Then immediately: +/speckit.plan Use JWT tokens, Passport.js, and PostgreSQL for user storage +``` + +However, **best practice** is to wait for each command to complete, review the generated artifact, and then proceed to the next step. + +--- + +## Error Recovery Commands + +If something goes wrong: + +| Problem | Solution | +|---------|----------| +| Command not recognized | Verify `specify init` was run, restart AI agent | +| Artifacts not generated | Check `.speckit/` directory exists, verify write permissions | +| Constitution conflicts | Edit `.speckit/constitution.md` manually, re-run `/speckit.analyze` | +| Implementation fails | Check prerequisites (tools installed), review task clarity, verify constitution | +| Integration conflicts | Load `references/guides/integration-planning.md`, consider adapter layer | + +--- + +## Command Availability by AI Agent + +| Command Type | Claude Code | Copilot | Cursor | Windsurf | Gemini CLI | Amazon Q | +|--------------|-------------|---------|--------|----------|------------|----------| +| `/speckit.*` slash commands | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes | ⚠️ Limited | +| Custom arguments | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes | ❌ No | +| Natural language feature mgmt | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes | + +**Amazon Q Note**: Amazon Q Developer CLI doesn't support custom arguments for slash commands. Use alternative phrasing or manual workflow steps. + +--- + +## Quick Reference Tables + +### By Project Type + +**Greenfield** (6 steps): +``` +init → constitution → specify → plan → tasks → implement +``` + +**Brownfield** (7-8 steps): +``` +brownfield → init --here → analyze-codebase → [optional: reverse-engineer] → +specify → integration-plan → tasks → implement +``` + +### By Phase + +| Phase | Greenfield Command | Brownfield Command | +|-------|-------------------|-------------------| +| Setup | `specify init` | `specify init --here --force` | +| Principles | `/speckit.constitution` | `/speckit.analyze-codebase` | +| Discovery | - | `/speckit.brownfield`, `/speckit.reverse-engineer` | +| Requirements | `/speckit.specify` | `/speckit.specify` | +| Planning | `/speckit.plan` | `/speckit.integration-plan` | +| Breakdown | `/speckit.tasks` | `/speckit.tasks` | +| Execution | `/speckit.implement` | `/speckit.implement` | + +--- + +## Resources + +- **Installation Guide**: `references/sdd_install.md` +- **Greenfield Workflow**: `references/workflows/greenfield-quick-start.md` +- **Brownfield Workflow**: `references/workflows/brownfield-quick-start.md` +- **GitHub Spec-Kit**: https://github.com/github/spec-kit +- **Feature Management**: `references/guides/feature-management-quick.md` diff --git a/references/templates/feature-status-brief.md b/references/templates/feature-status-brief.md new file mode 100644 index 0000000..6522625 --- /dev/null +++ b/references/templates/feature-status-brief.md @@ -0,0 +1,122 @@ +# Feature Status Brief Template + +Concise single-line status format for embedding in summaries after SDD commands. + +## Template Format + +```markdown +📊 Feature Status: [current-feature] ([phase]) → Next: [next-feature] +Progress: [●●●○○] [percentage]% | Completed: [X] of [Y] features +``` + +--- + +## Examples + +### Single Feature In Progress +```markdown +📊 Feature Status: photo-albums (Planning) → Next: None +Progress: [●●○○○] 40% | Completed: 0 of 1 feature +``` + +### Multiple Features - Constitution Phase +```markdown +📊 Feature Status: user-authentication (Constitution) → Next: photo-albums, social-sharing +Progress: [●○○○○] 20% | Completed: 0 of 3 features +``` + +### Multiple Features - Mid-Implementation +```markdown +📊 Feature Status: photo-albums (Tasks) → Next: user-authentication, social-sharing +Progress: [●●●●○] 80% | Completed: 0 of 3 features +``` + +### One Feature Complete, Others Pending +```markdown +📊 Feature Status: user-authentication (Specify) → Next: photo-albums, social-sharing +Progress: [●●●○○○] 50% | Completed: 1 of 3 features +``` + +### All Features Complete +```markdown +📊 Feature Status: All features complete ✅ +Progress: [●●●●●] 100% | Completed: 3 of 3 features +``` + +--- + +## Phase Labels + +Use these phase labels based on the last completed command: + +- **Constitution** - After `/speckit.constitution` +- **Specified** - After `/speckit.specify` +- **Planned** - After `/speckit.plan` +- **Tasks Ready** - After `/speckit.tasks` +- **In Progress** - During `/speckit.implement` +- **Complete** - After `/speckit.implement` finishes successfully + +### Brownfield-Specific Phases +- **Analyzed** - After `/speckit.brownfield` or `/speckit.analyze-codebase` +- **Reverse-Engineered** - After `/speckit.reverse-engineer` +- **Integration Planned** - After `/speckit.integration-plan` + +--- + +## Progress Bar Rules + +Calculate progress based on workflow completion: + +**Greenfield (6 steps)**: +- Constitution: 1/6 = 17% → [●○○○○○] +- Specify: 2/6 = 33% → [●●○○○○] +- Plan: 3/6 = 50% → [●●●○○○] +- Tasks: 4/6 = 67% → [●●●●○○] +- Implement start: 5/6 = 83% → [●●●●●○] +- Implement complete: 6/6 = 100% → [●●●●●●] + +**Brownfield (8 steps including analysis)**: +- Analyze: 1/8 = 12% → [●○○○○○○○] +- Constitution: 2/8 = 25% → [●●○○○○○○] +- Reverse-engineer: 3/8 = 37% → [●●●○○○○○] +- Specify: 4/8 = 50% → [●●●●○○○○] +- Integration plan: 5/8 = 62% → [●●●●●○○○] +- Tasks: 6/8 = 75% → [●●●●●●○○] +- Implement start: 7/8 = 87% → [●●●●●●●○] +- Implement complete: 8/8 = 100% → [●●●●●●●●] + +**Multiple Features**: +- Average progress across all features +- Example: Feature 1 (100%), Feature 2 (50%), Feature 3 (0%) → Average = 50% + +--- + +## When to Show Status + +### Always Show +- After any `/speckit.*` command completes +- When user asks about progress or status +- When switching between features + +### Don't Show +- During initial installation +- When no features have been specified yet +- When answering general questions about SDD methodology + +--- + +## Usage in Summaries + +Place the status line at the TOP of every summary after SDD commands: + +```markdown +## Constitution Summary + +📊 Feature Status: photo-albums (Constitution) → Next: user-authentication +Progress: [●○○○○○] 17% | Completed: 0 of 2 features + +### 🎯 What Was Created +[rest of summary...] +``` + +This keeps users oriented about overall project progress while reviewing specific artifacts. diff --git a/references/templates/feature-status-dashboard.md b/references/templates/feature-status-dashboard.md new file mode 100644 index 0000000..6f3dded --- /dev/null +++ b/references/templates/feature-status-dashboard.md @@ -0,0 +1,231 @@ +# Feature Status Dashboard Template + +Detailed multi-feature status display for when users request comprehensive progress overview. + +## Template Format + +```markdown +## Feature Status Dashboard + +### 📊 Overall Progress +[●●●○○○] 50% Complete | 1 of 3 features delivered + +--- + +### 🎯 Current Feature: [feature-name] +**Phase**: [phase-name] ([X] of [Y] steps complete) +**Started**: [date or "just now"] +**Status**: [In Progress | Blocked | Ready for Next Step] + +**Artifacts Generated**: +- ✅ constitution.md +- ✅ specify.md +- ✅ plan.md +- ⏳ tasks.md (in progress) +- ⏹️ implementation (not started) + +**Next Action**: [Specific command to run next] + +--- + +### 📋 Feature Pipeline + +| Feature | Phase | Progress | Status | +|---------|-------|----------|--------| +| [Feature 1] | [Phase] | [●●●●●●] 100% | ✅ Complete | +| [Feature 2] | [Phase] | [●●●○○○] 50% | 🔄 Active | +| [Feature 3] | [Phase] | [○○○○○○] 0% | ⏹️ Queued | + +--- + +### 🔗 Dependencies +[If any features depend on others, show dependency graph or list] + +**Example**: +- `social-sharing` depends on `user-authentication` (must complete first) +- `photo-albums` can be built in parallel + +--- + +### ⚠️ Blockers +[List any blockers or issues preventing progress] + +**Example**: +- Waiting for API key setup before implementing authentication +- Design review needed for social-sharing UI mockups + +--- + +### 📅 Timeline (if applicable) +- **Week 1**: photo-albums (complete ✅) +- **Week 2**: user-authentication (in progress 🔄) +- **Week 3**: social-sharing (queued ⏹️) +``` + +--- + +## Example: Mid-Project Dashboard + +```markdown +## Feature Status Dashboard + +### 📊 Overall Progress +[●●●●○○] 67% Complete | 1 of 3 features delivered + +--- + +### 🎯 Current Feature: user-authentication +**Phase**: Planning (3 of 6 steps complete) +**Started**: 2 hours ago +**Status**: Ready for Next Step + +**Artifacts Generated**: +- ✅ constitution.md (shared across all features) +- ✅ specify.md (requirements documented) +- ✅ plan.md (tech stack: JWT + OAuth2) +- ⏹️ tasks.md (not started) +- ⏹️ implementation (not started) + +**Next Action**: Run `/speckit.tasks` to break down implementation + +--- + +### 📋 Feature Pipeline + +| Feature | Phase | Progress | Status | +|---------|-------|----------|--------| +| photo-albums | Implemented | [●●●●●●] 100% | ✅ Complete | +| user-authentication | Planning | [●●●○○○] 50% | 🔄 Active | +| social-sharing | Queued | [○○○○○○] 0% | ⏹️ Queued | + +--- + +### 🔗 Dependencies +- `social-sharing` depends on `user-authentication` (blocked until auth complete) +- `photo-albums` was independent (completed first) + +**Recommendation**: Complete user-authentication before starting social-sharing to avoid rework. + +--- + +### ⚠️ Blockers +No blockers currently. All dependencies available, tools installed, environment ready. + +--- + +### 📅 Timeline +- **Day 1**: photo-albums (complete ✅) +- **Day 2**: user-authentication (in progress 🔄) +- **Day 3**: social-sharing (planned ⏹️) +``` + +--- + +## Example: Project Start Dashboard + +```markdown +## Feature Status Dashboard + +### 📊 Overall Progress +[●○○○○○] 17% Complete | 0 of 3 features delivered + +--- + +### 🎯 Current Feature: photo-albums +**Phase**: Constitution (1 of 6 steps complete) +**Started**: Just now +**Status**: Ready for Next Step + +**Artifacts Generated**: +- ✅ constitution.md (project principles defined) +- ⏹️ specify.md (not started) +- ⏹️ plan.md (not started) +- ⏹️ tasks.md (not started) +- ⏹️ implementation (not started) + +**Next Action**: Run `/speckit.specify` to define photo-albums requirements + +--- + +### 📋 Feature Pipeline + +| Feature | Phase | Progress | Status | +|---------|-------|----------|--------| +| photo-albums | Constitution | [●○○○○○] 17% | 🔄 Active | +| user-authentication | Queued | [○○○○○○] 0% | ⏹️ Queued | +| social-sharing | Queued | [○○○○○○] 0% | ⏹️ Queued | + +--- + +### 🔗 Dependencies +- No dependencies yet (all features can be built independently) +- Will reassess after specifications are complete + +--- + +### ⚠️ Blockers +No blockers. Project just initialized, ready to proceed. + +--- + +### 📅 Timeline +**Estimated** (based on 6-step workflow per feature): +- **Today**: photo-albums specification + planning +- **Tomorrow**: photo-albums implementation +- **This week**: All 3 features complete +``` + +--- + +## When to Show Dashboard + +### Show Full Dashboard When: +- User explicitly asks: "show feature status", "what's the progress", "show dashboard" +- User selects option **[D] Status** from feedback options +- Switching context between multiple features +- At project milestones (first feature complete, halfway through pipeline, etc.) + +### Don't Show Dashboard When: +- After routine command completion (use brief status instead) +- During installation or setup +- When answering methodology questions +- In the middle of active implementation (would interrupt flow) + +--- + +## Customization Options + +### Minimal Dashboard (2 features or less) +Omit the "Feature Pipeline" table, just show current feature details and next feature. + +### Large Projects (5+ features) +- Group features by category or epic +- Show only top 5 in pipeline, link to full list +- Add filtering options (by status, by dependency, by timeline) + +### Brownfield Projects +Add additional sections: +- **Legacy Code Analysis**: Summary of existing codebase findings +- **Integration Points**: Where new features touch existing code +- **Migration Progress**: If modernizing legacy features + +--- + +## Usage Notes + +**Placement**: Show dashboard in response to status requests, not automatically embedded in summaries (too verbose). + +**Update Frequency**: Update whenever feature status changes (phase transition, completion, blocking issue). + +**Link to Brief**: Always offer brief status line as alternative for users who want quick summary. + +Example response pattern: +```markdown +Here's your complete feature status dashboard: + +[Full dashboard content] + +--- + +**TL;DR**: [brief status line from feature-status-brief.md] +``` diff --git a/references/workflows/brownfield-quick-start.md b/references/workflows/brownfield-quick-start.md new file mode 100644 index 0000000..475758f --- /dev/null +++ b/references/workflows/brownfield-quick-start.md @@ -0,0 +1,307 @@ +# Brownfield Workflow Quick Start + +## Token Budget + +**Tier 1**: 100 tokens (already loaded) +**Tier 2**: 2,000 tokens (already loaded) +**Tier 3 (this guide)**: ~1,500 tokens + +**Additional resources available**: +- Codebase analysis: `references/guides/codebase-analysis.md` (+1,250 tokens) +- Reverse engineering: `references/guides/reverse-engineering.md` (+1,250 tokens) +- Integration planning: `references/guides/integration-planning.md` (+1,250 tokens) + +**Current total**: 3,600 tokens +**Remaining budget**: 6,400 tokens ✅ + +--- + +## When to Use Brownfield Workflow + +Use this workflow when: +- Adding features to an existing codebase +- Modernizing or refactoring legacy systems +- Adopting SDD methodology in an ongoing project +- Reverse-engineering existing code into SDD format +- Migrating from traditional development to spec-driven + +**For new projects from scratch**, use [Greenfield Workflow](greenfield-quick-start.md) instead. + +--- + +## The 7-Step Workflow + +### Step 1: Analyze Existing Codebase + +``` +/speckit.brownfield +``` + +**Purpose**: Analyze existing code to understand architecture, patterns, and tech stack. + +**What this does**: Scans codebase and identifies: +- Architecture and design patterns +- Technology stack and dependencies +- Coding standards and conventions +- Technical debt and opportunities + +**After this command**: Load `references/templates/10-point-summary-template.md` and summarize analysis. + +→ **For analysis depth options**, load `references/guides/codebase-analysis.md` + +--- + +### Step 2: Initialize SDD in Existing Project + +```bash +specify init --here --force +``` + +**What this does**: Creates `.speckit/` directory structure in existing project without conflicting with existing files. + +**Flags explained**: +- `--here`: Initialize in current directory +- `--force`: Override warnings about existing files + +--- + +### Step 3: Generate Constitution from Existing Code + +``` +/speckit.analyze-codebase +``` + +**Purpose**: Create constitution.md that acknowledges existing patterns and standards. + +**What gets created**: `.speckit/constitution.md` with: +- Architectural principles (derived from existing code) +- Established patterns and conventions +- Technology constraints and standards +- Future direction or planned migrations + +**After this command**: Load `references/templates/10-point-summary-template.md` and summarize. + +--- + +### Step 4: Choose Documentation Strategy + +**Interactive decision point** - Choose based on your needs: + +#### Option A: Constitution Only +Generate constitution.md only, use for new features going forward. +→ **Best for**: Teams adopting SDD for future work only. + +#### Option B: Constitution + Baseline Specs +Generate constitution.md and high-level specs for existing major features. +→ **Best for**: Partial documentation, focus on key features. + +#### Option C: Full Reverse-Engineering +Document all existing features comprehensively. +→ **Best for**: Complete documentation, migration to SDD. + +--- + +### Step 5: Reverse-Engineer (Optional) + +``` +/speckit.reverse-engineer +``` + +**Purpose**: Document existing features in SDD format. + +**What gets created**: For each discovered feature: +- `specify.md`: Requirements reverse-engineered from code +- Mapping to existing code files +- Integration points + +**After this command**: Load `references/templates/10-point-summary-template.md` and summarize. + +→ **For detailed guidance**, load `references/guides/reverse-engineering.md` + +--- + +### Step 6: Specify New Feature + +``` +/speckit.specify +``` + +**Purpose**: Define new feature to add to existing codebase. + +**Same as greenfield**, but emphasize: +- Integration points with existing code +- Dependencies on existing features +- Constraints from existing architecture + +**After this command**: Load `references/templates/10-point-summary-template.md` and summarize. + +--- + +### Step 7a: Create Integration Plan + +``` +/speckit.integration-plan +``` + +**Purpose**: Plan how new feature integrates with existing codebase. + +**What gets created**: Integration plan with: +- Integration points (where new code touches existing) +- Required modifications to existing code +- Sequencing and dependencies +- Risk assessment + +**After this command**: Load `references/templates/10-point-summary-template.md` and summarize. + +→ **For integration strategies**, load `references/guides/integration-planning.md` + +--- + +### Step 7b: Break Down into Tasks + +``` +/speckit.tasks +``` + +**Purpose**: Create task list including both new code and integration work. + +**Brownfield-specific tasks include**: +- Integration tasks (modifying existing files) +- Compatibility tasks (ensuring new code works with old) +- Migration tasks (if refactoring existing code) + +**After this command**: Load `references/templates/10-point-summary-template.md` and summarize. + +--- + +### Step 8: Execute Implementation + +``` +/speckit.implement +``` + +**Purpose**: Execute all tasks including integration work. + +**Brownfield considerations**: +- Respect existing patterns +- Minimize breaking changes +- Test integration thoroughly +- Consider gradual rollout + +--- + +## Analysis Depth Options + +### Surface Analysis (~5 min) +- File structure and organization +- Technology stack identification +- Basic pattern recognition + +→ **Choose when**: Quick overview needed, small codebase + +### Moderate Analysis (~15 min) +- Architecture patterns in detail +- Coding standards extraction +- Dependency mapping +- Technical debt identification + +→ **Choose when**: Standard brownfield adoption, medium codebase + +### Deep Analysis (~30+ min) +- Comprehensive feature inventory +- Complete reverse-engineering +- Integration point mapping +- Performance baseline + +→ **Choose when**: Large migration, enterprise adoption, complex codebase + +→ **For choosing depth**, load `references/guides/codebase-analysis.md` + +--- + +## Validation Commands + +After documenting existing code, validate the reverse-engineering: + +``` +/speckit.validate-reverse-engineering # Verify spec accuracy +/speckit.coverage-check # Check documentation coverage +/speckit.validate-constitution # Verify constitution consistency +/speckit.trace [feature] # Map specs to code +``` + +--- + +## Common Brownfield Scenarios + +### Scenario 1: Add Single Feature to Existing App +``` +/speckit.brownfield # Analyze +specify init --here --force # Initialize +/speckit.analyze-codebase # Generate constitution +/speckit.specify # Specify new feature +/speckit.integration-plan # Plan integration +/speckit.tasks # Break down +/speckit.implement # Execute +``` + +### Scenario 2: Modernize Legacy System +``` +/speckit.brownfield # Deep analysis +/speckit.reverse-engineer # Document existing +/speckit.specify # Modern replacement feature +/speckit.integration-plan # Migration strategy +/speckit.tasks # Include migration tasks +``` + +### Scenario 3: Extract Microservice +``` +/speckit.brownfield # Analyze monolith +/speckit.reverse-engineer # Document target functionality +/speckit.specify # New microservice spec +/speckit.integration-plan # Service boundaries, API contracts +/speckit.tasks # Extraction + integration tasks +``` + +--- + +## Best Practices for Brownfield + +1. **Respect existing patterns** - Constitution should acknowledge current architecture +2. **Incremental adoption** - Don't try to document everything at once +3. **Focus on integration** - New features must play well with existing code +4. **Test thoroughly** - Integration points are high-risk areas +5. **Gradual refactoring** - Use new features to gradually improve architecture + +--- + +## Troubleshooting + +**If analysis fails**: +1. Check if codebase too large (>100k lines may need manual scoping) +2. Verify read permissions on all files +3. Try surface analysis first, then moderate + +**If integration conflicts**: +1. Review constitution for architecture constraints +2. Load `references/guides/integration-planning.md` for strategies +3. Consider creating adapter layer + +**If unclear about strategy**: +1. Start with Constitution Only (Option A) +2. Add reverse-engineering later if needed +3. Focus on new features first + +--- + +## Related Resources + +**Need more details?** +- Codebase analysis strategies: `references/guides/codebase-analysis.md` +- Reverse-engineering guide: `references/guides/reverse-engineering.md` +- Integration planning: `references/guides/integration-planning.md` +- Summary template: `references/templates/10-point-summary-template.md` +- Feature management: `references/guides/feature-management-quick.md` + +**New project**: `references/workflows/greenfield-quick-start.md` +**Installation help**: `references/sdd_install.md` diff --git a/references/workflows/greenfield-quick-start.md b/references/workflows/greenfield-quick-start.md new file mode 100644 index 0000000..e3de8a6 --- /dev/null +++ b/references/workflows/greenfield-quick-start.md @@ -0,0 +1,247 @@ +# Greenfield Workflow Quick Start + +## Token Budget + +**Tier 1**: 100 tokens (already loaded) +**Tier 2**: 2,000 tokens (already loaded) +**Tier 3 (this guide)**: ~1,500 tokens + +**Additional resources available**: +- Step details: `references/guides/greenfield-step-details.md` (+750 tokens) +- Examples: `references/examples/greenfield-examples.md` (+500 tokens) +- 10-point summary template: `references/templates/10-point-summary-template.md` (+500 tokens) + +**Current total**: 3,600 tokens +**Remaining budget**: 6,400 tokens ✅ + +--- + +## When to Use Greenfield Workflow + +Use this workflow when: +- Starting a brand new project (0-to-1 development) +- Building a proof-of-concept or prototype +- Creating a new microservice or application component +- No existing codebase exists yet + +**For existing codebases**, use [Brownfield Workflow](brownfield-quick-start.md) instead. + +--- + +## The 6-Step Workflow + +### Step 1: Initialize Project + +```bash +# Basic initialization +specify init my-project --ai claude + +# Or in current directory +specify init --here --ai claude +``` + +**What this does**: Creates `.speckit/` directory structure and sets up slash commands for your AI agent. + +--- + +### Step 2: Establish Project Principles + +``` +/speckit.constitution +``` + +**Purpose**: Define project's governing principles and development guidelines. + +**Example prompt**: +``` +/speckit.constitution Create principles focused on code quality, testing standards, user experience consistency, and performance requirements +``` + +**What gets created**: `.speckit/constitution.md` with: +- Core development principles +- Coding standards and conventions +- Testing requirements +- Quality expectations + +**After this command**: Load `references/templates/10-point-summary-template.md` and summarize the constitution. + +--- + +### Step 3: Create the Specification + +``` +/speckit.specify +``` + +**Purpose**: Describe WHAT to build (focus on requirements, not tech stack). + +**Example prompt**: +``` +/speckit.specify Build an application that helps me organize photos in albums. Albums are grouped by date and can be reorganized by drag-and-drop. Within each album, photos are previewed in a tile interface. +``` + +**What gets created**: `.speckit/features/[number]-[name]/specify.md` with: +- Functional requirements +- User stories +- Success criteria +- Constraints + +**After this command**: +1. Load `references/templates/10-point-summary-template.md` and summarize +2. Ask: "Do you have multiple features planned?" (for feature tracking) + +--- + +### Step 4: Create Technical Implementation Plan + +``` +/speckit.plan +``` + +**Purpose**: Define HOW to build it (tech stack, architecture, dependencies). + +**Example prompt**: +``` +/speckit.plan Use React with TypeScript, Vite build tool, and Tailwind CSS. Keep dependencies minimal. Use local storage for data. +``` + +**What gets created**: `.speckit/features/[number]-[name]/plan.md` with: +- Technology stack choices +- Architecture decisions +- Key dependencies +- Implementation phases + +**After this command**: Load `references/templates/10-point-summary-template.md` and summarize. + +--- + +### Step 5: Break Down into Tasks + +``` +/speckit.tasks +``` + +**Purpose**: Create actionable task list from the implementation plan. + +**What gets created**: `.speckit/features/[number]-[name]/tasks.md` with: +- Numbered task list +- Task categories (UI, backend, testing, etc.) +- Dependencies between tasks +- Complexity estimates + +**After this command**: Load `references/templates/10-point-summary-template.md` and summarize. + +--- + +### Step 6: Execute Implementation + +``` +/speckit.implement +``` + +**Purpose**: Execute all tasks and build the feature. + +**What happens**: AI agent works through the task list, writing code according to the plan and constitution. + +--- + +## Optional Enhancement Commands + +Use these for additional quality and validation: + +### Clarify Underspecified Areas + +``` +/speckit.clarify +``` + +**When**: After `/speckit.specify`, before `/speckit.plan` +**Purpose**: Identify and clarify ambiguous requirements + +### Analyze Consistency & Coverage + +``` +/speckit.analyze +``` + +**When**: After `/speckit.tasks`, before `/speckit.implement` +**Purpose**: Cross-artifact consistency and coverage analysis +**Uses**: Analysis scripts from `scripts/` directory + +### Generate Quality Checklists + +``` +/speckit.checklist +``` + +**Purpose**: Create custom quality checklists for validation + +--- + +## Managing Multiple Features + +**After specifying first feature**, if you have more features planned: + +1. Tell Claude about all features: "I also want to build [feature 2], [feature 3]" +2. Claude will track them automatically +3. You'll see feature status in every summary: + ``` + 📊 Feature Status: photo-albums (Planned) → Next: user-authentication + Progress: [●●○○○] 40% | Completed: 0 of 3 features + ``` + +**To manage features**: +- Add: "Add a new feature for [description]" +- Reorder: "Move feature X before Y" +- Remove: "Remove feature Z" +- Status: "Show feature status" or option [D] + +→ **For detailed feature management**, load `references/guides/feature-management-quick.md` + +--- + +## Common Questions + +**Q: Can I run multiple features in parallel?** +A: Yes, but complete one feature's workflow before starting another to maintain clarity. + +**Q: What if I need to change the constitution mid-project?** +A: Edit `.speckit/constitution.md` directly and re-run `/speckit.analyze` to check consistency. + +**Q: Can I skip steps?** +A: Not recommended. Each step builds on the previous one. Skipping steps leads to incomplete specifications. + +**Q: What if implementation fails?** +A: Check prerequisites (tools installed), verify task clarity, review constitution for conflicts. + +--- + +## Troubleshooting + +**If command not recognized**: +1. Verify `specify init` completed successfully +2. Check `.claude/commands/` directory exists +3. Restart AI agent + +**If artifacts not generated**: +1. Check `.speckit/` directory structure +2. Verify write permissions +3. Check AI agent logs for errors + +**If unclear about next step**: +1. Review the workflow overview above +2. Load `references/guides/greenfield-step-details.md` for comprehensive guidance +3. Check `references/examples/greenfield-examples.md` for examples + +--- + +## Related Resources + +**Need more details?** +- Step-by-step guide: `references/guides/greenfield-step-details.md` +- Complete examples: `references/examples/greenfield-examples.md` +- Summary template: `references/templates/10-point-summary-template.md` +- Feature management: `references/guides/feature-management-quick.md` + +**Installation help**: `references/sdd_install.md` +**Existing codebase**: `references/workflows/brownfield-quick-start.md` diff --git a/skill.md b/skill.md index d6a2051..8d73ccf 100644 --- a/skill.md +++ b/skill.md @@ -1,658 +1,290 @@ --- name: sdd -description: This skill should be used when users want guidance on Spec-Driven Development methodology using GitHub's Spec-Kit. Guide users through executable specification workflows for both new projects (greenfield) and existing codebases (brownfield). After any SDD command generates artifacts, automatically provide structured 10-point summaries with feature status tracking, enabling natural language feature management and keeping users engaged throughout the process. -version: 2.1.0 +description: Guide users through GitHub Spec-Kit for executable spec-driven development (greenfield/brownfield workflows with feature tracking). +version: 2.2.0 triggers: - - spec-driven development - - spec kit - - speckit - sdd - - specify cli - - specification driven - - github spec-kit - - /speckit - - constitution - - specify init - - executable specifications - - intent-driven development + - speckit + - spec-driven + - greenfield - brownfield - - existing codebase - - legacy code - - legacy system - - add features to existing - - modernize - - modernization - - existing project - - reverse engineer - - codebase analysis - - iterative enhancement - feature status - - track features - - add feature - - move feature - - reorder features - - feature progress - - feature dependencies -author: Based on GitHub Spec-Kit by Den Delimarsky and John Lam + - /speckit +author: Based on GitHub Spec-Kit license: MIT -tags: - - development-methodology - - ai-native-development - - spec-driven - - github - - project-management - - workflow - - requirements - - planning +tier1_token_budget: 100 +tier2_token_budget: 2000 --- # Spec-Driven Development (SDD) Skill -Guide users through GitHub's Spec-Kit for Spec-Driven Development - a methodology that flips traditional software development by making specifications executable and directly generating working implementations. +Guide users through GitHub's Spec-Kit for Spec-Driven Development - a methodology that makes specifications executable, directly generating working implementations. ## Core Philosophy Spec-Driven Development emphasizes: -- **Intent-driven development**: Define the "what" before the "how" -- **Rich specification creation**: Use guardrails and organizational principles +- **Intent-driven**: Define "what" before "how" +- **Executable specs**: Specifications drive implementation, not just document it - **Multi-step refinement**: Not one-shot code generation -- **AI-native**: Heavy reliance on advanced AI capabilities - -Remember: This is **AI-native development**. Specifications aren't just documentation - they're executable artifacts that directly drive implementation. The AI agent uses them to generate working code that matches the intent defined in the specs. +- **AI-native**: Heavy reliance on AI capabilities -## Quick Decision Tree +## Intent Classification & Routing -### Is this a new project (greenfield)? -→ **See [Greenfield Workflow](references/greenfield.md)** for the complete 6-step process +**CRITICAL**: Use decision tree to route surgically to Tier 3 resources. Load only what's needed. -### Is this an existing codebase (brownfield)? -→ **See [Brownfield Workflow](references/brownfield.md)** for reverse-engineering and integration guidance +### Step 1: Identify User Intent -### Need installation help? -→ **See [Installation Guide](references/sdd_install.md)** for setup and troubleshooting +Analyze user request and classify into ONE primary intent: -## Installation Quick Start +**NEW_PROJECT** - Triggers: +- "new project", "from scratch", "greenfield", "specify init", "start fresh" +- User has no existing codebase +- Wants to build something new -**Recommended (Persistent):** -```bash -uv tool install specify-cli --from git+https://github.com/github/spec-kit.git -``` +**EXISTING_PROJECT** - Triggers: +- "existing", "brownfield", "legacy", "add feature to existing", "current codebase" +- User has existing code +- Wants to enhance or modernize -**One-time Usage:** -```bash -uvx --from git+https://github.com/github/spec-kit.git specify init -``` +**FEATURE_MANAGEMENT** - Triggers: +- "feature status", "track features", "add feature", "move feature", "show features" +- "progress", "dependencies", "what's next" +- User managing multiple features -**Verify:** -```bash -specify check -``` +**INSTALLATION** - Triggers: +- "install", "setup", "specify check", "how to install", "prerequisites" +- User needs to set up tools -For detailed installation options, troubleshooting, and environment variables, see [Installation Guide](references/sdd_install.md). +**EXECUTE_WORKFLOW** - Triggers: +- `/speckit.constitution`, `/speckit.specify`, `/speckit.plan`, `/speckit.tasks`, `/speckit.implement` +- User executing SDD commands +- Need to provide post-command summary -## Supported AI Agents +**COMMAND_REFERENCE** - Triggers: +- "what commands", "list commands", "available commands", "slash commands" +- User needs command documentation -Works with: -- ✅ Claude Code -- ✅ GitHub Copilot -- ✅ Gemini CLI -- ✅ Cursor -- ✅ Qwen Code -- ✅ opencode -- ✅ Windsurf -- ✅ Kilo Code -- ✅ Auggie CLI -- ✅ CodeBuddy CLI -- ✅ Roo Code -- ✅ Codex CLI -- ✅ Amp -- ⚠️ Amazon Q Developer CLI (doesn't support custom arguments for slash commands) - -## Artifact Summarization and Feedback Loop - -**CRITICAL WORKFLOW**: After any SDD command generates or modifies artifacts, automatically follow this feedback loop to keep the user engaged: - -### After Each Command Completes - -1. **Detect Artifact Changes** - - Identify which artifacts were created or modified: - - `constitution.md` (project principles) - - `spec.md` (requirements specification) - - `plan.md` (technical implementation plan) - - `tasks.md` (actionable task breakdown) - - Analysis reports from brownfield workflows - -2. **Read and Summarize** - - Read the relevant artifact(s) - - Extract key information: - - **For constitution.md**: Core principles, coding standards, constraints - - **For spec.md**: Main requirements, user stories, success criteria - - **For plan.md**: Tech stack choices, architecture decisions, milestones - - **For tasks.md**: Number of tasks, major task categories, dependencies - - **For analysis reports**: Current patterns, tech debt, integration points - -3. **Present Structured Summary** (Use 10-Point Template Below) - - Show what was generated and why - - Highlight the most important decisions with rationale - - Include quality indicators and watch-outs - - Keep summary focused and actionable - - Use clear headings for each section - -4. **Include Feature Status** (Hybrid Approach) - - Brief status line in every summary - - Detailed status on demand with `/speckit.status` - - See "Feature Status Tracking" section below - -5. **Offer Feedback Options** - - **Option A**: "Looks good, proceed to next step" - - **Option B**: "I'd like to modify [specific section]" - - **Option C**: "Regenerate with these changes: [user input]" - - **Option D**: "Explain why [specific decision] was made" - -### 10-Point Summary Template - -Use this structured format after ANY SDD command completes: +### Step 2: Route to Appropriate Resources (Surgical Loading) +**For NEW_PROJECT**: ``` -## ✅ [Command Name] Completed - Here's What Just Happened - -### 🎯 Key Decisions Made (Top 3) -1. [Decision] - **Rationale:** [Why this was chosen] -2. [Decision] - **Rationale:** [Why this was chosen] -3. [Decision] - **Rationale:** [Why this was chosen] - -### 📋 What Was Generated -- [Artifact 1]: [Brief description of content] -- [Artifact 2]: [Brief description of content] - -### 🔍 Important Items to Review (Top 3) -1. [Critical item to check and why it matters] -2. [Important detail to verify and potential impact] -3. [Edge case to consider and how it affects the design] - -### ⚠️ Watch Out For (Top 2) -- [Potential issue or gotcha] - **How to avoid:** [Guidance] -- [Common mistake] - **How to avoid:** [Guidance] - -### 🔄 What This Enables Next (2 Options) -- **Option 1:** [Next step] - Best if: [Condition] -- **Option 2:** [Alternative step] - Best if: [Condition] - -📊 **Feature Status:** [Current Feature Name] ([Stage]) → Next: [Next Feature] - Progress: [●●●○○] [X]% | Completed: [N] of [Total] features | Dependencies: [Status] +1. Load: references/workflows/greenfield-quick-start.md (~300 lines, ~1,500 tokens) +2. IF user asks for step details → Load: references/guides/greenfield-step-details.md (~150 lines) +3. IF stuck or needs examples → Load: references/examples/greenfield-examples.md (~100 lines) -**Your options:** [A] Proceed [B] Modify [C] Explain more [D] Show full status +Token budget: 2,100 + 1,500 = 3,600 tokens (within budget ✅) ``` -### Example: Enhanced Summarization After \`/speckit.specify\` - -\`\`\` -## ✅ Specify Completed - Here's What Just Happened - -### 🎯 Key Decisions Made -1. **Authentication: JWT tokens** - Rationale: Stateless architecture, horizontally scalable, industry standard -2. **Password requirements: 12+ characters with complexity** - Rationale: Balances security (NIST guidelines) with usability -3. **Session timeout: 24 hours** - Rationale: Standard for web apps, balances security vs user convenience +**For EXISTING_PROJECT**: +``` +1. Load: references/workflows/brownfield-quick-start.md (~300 lines, ~1,500 tokens) +2. IF needs codebase analysis → Load: references/guides/codebase-analysis.md (~250 lines) +3. IF needs reverse engineering → Load: references/guides/reverse-engineering.md (~250 lines) +4. IF needs integration planning → Load: references/guides/integration-planning.md (~250 lines) -### 📋 What Was Generated -- \`.speckit/features/user-auth/specify.md\`: Complete requirements with 5 user stories, 8 success criteria, 3 edge cases +Token budget: 2,100 + 1,500 + [0-1,250] = 3,600-4,850 tokens +``` -### 🔍 Important Items to Review -1. **Password reset flow** - Verify email requirements match your infrastructure (SMTP server, templates) -2. **Multi-factor authentication** - Currently marked as "future enhancement"; may need to be in MVP -3. **Rate limiting** - Set at 5 login attempts per 15 min; consider if this fits your security policy +**For FEATURE_MANAGEMENT**: +``` +1. Load: references/guides/feature-management-quick.md (~200 lines, ~1,000 tokens) +2. IF tracking status → Load: references/templates/feature-status-brief.md (~60 lines) +3. IF detailed dashboard → Load: references/templates/feature-status-dashboard.md (~100 lines) -### ⚠️ Watch Out For -- **Email service dependency not specified** - How to avoid: Add email service to plan.md dependencies -- **GDPR compliance for user data** - How to avoid: Review data retention and user deletion requirements +Token budget: 2,100 + 1,000 + [0-800] = 3,100-3,900 tokens (optimal ✅) +``` -### 🔄 What This Enables Next -- **Option 1:** Run \`/speckit.plan\` to design technical implementation - Best if: Requirements look good -- **Option 2:** Modify specify.md - Best if: You need to adjust requirements or add features +**For INSTALLATION**: +``` +1. Load: references/sdd_install.md (143 lines, ~715 tokens) -📊 **Feature Status:** user-authentication (Specified) → Next: profile-management - Progress: [●●○○○] 40% | Completed: 1 of 5 features | Dependencies: database-setup ✅ +Token budget: 2,100 + 715 = 2,815 tokens (excellent ✅) +``` -**Your options:** [A] Proceed to planning [B] Modify requirements [C] Explain JWT choice [D] Show full status -\`\`\` +**For EXECUTE_WORKFLOW** (after SDD command completes): +``` +1. Detect which command completed +2. Load: references/templates/10-point-summary-template.md (~100 lines, ~500 tokens) +3. IF feature tracking active → Load: references/templates/feature-status-brief.md (~60 lines) +4. Apply template to generated artifacts -### When to Skip Summarization +Token budget: 2,100 + 500 + [0-300] = 2,600-2,900 tokens (perfect ✅) +``` -Only skip the summarization step when: -- User explicitly requests "skip summaries" or "run all steps automatically" -- Re-running a command without artifact changes -- Command fails or produces errors (troubleshoot instead) +**For COMMAND_REFERENCE**: +``` +1. Load: references/templates/command-reference.md (~80 lines, ~400 tokens) -### Benefits of This Workflow +Token budget: 2,100 + 400 = 2,500 tokens (minimal ✅) +``` -- **Eliminates "black box" feeling**: Clear explanations of what was generated and why -- **Enables early feedback**: Catch misunderstandings before implementation -- **Maintains agility**: Quick review with structured format, not lengthy approval processes -- **Builds trust**: User sees the AI's reasoning and decisions with rationale -- **Provides context**: Feature status keeps users oriented in the overall project +## Token Budget Management -## Feature Status Tracking +**Total Budget per Request**: <10,000 tokens (target: <7,500) -### Hybrid Approach +**Tier Loading Costs**: +- **Tier 1 (YAML)**: 100 tokens (always loaded) +- **Tier 2 (this file)**: 2,000 tokens (always loaded) +- **Tier 3 (on-demand)**: 400-6,000 tokens depending on intent -After every SDD command, include a **brief feature status line** in the summary. Provide **detailed status on demand** with `/speckit.status`. +**Before Loading Tier 3**: +1. ✅ Identify intent (above decision tree) +2. ✅ Select minimal relevant resource +3. ✅ Check cumulative budget (Tier1 + Tier2 + planned Tier3) +4. ⚠️ If approaching 8,000 tokens → Load summary/overview only +5. ❌ If over 10,000 tokens → Stop loading, use inline guidance -### Brief Status Line Format +**Loading Priority** (when budget constrained): +1. Workflow quick-start (essential) +2. Templates (if command executed) +3. Step details (if user stuck) +4. Examples (last resort) -Include this at the end of every summary: +## Workflow Quick Reference +**Greenfield** (New Projects - 6 steps): ``` -📊 **Feature Status:** [Current Feature Name] ([Stage]) → Next: [Next Feature Name] - Progress: [●●●○○] [X]% | Completed: [N] of [Total] features | Dependencies: [Dep] ✅/⏸️ +specify init → /speckit.constitution → /speckit.specify → +/speckit.plan → /speckit.tasks → /speckit.implement ``` +→ **Full guide**: `references/workflows/greenfield-quick-start.md` -**Stage values:** -- `Specifying` (20% complete) -- `Planning` (40% complete) -- `Tasking` (60% complete) -- `In Progress` (80% complete) -- `Complete` (100% complete) - -**Progress indicator:** -- Use filled circles (●) for completed stages -- Use empty circles (○) for pending stages -- Calculate percentage based on stage - -### Detailed Status Dashboard - -When user requests full status (option D) or runs `/speckit.status`, show: - +**Brownfield** (Existing Projects - 7 steps): ``` -📊 Project Feature Status Dashboard - -🎯 CURRENT FEATURE -├─ [feature-name] ([Stage] - [X]% complete) -│ ├─ ✅ Requirements specified -│ ├─ 🔄 Implementation plan in progress -│ ├─ ⏸️ Tasks not started -│ └─ ⏸️ Implementation not started -│ Blockers: [None | Description] -│ Dependencies: [feature-name] ✅ - -✅ COMPLETED FEATURES ([N]) -├─ [feature-1] (100% complete) -└─ [feature-2] (100% complete) - -📋 UPCOMING FEATURES ([N]) -├─ [feature-3] (depends on: [current-feature]) -└─ [feature-4] (depends on: [feature-3]) - -⚠️ BLOCKED FEATURES ([N]) -[List any features that are blocked with reasons] +/speckit.brownfield → specify init --here → /speckit.analyze-codebase → +/speckit.reverse-engineer → /speckit.specify → /speckit.integration-plan → +/speckit.tasks → /speckit.implement ``` +→ **Full guide**: `references/workflows/brownfield-quick-start.md` -### Natural Language Feature Management - -Claude should automatically detect and handle natural language feature management requests: - -**User says:** "Move feature XYZ before ABC" -**Claude does:** -1. Reads current feature list from `.speckit/features/` -2. Shows current order with numbers -3. Proposes new order -4. Asks for confirmation -5. Updates feature priority/order in constitution or plan -6. Shows updated status dashboard - -**User says:** "Add a new feature for email notifications" -**Claude does:** -1. Detects new feature request -2. Asks clarifying questions (priority, dependencies, description) -3. Generates feature spec outline -4. Inserts into feature list at appropriate position -5. Shows updated status dashboard - -**User says:** "Let's do profile-management first" -**Claude does:** -1. Identifies current feature order -2. Proposes moving profile-management to top priority -3. Adjusts dependencies if needed -4. Updates artifacts -5. Shows updated status - -**Detection patterns:** -- "Move [feature] before/after [other]" → Reorder -- "Add [feature]" → New feature -- "Let's do [feature] first" → Move to top priority -- "Skip [feature] for now" → Mark as deferred -- "We finished [feature]" → Update status to complete -- "What features depend on [feature]?" → Show dependency tree -- "Show feature status" → Display full dashboard - -### Quick Feature Operations - -Guide users through these operations when requested: - -**Add Feature:** -``` -User: "Add a feature for admin dashboard" -Claude: -1. What's the priority? (High/Medium/Low) -2. What features does this depend on? (user-auth, profile-management, etc.) -3. Brief description? -[Creates outline, shows updated status] -``` +## Supported AI Agents -**Reorder Features:** -``` -User: "Reorder features" -Claude: -Current order: -1. user-authentication -2. profile-management -3. admin-dashboard -4. email-notifications -5. reporting - -How would you like to reorder? (provide new numbers or describe changes) -[Updates order, shows new status] -``` +Works with: Claude Code, GitHub Copilot, Cursor, Windsurf, Gemini CLI, Qwen Code, opencode, Roo Code, and others. -**Remove Feature:** -``` -User: "Remove the reporting feature" -Claude: -⚠️ Warning: This will remove 'reporting' feature. -Dependencies affected: None -Are you sure? (yes/no) -[If yes: removes, updates status] -``` +⚠️ **Amazon Q Developer CLI** doesn't support custom arguments for slash commands. -### Progress Calculation +→ **Full list**: See README.md -Automatically calculate progress based on SDD workflow completion: +## Resource Loading Policy -| Stage | Progress | Indicators | -|-------|----------|------------| -| **Specified** | 20% | `specify.md` exists | -| **Planned** | 40% | `plan.md` exists | -| **Tasked** | 60% | `tasks.md` exists | -| **In Progress** | 80% | Implementation started (code files modified) | -| **Complete** | 100% | Implementation complete, tests pass | +**CRITICAL**: Load resources surgically, never proactively. -### Dependency Tracking +**Templates** (load ONLY when): +- `/speckit.*` command completes → Load `templates/10-point-summary-template.md` +- User requests commands → Load `templates/command-reference.md` +- Feature tracking active → Load `templates/feature-status-*.md` -Track and visualize dependencies: +**Workflow Guides** (load ONLY when): +- Intent=NEW_PROJECT → Load `workflows/greenfield-quick-start.md` +- Intent=EXISTING_PROJECT → Load `workflows/brownfield-quick-start.md` -**Show dependencies:** -``` -user-authentication -├─ Depends on: database-setup ✅ -└─ Blocks: profile-management ⏸️, admin-dashboard ⏸️ -``` +**Detail Guides** (load ONLY when): +- User asks specific questions → Load relevant `guides/*.md` +- User is stuck on a step → Load step details +- User requests examples → Load `examples/*.md` -**Check if ready:** +**How to Load**: ``` -📊 Can we start profile-management? - Checking dependencies... - ✅ user-authentication (complete) - ✅ database-setup (complete) - - All dependencies satisfied! Ready to proceed. +Use Read tool with specific file path +Extract only relevant sections if file is large +Never load entire directories +Never load "just in case" ``` -**Detect circular dependencies:** +**Example Loading**: ``` -⚠️ Warning: Circular dependency detected - feature-A depends on feature-B - feature-B depends on feature-C - feature-C depends on feature-A - - Please resolve this before proceeding. +User: "I want to start a new project with SDD" +→ Intent: NEW_PROJECT +→ Read: references/workflows/greenfield-quick-start.md +→ Present overview +→ Wait for next user action ``` -### Integration with Workflows +## Key Integration Points -**For Greenfield Projects:** -- After `/speckit.specify`, ask if there are multiple features -- If yes, list them and track progress through each -- Show status after each command +**Other Claude Code Skills**: +- `project-memory`: Document SDD decisions and patterns +- `design-doc-mermaid`: Visualize architecture from plan.md +- `github-workflows`: Automate SDD artifact validation -**For Brownfield Projects:** -- After `/speckit.reverse-engineer`, create feature list from discovered functionality -- Track new features separately from existing documented features -- Show integration impact on status +**External Tools**: +- `specify-cli`: Core SDD tool (via uv package manager) +- `uv`: Package manager for specify-cli installation +- Git: Version control for artifacts -For complete feature management guidance, see [Feature Management Guide](references/feature_management.md). +**AI Agents**: +- Claude Code (primary) +- GitHub Copilot, Cursor, Windsurf (supported) -## How to Use This Skill +## Error Handling -### When User Asks About SDD +**If Resource Not Found**: +1. Check if file path is correct +2. Fall back to inline basic guidance +3. Direct user to GitHub Spec-Kit docs: https://github.com/github/spec-kit +4. Suggest manual workflow steps -1. Explain core philosophy: Executable specifications, intent-driven, AI-native -2. Verify prerequisites: \`uv\`, Python 3.11+, Git, AI agent -3. Determine project type: New (greenfield) vs existing (brownfield) -4. Guide to appropriate workflow: - - Greenfield → [Greenfield Workflow](references/greenfield.md) - - Brownfield → [Brownfield Workflow](references/brownfield.md) +**If Over Token Budget**: +1. Load workflow quick-start ONLY (skip details) +2. Provide summary instead of full examples +3. Offer to load detailed sections on-demand +4. Track and report token usage to user -### When User Wants to Start a New Project +**If Intent Unclear**: +1. Ask clarifying question: "Are you starting a new project or working with existing code?" +2. Present decision tree options +3. Default to Installation guide if truly unclear -1. Guide installation → [Installation Guide](references/sdd_install.md) -2. Initialize project: - \`\`\`bash - specify init my-project --ai claude - \`\`\` -3. Follow greenfield workflow → [Greenfield Workflow](references/greenfield.md) -4. **After each step**: Summarize artifacts and get user feedback +**If Workflow Fails**: +1. Check prerequisites (uv installed, specify-cli installed) +2. Verify command syntax +3. Load troubleshooting from relevant workflow guide +4. Reference GitHub Spec-Kit issues -### When User Has an Existing Codebase +## Quick Start Guidance -1. Check for \`.speckit/\` directory -2. **If missing** → Guide through [Brownfield Workflow](references/brownfield.md): - - Analyze existing code - - Generate constitution from existing patterns - - Choose artifact generation strategy - - Add new features with SDD -3. **If present** → Determine next step based on current progress -4. **After each step**: Summarize artifacts and get user feedback +**For absolute beginners**, provide this inline minimal guidance: -### When User Wants to Add a Feature +### New Project (Greenfield) +```bash +# 1. Install specify-cli +uv tool install specify-cli --from git+https://github.com/github/spec-kit.git -**To greenfield project:** -1. Navigate to [Greenfield Workflow](references/greenfield.md) -2. Follow steps 3-6 (specify → plan → tasks → implement) -3. Summarize each artifact before proceeding +# 2. Initialize project +specify init my-project --ai claude -**To brownfield/existing project:** -1. Navigate to [Brownfield Workflow](references/brownfield.md) -2. Follow steps 6-7 (specify → integration planning → tasks → implement) -3. Summarize each artifact before proceeding +# 3. In AI agent, run these commands in sequence: +/speckit.constitution # Define project principles +/speckit.specify # Define requirements +/speckit.plan # Technical planning +/speckit.tasks # Break down tasks +/speckit.implement # Execute +``` -### When User Encounters Issues +### Existing Project (Brownfield) +```bash +# 1. Install specify-cli (same as above) + +# 2. In AI agent: +/speckit.brownfield # Analyze existing code +specify init --here --force # Initialize in current dir +/speckit.analyze-codebase # Generate constitution +/speckit.specify # Specify new feature +/speckit.integration-plan # Plan integration +/speckit.tasks # Break down +/speckit.implement # Execute +``` -1. **Installation issues** → [Installation Guide](references/sdd_install.md) troubleshooting section -2. **Workflow issues** → Check appropriate workflow guide: - - [Greenfield troubleshooting](references/greenfield.md) - - [Brownfield troubleshooting](references/brownfield.md) -3. **Feature detection** → Set \`SPECIFY_FEATURE\` environment variable (see [Installation Guide](references/sdd_install.md)) +**After providing this**, route to full workflow guide for details. -## Workflow Overview - -### Greenfield (New Projects) +## Maintainers -\`\`\` -specify init → /speckit.constitution → [SUMMARIZE] → -/speckit.specify → [SUMMARIZE] → /speckit.plan → [SUMMARIZE] → -/speckit.tasks → [SUMMARIZE] → /speckit.implement -\`\`\` - -**Full details:** [Greenfield Workflow](references/greenfield.md) - -### Brownfield (Existing Projects) - -\`\`\` -specify init --here → /speckit.brownfield → [SUMMARIZE] → -/speckit.analyze-codebase → [SUMMARIZE] → -/speckit.reverse-engineer → [SUMMARIZE] → /speckit.specify → [SUMMARIZE] → -/speckit.integration-plan → [SUMMARIZE] → /speckit.tasks → [SUMMARIZE] → -/speckit.implement -\`\`\` - -**Full details:** [Brownfield Workflow](references/brownfield.md) - -## Development Phases Supported - -### 0-to-1 Development ("Greenfield") -Start with high-level requirements, generate specifications from scratch, plan implementation steps, build production-ready applications. - -**→ [Greenfield Workflow](references/greenfield.md)** - -### Iterative Enhancement ("Brownfield") -Add features iteratively to existing codebases, modernize legacy systems, adapt processes for evolving requirements, reverse-engineer existing code into SDD format. - -**→ [Brownfield Workflow](references/brownfield.md)** - -### Creative Exploration -Explore diverse solutions in parallel, support multiple technology stacks & architectures, experiment with UX patterns. - -**→ [Greenfield Workflow](references/greenfield.md) - Multi-Stack Exploration section** - -## Key Commands Reference - -### Installation & Setup -\`\`\`bash -specify init # New project -specify init --here --force # Existing project -specify check # Verify installation -\`\`\` - -### Greenfield Workflow -\`\`\` -/speckit.constitution # Project principles → SUMMARIZE -/speckit.specify # Define requirements → SUMMARIZE -/speckit.plan # Technical planning → SUMMARIZE -/speckit.tasks # Break down tasks → SUMMARIZE -/speckit.implement # Execute -\`\`\` - -### Brownfield Workflow -\`\`\` -/speckit.brownfield # Analyze existing code → SUMMARIZE -/speckit.analyze-codebase # Deep analysis & constitution → SUMMARIZE -/speckit.reverse-engineer # Document existing features → SUMMARIZE -/speckit.integration-plan # Plan new feature integration → SUMMARIZE -\`\`\` - -### Optional Enhancement Commands -\`\`\` -/speckit.clarify # Clarify ambiguous requirements -/speckit.analyze # Cross-artifact consistency check -/speckit.checklist # Generate quality checklists -\`\`\` - -## Analysis Scripts - -The SDD skill includes analysis scripts for deep quality validation and progress tracking: - -### \`scripts/phase_summary.sh\` -Generates a comprehensive progress report across all phases in a tasks.md file: -- Shows completion percentage for each phase -- Lists pending tasks per phase -- Highlights simplified/modified tasks -- Provides overall progress statistics -- Supports any SDD feature's tasks.md file - -**Usage:** -\`\`\`bash -~/.claude/skills/sdd/scripts/phase_summary.sh specs/003-keyboard-shortcuts/tasks.md -\`\`\` - -**Output:** Markdown-formatted phase-by-phase progress report with: -- Phase-by-phase completion percentages -- Pending task lists (up to 5 per phase) -- Simplified task warnings -- Overall feature progress summary - -**When to Use:** -- Check progress on any SDD feature -- Get quick overview of what's complete vs pending -- Identify phases that need attention -- Generate status reports for stakeholders - -### \`scripts/analyze-requirements.py\` -Analyzes requirement coverage across spec.md and tasks.md: -- Maps functional requirements (FR-001, FR-002, etc.) to implementation tasks -- Identifies uncovered requirements (gaps in task coverage) -- Flags vague requirements lacking measurable criteria -- Calculates coverage percentage - -**Usage:** -\`\`\`bash -python3 ~/.claude/skills/sdd/scripts/analyze-requirements.py -\`\`\` - -**Output:** JSON with coverage metrics, uncovered requirements, vague requirements - -### \`scripts/analyze-success-criteria.py\` -Analyzes success criteria verification coverage: -- Maps success criteria (SC-001, SC-002, etc.) to verification tasks -- Validates measurability of each criterion -- Identifies criteria without verification tasks -- Groups by metric type (performance, accessibility, usability) - -**Usage:** -\`\`\`bash -python3 ~/.claude/skills/sdd/scripts/analyze-success-criteria.py -\`\`\` - -**Output:** JSON with coverage summary, verification task mapping - -### \`scripts/analyze-edge-cases.py\` -Analyzes edge case coverage across specifications: -- Maps edge cases to explicit task coverage -- Identifies implicitly covered cases (handled by general logic) -- Flags uncovered edge cases requiring attention -- Categorizes coverage type (EXPLICIT, IMPLICIT, UNCOVERED) - -**Usage:** -\`\`\`bash -python3 ~/.claude/skills/sdd/scripts/analyze-edge-cases.py -\`\`\` - -**Output:** JSON with coverage breakdown, uncovered edge case details - -**When to Use:** -These scripts are automatically invoked during \`/speckit.analyze\` to provide deep consistency validation. They help identify: -- Requirements without task coverage -- Success criteria without verification -- Edge cases that need test coverage -- Ambiguous requirements needing clarification - -### Validation Commands (Brownfield) -\`\`\` -/speckit.validate-reverse-engineering # Verify spec accuracy -/speckit.coverage-check # Check documentation coverage -/speckit.validate-constitution # Verify constitution consistency -/speckit.trace [feature] # Map specs to code -\`\`\` - -## Detailed Documentation - -- **[Installation Guide](references/sdd_install.md)**: Installation methods, troubleshooting, environment variables -- **[Greenfield Workflow](references/greenfield.md)**: Complete 6-step workflow for new projects -- **[Brownfield Workflow](references/brownfield.md)**: Complete 7-step workflow for existing codebases - -## Integration with Other Skills - -This skill works well with: -- **project-memory**: Document SDD decisions and patterns -- **design-doc-mermaid**: Visualize architecture from plan.md -- **github-workflows**: Automate SDD artifact validation -- **code-quality-reviewer**: Review generated implementation - -## Resources - -- GitHub Spec-Kit Repository: https://github.com/github/spec-kit -- Issues/Support: https://github.com/github/spec-kit/issues -- License: MIT +Den Delimarsky (@localden), John Lam (@jflam) -## Maintainers +--- -- Den Delimarsky (@localden) -- John Lam (@jflam) +**For comprehensive documentation, see**: +- Greenfield: `references/workflows/greenfield-quick-start.md` +- Brownfield: `references/workflows/brownfield-quick-start.md` +- Feature Management: `references/guides/feature-management-quick.md` +- Installation: `references/sdd_install.md` diff --git a/skill_old.md b/skill_old.md new file mode 100644 index 0000000..ffa53c8 --- /dev/null +++ b/skill_old.md @@ -0,0 +1,628 @@ +--- +name: sdd +description: Guide users through GitHub Spec-Kit for executable spec-driven development (greenfield/brownfield workflows with feature tracking). +version: 2.2.0 +triggers: + - sdd + - speckit + - spec-driven + - greenfield + - brownfield + - feature status + - /speckit +author: Based on GitHub Spec-Kit +license: MIT +tier1_token_budget: 100 +tier2_token_budget: 2000 +--- + +# Spec-Driven Development (SDD) Skill + +Guide users through GitHub's Spec-Kit for Spec-Driven Development - a methodology that flips traditional software development by making specifications executable and directly generating working implementations. + +## Core Philosophy + +Spec-Driven Development emphasizes: +- **Intent-driven development**: Define the "what" before the "how" +- **Rich specification creation**: Use guardrails and organizational principles +- **Multi-step refinement**: Not one-shot code generation +- **AI-native**: Heavy reliance on advanced AI capabilities + +Remember: This is **AI-native development**. Specifications aren't just documentation - they're executable artifacts that directly drive implementation. The AI agent uses them to generate working code that matches the intent defined in the specs. + +## Quick Decision Tree + +### Is this a new project (greenfield)? +→ **See [Greenfield Workflow](references/greenfield.md)** for the complete 6-step process + +### Is this an existing codebase (brownfield)? +→ **See [Brownfield Workflow](references/brownfield.md)** for reverse-engineering and integration guidance + +### Need installation help? +→ **See [Installation Guide](references/sdd_install.md)** for setup and troubleshooting + +## Installation Quick Start + +**Recommended (Persistent):** +```bash +uv tool install specify-cli --from git+https://github.com/github/spec-kit.git +``` + +**One-time Usage:** +```bash +uvx --from git+https://github.com/github/spec-kit.git specify init +``` + +**Verify:** +```bash +specify check +``` + +For detailed installation options, troubleshooting, and environment variables, see [Installation Guide](references/sdd_install.md). + +## Supported AI Agents + +Works with: +- ✅ Claude Code +- ✅ GitHub Copilot +- ✅ Gemini CLI +- ✅ Cursor +- ✅ Qwen Code +- ✅ opencode +- ✅ Windsurf +- ✅ Kilo Code +- ✅ Auggie CLI +- ✅ CodeBuddy CLI +- ✅ Roo Code +- ✅ Codex CLI +- ✅ Amp +- ⚠️ Amazon Q Developer CLI (doesn't support custom arguments for slash commands) + +## Artifact Summarization and Feedback Loop + +**CRITICAL WORKFLOW**: After any SDD command generates or modifies artifacts, automatically follow this feedback loop to keep the user engaged: + +### After Each Command Completes + +1. **Detect Artifact Changes** + - Identify which artifacts were created or modified: + - `constitution.md` (project principles) + - `spec.md` (requirements specification) + - `plan.md` (technical implementation plan) + - `tasks.md` (actionable task breakdown) + - Analysis reports from brownfield workflows + +2. **Read and Summarize** + - Read the relevant artifact(s) + - Extract key information: + - **For constitution.md**: Core principles, coding standards, constraints + - **For spec.md**: Main requirements, user stories, success criteria + - **For plan.md**: Tech stack choices, architecture decisions, milestones + - **For tasks.md**: Number of tasks, major task categories, dependencies + - **For analysis reports**: Current patterns, tech debt, integration points + +3. **Present Structured Summary** (Use 10-Point Template Below) + - Show what was generated and why + - Highlight the most important decisions with rationale + - Include quality indicators and watch-outs + - Keep summary focused and actionable + - Use clear headings for each section + +4. **Include Feature Status** (Hybrid Approach) + - Brief status line in every summary + - Detailed status on demand with `/speckit.status` + - See "Feature Status Tracking" section below + +5. **Offer Feedback Options** + - **Option A**: "Looks good, proceed to next step" + - **Option B**: "I'd like to modify [specific section]" + - **Option C**: "Regenerate with these changes: [user input]" + - **Option D**: "Explain why [specific decision] was made" + +### 10-Point Summary Template + +Use this structured format after ANY SDD command completes: + +``` +## ✅ [Command Name] Completed - Here's What Just Happened + +### 🎯 Key Decisions Made (Top 3) +1. [Decision] - **Rationale:** [Why this was chosen] +2. [Decision] - **Rationale:** [Why this was chosen] +3. [Decision] - **Rationale:** [Why this was chosen] + +### 📋 What Was Generated +- [Artifact 1]: [Brief description of content] +- [Artifact 2]: [Brief description of content] + +### 🔍 Important Items to Review (Top 3) +1. [Critical item to check and why it matters] +2. [Important detail to verify and potential impact] +3. [Edge case to consider and how it affects the design] + +### ⚠️ Watch Out For (Top 2) +- [Potential issue or gotcha] - **How to avoid:** [Guidance] +- [Common mistake] - **How to avoid:** [Guidance] + +### 🔄 What This Enables Next (2 Options) +- **Option 1:** [Next step] - Best if: [Condition] +- **Option 2:** [Alternative step] - Best if: [Condition] + +📊 **Feature Status:** [Current Feature Name] ([Stage]) → Next: [Next Feature] + Progress: [●●●○○] [X]% | Completed: [N] of [Total] features | Dependencies: [Status] + +**Your options:** [A] Proceed [B] Modify [C] Explain more [D] Show full status +``` + +### Example: Enhanced Summarization After \`/speckit.specify\` + +\`\`\` +## ✅ Specify Completed - Here's What Just Happened + +### 🎯 Key Decisions Made +1. **Authentication: JWT tokens** - Rationale: Stateless architecture, horizontally scalable, industry standard +2. **Password requirements: 12+ characters with complexity** - Rationale: Balances security (NIST guidelines) with usability +3. **Session timeout: 24 hours** - Rationale: Standard for web apps, balances security vs user convenience + +### 📋 What Was Generated +- \`.speckit/features/user-auth/specify.md\`: Complete requirements with 5 user stories, 8 success criteria, 3 edge cases + +### 🔍 Important Items to Review +1. **Password reset flow** - Verify email requirements match your infrastructure (SMTP server, templates) +2. **Multi-factor authentication** - Currently marked as "future enhancement"; may need to be in MVP +3. **Rate limiting** - Set at 5 login attempts per 15 min; consider if this fits your security policy + +### ⚠️ Watch Out For +- **Email service dependency not specified** - How to avoid: Add email service to plan.md dependencies +- **GDPR compliance for user data** - How to avoid: Review data retention and user deletion requirements + +### 🔄 What This Enables Next +- **Option 1:** Run \`/speckit.plan\` to design technical implementation - Best if: Requirements look good +- **Option 2:** Modify specify.md - Best if: You need to adjust requirements or add features + +📊 **Feature Status:** user-authentication (Specified) → Next: profile-management + Progress: [●●○○○] 40% | Completed: 1 of 5 features | Dependencies: database-setup ✅ + +**Your options:** [A] Proceed to planning [B] Modify requirements [C] Explain JWT choice [D] Show full status +\`\`\` + +### When to Skip Summarization + +Only skip the summarization step when: +- User explicitly requests "skip summaries" or "run all steps automatically" +- Re-running a command without artifact changes +- Command fails or produces errors (troubleshoot instead) + +### Benefits of This Workflow + +- **Eliminates "black box" feeling**: Clear explanations of what was generated and why +- **Enables early feedback**: Catch misunderstandings before implementation +- **Maintains agility**: Quick review with structured format, not lengthy approval processes +- **Builds trust**: User sees the AI's reasoning and decisions with rationale +- **Provides context**: Feature status keeps users oriented in the overall project + +## Feature Status Tracking + +### Hybrid Approach + +After every SDD command, include a **brief feature status line** in the summary. Provide **detailed status on demand** with `/speckit.status`. + +### Brief Status Line Format + +Include this at the end of every summary: + +``` +📊 **Feature Status:** [Current Feature Name] ([Stage]) → Next: [Next Feature Name] + Progress: [●●●○○] [X]% | Completed: [N] of [Total] features | Dependencies: [Dep] ✅/⏸️ +``` + +**Stage values:** +- `Specifying` (20% complete) +- `Planning` (40% complete) +- `Tasking` (60% complete) +- `In Progress` (80% complete) +- `Complete` (100% complete) + +**Progress indicator:** +- Use filled circles (●) for completed stages +- Use empty circles (○) for pending stages +- Calculate percentage based on stage + +### Detailed Status Dashboard + +When user requests full status (option D) or runs `/speckit.status`, show: + +``` +📊 Project Feature Status Dashboard + +🎯 CURRENT FEATURE +├─ [feature-name] ([Stage] - [X]% complete) +│ ├─ ✅ Requirements specified +│ ├─ 🔄 Implementation plan in progress +│ ├─ ⏸️ Tasks not started +│ └─ ⏸️ Implementation not started +│ Blockers: [None | Description] +│ Dependencies: [feature-name] ✅ + +✅ COMPLETED FEATURES ([N]) +├─ [feature-1] (100% complete) +└─ [feature-2] (100% complete) + +📋 UPCOMING FEATURES ([N]) +├─ [feature-3] (depends on: [current-feature]) +└─ [feature-4] (depends on: [feature-3]) + +⚠️ BLOCKED FEATURES ([N]) +[List any features that are blocked with reasons] +``` + +### Natural Language Feature Management + +Claude should automatically detect and handle natural language feature management requests: + +**User says:** "Move feature XYZ before ABC" +**Claude does:** +1. Reads current feature list from `.speckit/features/` +2. Shows current order with numbers +3. Proposes new order +4. Asks for confirmation +5. Updates feature priority/order in constitution or plan +6. Shows updated status dashboard + +**User says:** "Add a new feature for email notifications" +**Claude does:** +1. Detects new feature request +2. Asks clarifying questions (priority, dependencies, description) +3. Generates feature spec outline +4. Inserts into feature list at appropriate position +5. Shows updated status dashboard + +**User says:** "Let's do profile-management first" +**Claude does:** +1. Identifies current feature order +2. Proposes moving profile-management to top priority +3. Adjusts dependencies if needed +4. Updates artifacts +5. Shows updated status + +**Detection patterns:** +- "Move [feature] before/after [other]" → Reorder +- "Add [feature]" → New feature +- "Let's do [feature] first" → Move to top priority +- "Skip [feature] for now" → Mark as deferred +- "We finished [feature]" → Update status to complete +- "What features depend on [feature]?" → Show dependency tree +- "Show feature status" → Display full dashboard + +### Quick Feature Operations + +Guide users through these operations when requested: + +**Add Feature:** +``` +User: "Add a feature for admin dashboard" +Claude: +1. What's the priority? (High/Medium/Low) +2. What features does this depend on? (user-auth, profile-management, etc.) +3. Brief description? +[Creates outline, shows updated status] +``` + +**Reorder Features:** +``` +User: "Reorder features" +Claude: +Current order: +1. user-authentication +2. profile-management +3. admin-dashboard +4. email-notifications +5. reporting + +How would you like to reorder? (provide new numbers or describe changes) +[Updates order, shows new status] +``` + +**Remove Feature:** +``` +User: "Remove the reporting feature" +Claude: +⚠️ Warning: This will remove 'reporting' feature. +Dependencies affected: None +Are you sure? (yes/no) +[If yes: removes, updates status] +``` + +### Progress Calculation + +Automatically calculate progress based on SDD workflow completion: + +| Stage | Progress | Indicators | +|-------|----------|------------| +| **Specified** | 20% | `specify.md` exists | +| **Planned** | 40% | `plan.md` exists | +| **Tasked** | 60% | `tasks.md` exists | +| **In Progress** | 80% | Implementation started (code files modified) | +| **Complete** | 100% | Implementation complete, tests pass | + +### Dependency Tracking + +Track and visualize dependencies: + +**Show dependencies:** +``` +user-authentication +├─ Depends on: database-setup ✅ +└─ Blocks: profile-management ⏸️, admin-dashboard ⏸️ +``` + +**Check if ready:** +``` +📊 Can we start profile-management? + Checking dependencies... + ✅ user-authentication (complete) + ✅ database-setup (complete) + + All dependencies satisfied! Ready to proceed. +``` + +**Detect circular dependencies:** +``` +⚠️ Warning: Circular dependency detected + feature-A depends on feature-B + feature-B depends on feature-C + feature-C depends on feature-A + + Please resolve this before proceeding. +``` + +### Integration with Workflows + +**For Greenfield Projects:** +- After `/speckit.specify`, ask if there are multiple features +- If yes, list them and track progress through each +- Show status after each command + +**For Brownfield Projects:** +- After `/speckit.reverse-engineer`, create feature list from discovered functionality +- Track new features separately from existing documented features +- Show integration impact on status + +For complete feature management guidance, see [Feature Management Guide](references/feature_management.md). + +## How to Use This Skill + +### When User Asks About SDD + +1. Explain core philosophy: Executable specifications, intent-driven, AI-native +2. Verify prerequisites: \`uv\`, Python 3.11+, Git, AI agent +3. Determine project type: New (greenfield) vs existing (brownfield) +4. Guide to appropriate workflow: + - Greenfield → [Greenfield Workflow](references/greenfield.md) + - Brownfield → [Brownfield Workflow](references/brownfield.md) + +### When User Wants to Start a New Project + +1. Guide installation → [Installation Guide](references/sdd_install.md) +2. Initialize project: + \`\`\`bash + specify init my-project --ai claude + \`\`\` +3. Follow greenfield workflow → [Greenfield Workflow](references/greenfield.md) +4. **After each step**: Summarize artifacts and get user feedback + +### When User Has an Existing Codebase + +1. Check for \`.speckit/\` directory +2. **If missing** → Guide through [Brownfield Workflow](references/brownfield.md): + - Analyze existing code + - Generate constitution from existing patterns + - Choose artifact generation strategy + - Add new features with SDD +3. **If present** → Determine next step based on current progress +4. **After each step**: Summarize artifacts and get user feedback + +### When User Wants to Add a Feature + +**To greenfield project:** +1. Navigate to [Greenfield Workflow](references/greenfield.md) +2. Follow steps 3-6 (specify → plan → tasks → implement) +3. Summarize each artifact before proceeding + +**To brownfield/existing project:** +1. Navigate to [Brownfield Workflow](references/brownfield.md) +2. Follow steps 6-7 (specify → integration planning → tasks → implement) +3. Summarize each artifact before proceeding + +### When User Encounters Issues + +1. **Installation issues** → [Installation Guide](references/sdd_install.md) troubleshooting section +2. **Workflow issues** → Check appropriate workflow guide: + - [Greenfield troubleshooting](references/greenfield.md) + - [Brownfield troubleshooting](references/brownfield.md) +3. **Feature detection** → Set \`SPECIFY_FEATURE\` environment variable (see [Installation Guide](references/sdd_install.md)) + +## Workflow Overview + +### Greenfield (New Projects) + +\`\`\` +specify init → /speckit.constitution → [SUMMARIZE] → +/speckit.specify → [SUMMARIZE] → /speckit.plan → [SUMMARIZE] → +/speckit.tasks → [SUMMARIZE] → /speckit.implement +\`\`\` + +**Full details:** [Greenfield Workflow](references/greenfield.md) + +### Brownfield (Existing Projects) + +\`\`\` +specify init --here → /speckit.brownfield → [SUMMARIZE] → +/speckit.analyze-codebase → [SUMMARIZE] → +/speckit.reverse-engineer → [SUMMARIZE] → /speckit.specify → [SUMMARIZE] → +/speckit.integration-plan → [SUMMARIZE] → /speckit.tasks → [SUMMARIZE] → +/speckit.implement +\`\`\` + +**Full details:** [Brownfield Workflow](references/brownfield.md) + +## Development Phases Supported + +### 0-to-1 Development ("Greenfield") +Start with high-level requirements, generate specifications from scratch, plan implementation steps, build production-ready applications. + +**→ [Greenfield Workflow](references/greenfield.md)** + +### Iterative Enhancement ("Brownfield") +Add features iteratively to existing codebases, modernize legacy systems, adapt processes for evolving requirements, reverse-engineer existing code into SDD format. + +**→ [Brownfield Workflow](references/brownfield.md)** + +### Creative Exploration +Explore diverse solutions in parallel, support multiple technology stacks & architectures, experiment with UX patterns. + +**→ [Greenfield Workflow](references/greenfield.md) - Multi-Stack Exploration section** + +## Key Commands Reference + +### Installation & Setup +\`\`\`bash +specify init # New project +specify init --here --force # Existing project +specify check # Verify installation +\`\`\` + +### Greenfield Workflow +\`\`\` +/speckit.constitution # Project principles → SUMMARIZE +/speckit.specify # Define requirements → SUMMARIZE +/speckit.plan # Technical planning → SUMMARIZE +/speckit.tasks # Break down tasks → SUMMARIZE +/speckit.implement # Execute +\`\`\` + +### Brownfield Workflow +\`\`\` +/speckit.brownfield # Analyze existing code → SUMMARIZE +/speckit.analyze-codebase # Deep analysis & constitution → SUMMARIZE +/speckit.reverse-engineer # Document existing features → SUMMARIZE +/speckit.integration-plan # Plan new feature integration → SUMMARIZE +\`\`\` + +### Optional Enhancement Commands +\`\`\` +/speckit.clarify # Clarify ambiguous requirements +/speckit.analyze # Cross-artifact consistency check +/speckit.checklist # Generate quality checklists +\`\`\` + +## Analysis Scripts + +The SDD skill includes analysis scripts for deep quality validation and progress tracking: + +### \`scripts/phase_summary.sh\` +Generates a comprehensive progress report across all phases in a tasks.md file: +- Shows completion percentage for each phase +- Lists pending tasks per phase +- Highlights simplified/modified tasks +- Provides overall progress statistics +- Supports any SDD feature's tasks.md file + +**Usage:** +\`\`\`bash +~/.claude/skills/sdd/scripts/phase_summary.sh specs/003-keyboard-shortcuts/tasks.md +\`\`\` + +**Output:** Markdown-formatted phase-by-phase progress report with: +- Phase-by-phase completion percentages +- Pending task lists (up to 5 per phase) +- Simplified task warnings +- Overall feature progress summary + +**When to Use:** +- Check progress on any SDD feature +- Get quick overview of what's complete vs pending +- Identify phases that need attention +- Generate status reports for stakeholders + +### \`scripts/analyze-requirements.py\` +Analyzes requirement coverage across spec.md and tasks.md: +- Maps functional requirements (FR-001, FR-002, etc.) to implementation tasks +- Identifies uncovered requirements (gaps in task coverage) +- Flags vague requirements lacking measurable criteria +- Calculates coverage percentage + +**Usage:** +\`\`\`bash +python3 ~/.claude/skills/sdd/scripts/analyze-requirements.py +\`\`\` + +**Output:** JSON with coverage metrics, uncovered requirements, vague requirements + +### \`scripts/analyze-success-criteria.py\` +Analyzes success criteria verification coverage: +- Maps success criteria (SC-001, SC-002, etc.) to verification tasks +- Validates measurability of each criterion +- Identifies criteria without verification tasks +- Groups by metric type (performance, accessibility, usability) + +**Usage:** +\`\`\`bash +python3 ~/.claude/skills/sdd/scripts/analyze-success-criteria.py +\`\`\` + +**Output:** JSON with coverage summary, verification task mapping + +### \`scripts/analyze-edge-cases.py\` +Analyzes edge case coverage across specifications: +- Maps edge cases to explicit task coverage +- Identifies implicitly covered cases (handled by general logic) +- Flags uncovered edge cases requiring attention +- Categorizes coverage type (EXPLICIT, IMPLICIT, UNCOVERED) + +**Usage:** +\`\`\`bash +python3 ~/.claude/skills/sdd/scripts/analyze-edge-cases.py +\`\`\` + +**Output:** JSON with coverage breakdown, uncovered edge case details + +**When to Use:** +These scripts are automatically invoked during \`/speckit.analyze\` to provide deep consistency validation. They help identify: +- Requirements without task coverage +- Success criteria without verification +- Edge cases that need test coverage +- Ambiguous requirements needing clarification + +### Validation Commands (Brownfield) +\`\`\` +/speckit.validate-reverse-engineering # Verify spec accuracy +/speckit.coverage-check # Check documentation coverage +/speckit.validate-constitution # Verify constitution consistency +/speckit.trace [feature] # Map specs to code +\`\`\` + +## Detailed Documentation + +- **[Installation Guide](references/sdd_install.md)**: Installation methods, troubleshooting, environment variables +- **[Greenfield Workflow](references/greenfield.md)**: Complete 6-step workflow for new projects +- **[Brownfield Workflow](references/brownfield.md)**: Complete 7-step workflow for existing codebases + +## Integration with Other Skills + +This skill works well with: +- **project-memory**: Document SDD decisions and patterns +- **design-doc-mermaid**: Visualize architecture from plan.md +- **github-workflows**: Automate SDD artifact validation +- **code-quality-reviewer**: Review generated implementation + +## Resources + +- GitHub Spec-Kit Repository: https://github.com/github/spec-kit +- Issues/Support: https://github.com/github/spec-kit/issues +- License: MIT + +## Maintainers + +- Den Delimarsky (@localden) +- John Lam (@jflam)