From a0be4de7ac3a09883cb7721201283282270d0b92 Mon Sep 17 00:00:00 2001 From: Zhongwei Li Date: Sun, 30 Nov 2025 08:51:44 +0800 Subject: [PATCH] Initial commit --- .claude-plugin/plugin.json | 15 + README.md | 3 + commands/brainstorm.md | 6 + commands/constitution.md | 6 + commands/evolve.md | 6 + commands/implement.md | 6 + commands/review-code.md | 6 + commands/review-spec.md | 6 + commands/spec.md | 6 + plugin.lock.json | 117 ++++ skills/brainstorm/SKILL.md | 314 ++++++++++ skills/constitution/SKILL.md | 518 +++++++++++++++++ skills/evolve/SKILL.md | 534 ++++++++++++++++++ skills/implement/SKILL.md | 432 ++++++++++++++ skills/review-code/SKILL.md | 350 ++++++++++++ skills/review-spec/SKILL.md | 498 ++++++++++++++++ skills/spec-kit/SKILL.md | 371 ++++++++++++ skills/spec-refactoring/SKILL.md | 447 +++++++++++++++ skills/spec/SKILL.md | 233 ++++++++ skills/using-superpowers-sdd/SKILL.md | 331 +++++++++++ .../verification-before-completion/SKILL.md | 419 ++++++++++++++ skills/writing-plans/SKILL.md | 500 ++++++++++++++++ 22 files changed, 5124 insertions(+) create mode 100644 .claude-plugin/plugin.json create mode 100644 README.md create mode 100644 commands/brainstorm.md create mode 100644 commands/constitution.md create mode 100644 commands/evolve.md create mode 100644 commands/implement.md create mode 100644 commands/review-code.md create mode 100644 commands/review-spec.md create mode 100644 commands/spec.md create mode 100644 plugin.lock.json create mode 100644 skills/brainstorm/SKILL.md create mode 100644 skills/constitution/SKILL.md create mode 100644 skills/evolve/SKILL.md create mode 100644 skills/implement/SKILL.md create mode 100644 skills/review-code/SKILL.md create mode 100644 skills/review-spec/SKILL.md create mode 100644 skills/spec-kit/SKILL.md create mode 100644 skills/spec-refactoring/SKILL.md create mode 100644 skills/spec/SKILL.md create mode 100644 skills/using-superpowers-sdd/SKILL.md create mode 100644 skills/verification-before-completion/SKILL.md create mode 100644 skills/writing-plans/SKILL.md diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..1c2ab0b --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "sdd", + "description": "Specification-Driven Development with Process Discipline for Claude Code", + "version": "1.0.0", + "author": { + "name": "Roland Huss", + "email": "rhuss@redhat.com" + }, + "skills": [ + "./skills" + ], + "commands": [ + "./commands" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..8626e1f --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# sdd + +Specification-Driven Development with Process Discipline for Claude Code diff --git a/commands/brainstorm.md b/commands/brainstorm.md new file mode 100644 index 0000000..c46a3f4 --- /dev/null +++ b/commands/brainstorm.md @@ -0,0 +1,6 @@ +--- +name: sdd:brainstorm +description: Refine rough ideas into executable specifications through collaborative dialogue +--- + +Use the `sdd:brainstorm` skill to guide the user through collaborative brainstorming, turning their rough idea into a formal, executable specification. diff --git a/commands/constitution.md b/commands/constitution.md new file mode 100644 index 0000000..c7b1eca --- /dev/null +++ b/commands/constitution.md @@ -0,0 +1,6 @@ +--- +name: sdd:constitution +description: Create and manage project constitution defining project-wide principles +--- + +Use the `sdd:constitution` skill to create or update the project constitution. diff --git a/commands/evolve.md b/commands/evolve.md new file mode 100644 index 0000000..3870a34 --- /dev/null +++ b/commands/evolve.md @@ -0,0 +1,6 @@ +--- +name: sdd:evolve +description: Reconcile spec/code mismatches with AI-guided evolution and user control +--- + +Use the `sdd:evolve` skill to reconcile mismatches between specifications and code implementation. diff --git a/commands/implement.md b/commands/implement.md new file mode 100644 index 0000000..c84f4a5 --- /dev/null +++ b/commands/implement.md @@ -0,0 +1,6 @@ +--- +name: sdd:implement +description: Implement features from validated specifications using TDD with spec compliance checking +--- + +Use the `sdd:implement` skill to implement a feature from an existing, validated specification. diff --git a/commands/review-code.md b/commands/review-code.md new file mode 100644 index 0000000..60a178c --- /dev/null +++ b/commands/review-code.md @@ -0,0 +1,6 @@ +--- +name: sdd:review-code +description: Review code against spec compliance - checks implementation matches spec requirements, identifies deviations, reports compliance score +--- + +Use the `sdd:review-code` skill to review code implementation against the specification for compliance. diff --git a/commands/review-spec.md b/commands/review-spec.md new file mode 100644 index 0000000..28e7290 --- /dev/null +++ b/commands/review-spec.md @@ -0,0 +1,6 @@ +--- +name: sdd:review-spec +description: Review specifications for soundness, completeness, and implementability +--- + +Use the `sdd:review-spec` skill to review a specification for soundness, completeness, and implementability. diff --git a/commands/spec.md b/commands/spec.md new file mode 100644 index 0000000..a385565 --- /dev/null +++ b/commands/spec.md @@ -0,0 +1,6 @@ +--- +name: sdd:spec +description: Create formal specifications directly from clear requirements +--- + +Use the `sdd:spec` skill to create a formal specification directly from the user's clear requirements. diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..f4681a0 --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,117 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:rhuss/cc-superpowers-sdd:", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "f5bf556dd2b55412d83cefdd327d45da9f9e9baa", + "treeHash": "71d8c21f24d6a6239f4172c8120ac1612292706c17824cae1b1f0717891508d7", + "generatedAt": "2025-11-28T10:27:57.354456Z", + "toolVersion": "publish_plugins.py@0.2.0" + }, + "origin": { + "remote": "git@github.com:zhongweili/42plugin-data.git", + "branch": "master", + "commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390", + "repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data" + }, + "manifest": { + "name": "sdd", + "description": "Specification-Driven Development with Process Discipline for Claude Code", + "version": "1.0.0" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "c59bb5c42fcfb5ba7fd49378db5d2c5fa1744d4bf716bbec18151f90a3ec6282" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "085c850a3c04a0ed6112514d5f7d3db706b9a75b8e3af07f9dd5d3bab82b56b9" + }, + { + "path": "commands/constitution.md", + "sha256": "bfc87059b5bda62143b5bf6778d99cfbbfc437d1614279a478885a90e8d13ef1" + }, + { + "path": "commands/implement.md", + "sha256": "2e3909c2d0c36d943d5e578b15455b8ff50e76d6c40d16c02e105472a9d67f23" + }, + { + "path": "commands/review-spec.md", + "sha256": "fc3a009cd5085395b6ddb4c6481b3cbd744457ce681d8fcf29c83a5dd7207600" + }, + { + "path": "commands/review-code.md", + "sha256": "40f6716331dda768c9b3b7a8eda800342f892993e26fb5771f6061facc1c719e" + }, + { + "path": "commands/evolve.md", + "sha256": "50a2d1df0059f5601bd2b5caa641052335c33cccda1293ac743ea354bcce046d" + }, + { + "path": "commands/spec.md", + "sha256": "2182b65cbb1aa331ac42fe30567cbcc5f4c4ac7e64f4f1f831d254973eeb2a71" + }, + { + "path": "commands/brainstorm.md", + "sha256": "f214ce202bd62df159df9ffc8a3416ed4b69442cd2ed35394be8f32e32cfc396" + }, + { + "path": "skills/review-spec/SKILL.md", + "sha256": "4c4b0975c3ce30743ec556b259eff98015b7b9c74657cd8ee9930a4569d2ace3" + }, + { + "path": "skills/review-code/SKILL.md", + "sha256": "45869d1bd9e8af7bff02488c2bd49e2c46fec9692282fb0124255317054ac4f9" + }, + { + "path": "skills/brainstorm/SKILL.md", + "sha256": "5a2eedb69cd87c9036d9268689a886c1a58f8003bb0c474f1545d5dc0bbd716b" + }, + { + "path": "skills/using-superpowers-sdd/SKILL.md", + "sha256": "a8cb5012d28ec6ace21ead813a787bd10dfe6d7f2286a3197610a451a7d6cb33" + }, + { + "path": "skills/spec-refactoring/SKILL.md", + "sha256": "39b6277f7a4e18048f343e58e17a96beb608d1a1f45924dc8303a17934bf54f6" + }, + { + "path": "skills/spec/SKILL.md", + "sha256": "e3b533f99474058f4bcf3a62490640a752310f27d657b8c295c8c47b25089cfc" + }, + { + "path": "skills/evolve/SKILL.md", + "sha256": "17d7072f8dfbd02c86472fd9ae9a487384226b624314d26b5b8aeaa852a494a4" + }, + { + "path": "skills/constitution/SKILL.md", + "sha256": "15313ce80a72bbc4a88a9c939223a549bdda9941e2dcaf50b422301dc6bc70d6" + }, + { + "path": "skills/spec-kit/SKILL.md", + "sha256": "467a3775eef8c11b31223511ed9b6c4773db5194c3284fc59d4f1ef541075155" + }, + { + "path": "skills/implement/SKILL.md", + "sha256": "0007d30d70a6d1f7b0cdde7ab91ebbe915cf9112f22f08b8148f7878de4500f2" + }, + { + "path": "skills/writing-plans/SKILL.md", + "sha256": "851c271e7b2958127fcbdf5f180b757d8999c01613d7fd072b76acd5c0ed8368" + }, + { + "path": "skills/verification-before-completion/SKILL.md", + "sha256": "5fc420b327486a6f05c7b2c854e9a08f49b5dc0a7a854fb662e73749a2c6fff5" + } + ], + "dirSha256": "71d8c21f24d6a6239f4172c8120ac1612292706c17824cae1b1f0717891508d7" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file diff --git a/skills/brainstorm/SKILL.md b/skills/brainstorm/SKILL.md new file mode 100644 index 0000000..299ec55 --- /dev/null +++ b/skills/brainstorm/SKILL.md @@ -0,0 +1,314 @@ +--- +name: brainstorm +description: Use when starting from rough ideas - refines concepts into executable specifications through collaborative questioning, alternative exploration, and incremental validation, use this skill when called from a command +--- + +# Brainstorming Ideas Into Specifications + +## Overview + +Help turn rough ideas into formal, executable specifications through natural collaborative dialogue. + +Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, create the specification using spec-kit (if available) or directly as markdown. + +**Key Difference from Standard Brainstorming:** +- **Output is a SPEC**, not a design document +- Spec is the **source of truth** for implementation +- Focus on **"what" and "why"**, defer "how" to implementation phase +- Validate spec soundness before finishing + +## Prerequisites + +Before starting the brainstorming workflow, ensure spec-kit is initialized: + +{Skill: spec-kit} + +If spec-kit prompts for restart, pause this workflow and resume after restart. + +## The Process + +### Understanding the idea + +**Check context first:** +- Review existing specs (if any) in `specs/` directory +- Check for constitution (`specs/constitution.md`) +- Review recent commits to understand project state +- Look for related features or patterns + +**Ask questions to refine:** +- Ask questions one at a time +- Prefer multiple choice when possible +- Focus on: purpose, constraints, success criteria, edge cases +- Identify dependencies and integrations + +**Remember:** You're building a SPEC, so focus on WHAT needs to happen, not HOW it will be implemented. + +### Exploring approaches + +**Propose 2-3 different approaches:** +- Present options conversationally with trade-offs +- Lead with your recommended option +- Explain reasoning clearly +- Consider: complexity, maintainability, user impact + +**Questions to explore:** +- What are the core requirements vs. nice-to-have? +- What are the error cases and edge conditions? +- How does this integrate with existing features? +- What are the success criteria? + +### Creating the specification + +**Once you understand what you're building:** + +1. **Announce spec creation:** + "Based on our discussion, I'm creating the specification..." + +2. **Create spec file:** + - Location: `specs/features/[feature-name]/spec.md` + - Use spec-kit CLI if available: `speckit specify` + - Otherwise: Create markdown directly + +3. **IMPORTANT: Capture implementation insights separately** + + If technical details emerged during brainstorming (technology choices, architecture decisions, trade-off discussions), **create implementation-notes.md** to capture them: + + - Location: `specs/features/[feature-name]/implementation-notes.md` + - Purpose: Document the "why" behind design decisions + - Content: + - Alternative approaches considered + - Trade-offs discussed + - Technology choices and rationale + - Technical constraints discovered + - Questions answered during brainstorming + + **Why separate from spec:** + - Spec = WHAT and WHY (requirements, contracts) + - Implementation notes = Technical context for HOW + - Keeps spec stable while preserving valuable context + - Helps future implementers understand decisions + + **Example content:** + ```markdown + # Implementation Notes: User Authentication + + ## Design Decisions + + ### Decision: OAuth vs. Magic Links + - Chose OAuth (Google + GitHub) + - Rationale: User preference for familiar login flow + - Rejected magic links: Email deliverability concerns + + ### Decision: JWT in httpOnly cookies + - Prevents XSS attacks + - Refresh token rotation for security + - Trade-off: Slightly more complex than localStorage + ``` + +4. **Spec structure** (use this template): + +```markdown +# Feature: [Feature Name] + +## Purpose +[Why this feature exists - the problem it solves] + +## Requirements + +### Functional Requirements +- [What the feature must do] +- [Behavior in specific scenarios] +- [Integration points] + +### Non-Functional Requirements +- [Performance constraints] +- [Security requirements] +- [Accessibility needs] + +## Success Criteria +- [How we know it works] +- [Measurable outcomes] + +## Error Handling +- [What can go wrong] +- [How errors should be handled] + +## Edge Cases +- [Boundary conditions] +- [Unusual scenarios] + +## Dependencies +- [Other features/systems required] +- [External services] + +## Out of Scope +- [What this feature explicitly does NOT do] +- [Future considerations] + +## Open Questions +- [Anything still unclear] +- [Decisions deferred to implementation] +``` + +4. **Validate against constitution** (if exists): + - Read `specs/constitution.md` + - Check spec aligns with project principles + - Note any violations and address them + +5. **Present spec in sections:** + - Show 200-300 words at a time + - Ask: "Does this look right so far?" + - Be ready to revise based on feedback + +### After spec creation + +**Validate the spec:** +- Use `sdd:review-spec` to check soundness +- Ensure spec is implementable +- Confirm no ambiguities remain + +**Offer next steps:** +- "Spec created and validated. Ready to implement?" +- If yes → Use `sdd:implement` +- If no → Offer to refine spec or pause + +**Commit the spec:** +```bash +git add specs/features/[feature-name].md +git commit -m "Add spec for [feature name] + +[Brief description of what the feature does] + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +Co-Authored-By: Claude " +``` + +## Key Principles + +- **One question at a time** - Don't overwhelm with multiple questions +- **Multiple choice preferred** - Easier to answer than open-ended +- **YAGNI ruthlessly** - Remove unnecessary features from all specs +- **Explore alternatives** - Always propose 2-3 approaches before settling +- **Incremental validation** - Present spec in sections, validate each +- **Be flexible** - Go back and clarify when something doesn't make sense +- **Separate WHAT from HOW** - Spec focuses on requirements and contracts; implementation notes capture technical decisions +- **Capture context** - If technical details emerge, put them in implementation-notes.md, not the spec +- **Spec, not design** - Focus on WHAT, defer HOW to implementation + +## Recommend Constitution (First Time Users) + +If no constitution exists and this seems to be early in project: + +**After first spec created:** +- "I notice you don't have a constitution yet." +- "A constitution defines project-wide principles like:" + - Coding standards + - Architectural patterns + - Quality gates + - Error handling approaches +- "Would you like to create one? It ensures consistency across features." +- If yes → Use `sdd:constitution` + +**Don't be pushy:** Constitution is optional but recommended. + +## Checklist + +Use TodoWrite to track: + +- [ ] Understand current project context +- [ ] Ask questions to refine idea +- [ ] Explore 2-3 approaches with trade-offs +- [ ] Create specification file +- [ ] Validate against constitution (if exists) +- [ ] Review spec for soundness +- [ ] Commit spec to git +- [ ] Offer next steps (implement or refine) + +## Example Flow + +``` +User: I want to add a comment system to the blog + +You: I'm using sdd:brainstorm to refine this idea into a spec. + +Let me understand the context first... +[Reviews existing code and specs] + +For the comment system, what level of features do you want? + +A) Basic - Name, email, comment text only +B) Standard - Above + threading/replies +C) Advanced - Above + reactions, editing, moderation +D) Full - Above + notifications, mentions, markdown + +User: B - Standard with threading + +You: Great. For threading, should replies be: + +A) Unlimited depth (comments on comments on comments...) +B) One level only (reply to top-level comments) +C) Two levels (reply and one nested level) + +[... conversation continues ...] + +You: Based on our discussion, I'm creating the specification at: +specs/features/blog-comments.md + +[Creates spec with all discussed requirements] + +Here's the Purpose and Requirements section: + +## Purpose +Enable readers to discuss blog posts through threaded comments, +fostering community engagement and feedback. + +## Requirements + +### Functional Requirements +- Readers can submit comments on published blog posts +- Comments require: name, email, comment text +- Comments support one level of replies (threading) +- Comments display in chronological order, newest first +- Replies display under parent comment +... + +Does this look right so far? + +User: Yes + +[... continues through all sections ...] + +You: Spec created! Let me validate it for soundness... + +[Runs sdd:review-spec] + +Spec is sound and implementable ✓ + +Committed to git ✓ + +Ready to implement the comment system? +``` + +## Common Pitfalls + +**Don't:** +- Create design documents instead of specs +- Include implementation details ("use Redis for caching") +- Make decisions that belong in implementation phase +- Skip exploring alternatives +- Rush to spec creation before understanding the problem + +**Do:** +- Focus on requirements and behavior +- Specify WHAT, not HOW +- Explore multiple approaches +- Validate incrementally +- Check against constitution +- Ensure spec is implementable + +## Remember + +The spec you create here becomes the source of truth. Implementation will flow from it. Code reviews will validate against it. Make it clear, complete, and correct. + +**Good specs enable good implementation. Take the time to get it right.** diff --git a/skills/constitution/SKILL.md b/skills/constitution/SKILL.md new file mode 100644 index 0000000..e8a5bf3 --- /dev/null +++ b/skills/constitution/SKILL.md @@ -0,0 +1,518 @@ +--- +name: constitution +description: Create and manage project constitution - defines project-wide principles, patterns, and standards that guide all specs and implementations +--- + +# Project Constitution Management + +## Overview + +Create and maintain a project constitution that defines project-wide principles, standards, and patterns. + +A constitution provides: +- Architectural decisions +- Coding standards +- Error handling patterns +- Quality gates +- Common practices + +All specs are validated against the constitution for consistency. + +## Prerequisites + +Ensure spec-kit is initialized: + +{Skill: spec-kit} + +If spec-kit prompts for restart, pause this workflow and resume after restart. + +## What is a Constitution? + +**Purpose:** +Document project-wide rules that ensure consistency across features. + +**Contains:** +- Architectural principles +- Coding standards +- API design patterns +- Error handling approaches +- Security requirements +- Testing standards +- Performance requirements +- Accessibility standards + +**Benefits:** +- Consistency across features +- Onboarding documentation +- Design decision record +- Spec validation reference + +## When to Create + +**Good times:** +- New project starting +- After second or third feature (patterns emerging) +- Team wants consistency +- Before major expansion + +**Bad times:** +- First feature (too early, no patterns yet) +- During active implementation +- As reaction to single issue + +**Rule of thumb:** Create after you see patterns repeating. + +## The Process + +### 1. Decide if Constitution Needed + +**Ask:** +- Are there repeated patterns in specs? +- Do you want consistency enforced? +- Is this a team project? +- Is this a long-term project? + +**If solo + small project:** Constitution might be overkill + +**If team OR large OR long-term:** Constitution recommended + +### 2. Gather Existing Patterns + +**Review existing specs:** +```bash +ls specs/features/ +cat specs/features/*.md +``` + +**Identify patterns:** +- How do we handle errors? +- What API patterns do we follow? +- What security requirements are common? +- What coding standards do we use? + +**Extract commonalities:** +Make implicit standards explicit. + +### 3. Use Spec-Kit or Manual Creation + +**With spec-kit:** +```bash +speckit constitution +``` + +**Manual creation:** +Create `specs/constitution.md` with template below. + +### 4. Create Constitution Content + +**Template:** + +```markdown +# Project Constitution + +**Project:** [Project Name] +**Created:** YYYY-MM-DD +**Last Updated:** YYYY-MM-DD + +## Purpose + +This constitution defines project-wide principles, patterns, and standards. +All features and implementations must align with these principles. + +## Architectural Principles + +### [Principle Name] +**Description:** [What this principle means] +**Rationale:** [Why we follow this] +**Examples:** +- ✓ [Good example] +- ✗ [Bad example] + +[Repeat for each principle] + +## API Design Standards + +### RESTful Conventions +- Use standard HTTP methods (GET, POST, PUT, DELETE) +- Plural resource names (/users, not /user) +- Return appropriate status codes +- Use JSON for request/response bodies + +### Error Responses +**Format:** +```json +{ + "error": "Human-readable error message", + "code": "ERROR_CODE", + "details": { ... } +} +``` + +**Status Codes:** +- 400: Bad Request (client error) +- 401: Unauthorized (auth required) +- 403: Forbidden (auth insufficient) +- 404: Not Found +- 422: Unprocessable Entity (validation failed) +- 500: Internal Server Error + +## Error Handling + +### Approach +- All errors must be handled explicitly +- Use try-catch for I/O operations +- Log errors with context +- Return user-friendly messages + +### Retry Logic +- Database operations: 3 retries with exponential backoff +- External APIs: 2 retries with fixed delay +- Timeout: 30 seconds for external calls + +## Security Requirements + +### Authentication +- All API endpoints require JWT authentication (except public endpoints) +- JWTs expire after 30 minutes +- Refresh tokens expire after 7 days + +### Input Validation +- Validate all user input +- Sanitize before database operations +- Reject unexpected fields + +### Secrets Management +- Never commit secrets to git +- Use environment variables +- Rotate secrets quarterly + +## Testing Standards + +### Coverage Requirements +- Minimum 80% code coverage +- 100% coverage for critical paths + +### Test Types +- Unit tests for all functions +- Integration tests for API endpoints +- E2E tests for critical user flows + +### Test Organization +- Tests in `tests/` directory +- Mirror source structure +- Use descriptive test names + +## Performance Requirements + +### Response Times +- API responses: < 200ms (p95) +- Database queries: < 50ms (p95) +- Page loads: < 2 seconds + +### Scalability +- Design for 10,000 concurrent users +- Horizontal scaling preferred +- Stateless where possible + +## Code Quality Standards + +### Code Style +- Follow [ESLint/Prettier/etc.] configuration +- Consistent naming conventions +- Comments for complex logic only + +### Code Review +- All code must be reviewed +- Spec compliance verified +- Tests required before merge + +## Accessibility Standards + +### WCAG Compliance +- Meet WCAG 2.1 Level AA +- Keyboard navigation required +- Screen reader compatible + +## Documentation Standards + +### Code Documentation +- JSDoc for public functions +- README in each module +- Architecture diagrams for complex systems + +### Spec Documentation +- All features must have specs +- Specs updated with changes +- Specs validated before implementation + +## Change Management + +### Updating This Constitution +- Requires team discussion (if team) +- Document rationale for changes +- Update all affected specs +- Communicate changes + +### Exceptions +- Exceptions must be documented in spec +- Requires justification +- Reviewed during code review + +## Glossary + +**[Term 1]:** [Definition] +**[Term 2]:** [Definition] + +## Decision Log + +### [Decision Date]: [Decision Title] +**Context:** [Why decision needed] +**Decision:** [What was decided] +**Rationale:** [Why this decision] +**Implications:** [What this affects] + +[Add new decisions here] +``` + +### 5. Review and Refine + +**Questions to ask:** +- Is this too restrictive? +- Is this clear enough? +- Can we realistically follow this? +- Does this reflect our actual practices? + +**Adjust as needed.** + +### 6. Validate Against Existing Specs + +**Check existing specs:** +```bash +# For each existing spec +cat specs/features/[feature].md + +# Does it align with constitution? +# Any violations? +``` + +**If violations found:** +- Update spec, OR +- Update constitution (if spec is right), OR +- Note as exception + +### 7. Commit Constitution + +```bash +git add specs/constitution.md +git commit -m "Add project constitution + +Defines project-wide principles and standards: +- Architectural principles +- API design standards +- Error handling patterns +- Security requirements +- Testing standards +- Code quality standards + +All future specs will be validated against this constitution. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +Co-Authored-By: Claude " +``` + +### 8. Communicate and Adopt + +**For team projects:** +- Share with team +- Get consensus +- Document exceptions +- Reference in onboarding + +**For solo projects:** +- Keep visible +- Reference when creating specs +- Update as you learn + +## Constitution Checklist + +Use TodoWrite to track: + +- [ ] Decide if constitution needed +- [ ] Gather existing patterns from specs/code +- [ ] Create constitution file (spec-kit or manual) +- [ ] Fill in all relevant sections +- [ ] Review for clarity and feasibility +- [ ] Validate against existing specs +- [ ] Handle any violations found +- [ ] Commit constitution to git +- [ ] Communicate to team (if applicable) + +## Example Constitution + +```markdown +# Todo App Project Constitution + +**Created:** 2025-11-10 + +## Purpose + +Define standards for the todo app project to ensure consistency. + +## Architectural Principles + +### RESTful API Design +All endpoints follow REST conventions: +- `GET /api/todos` - List todos +- `POST /api/todos` - Create todo +- `PUT /api/todos/:id` - Update todo +- `DELETE /api/todos/:id` - Delete todo + +### Data Validation +- Validate on server (never trust client) +- Return 422 for validation failures +- Provide specific error messages + +## Error Handling + +### Error Response Format +```json +{ + "error": "Human-readable message", + "field": "field_name", // for validation errors + "code": "ERROR_CODE" +} +``` + +### Common Errors +- 400: Malformed request +- 401: Not authenticated +- 404: Todo not found +- 422: Validation failed (e.g., title too long) + +## Testing Standards + +### Requirements +- All endpoints have integration tests +- All validation rules have tests +- Edge cases tested + +### Coverage +- Minimum 80% coverage +- 100% coverage for API endpoints + +## Code Quality + +### Naming +- camelCase for variables and functions +- PascalCase for classes +- UPPER_CASE for constants + +### Comments +- JSDoc for public functions +- Inline comments for complex logic only + +## Security + +### Authentication +- JWT tokens required for all /api/* endpoints +- Tokens expire after 1 hour +- Refresh on activity + +### Input Sanitization +- Escape HTML in todo titles/descriptions +- Limit field lengths (title: 200 chars, description: 2000 chars) + +## Decision Log + +### 2025-11-10: Use JWT for Auth +**Context:** Need authentication for multi-user support +**Decision:** Use JWT tokens stored in httpOnly cookies +**Rationale:** Secure, stateless, industry standard +**Implications:** Need token refresh mechanism, logout handling +``` + +## Maintaining the Constitution + +**Update when:** +- New patterns emerge +- Decisions change +- Standards evolve +- Exceptions become rules + +**Don't update when:** +- Single feature needs exception +- Trying to justify shortcut +- Reacting to single issue + +**Update process:** +1. Propose change +2. Update constitution +3. Update affected specs +4. Communicate change +5. Add to decision log + +## Common Sections + +### Minimal Constitution +- Architectural principles +- Error handling +- Testing standards + +### Standard Constitution +- Above, plus: +- API design +- Security requirements +- Code quality + +### Comprehensive Constitution +- Above, plus: +- Performance requirements +- Accessibility standards +- Deployment practices +- Monitoring/observability + +**Start minimal, expand as needed.** + +## Anti-Patterns + +**Avoid:** +- Creating constitution too early (no patterns yet) +- Making it too restrictive (can't follow it) +- Copying from other projects (doesn't fit yours) +- Never updating it (becomes outdated) +- Not following it (then why have it?) + +**Instead:** +- Wait for patterns to emerge +- Make it realistic and followable +- Extract from your own project +- Update as project evolves +- Enforce during spec validation + +## Remember + +**Constitution is living document.** + +- Starts small, grows with project +- Reflects actual practices +- Updated as standards evolve +- Referenced regularly + +**Constitution enables consistency.** + +- Specs validated against it +- Reduces decision fatigue +- Onboards new developers +- Documents architectural decisions + +**Constitution serves the project.** + +- Not rigid rules set in stone +- Pragmatic guidelines +- Updated when they don't serve +- Exceptions documented + +**Good constitution helps. Bad constitution hinders.** + +Make yours helpful. diff --git a/skills/evolve/SKILL.md b/skills/evolve/SKILL.md new file mode 100644 index 0000000..fa0e5de --- /dev/null +++ b/skills/evolve/SKILL.md @@ -0,0 +1,534 @@ +--- +name: evolve +description: Use when spec and code diverge - AI analyzes mismatches, recommends update spec vs fix code with reasoning, handles evolution with user control or auto-updates +--- + +# Spec Evolution and Reconciliation + +## Overview + +Handle spec/code mismatches through AI-guided analysis and user-controlled evolution. + +Specs WILL diverge from code. This is normal and healthy. The question is: which should change? + +This skill detects divergence, analyzes the mismatch, recommends resolution, and executes the change. + +## When to Use + +**Use this skill when:** +- Code review detects spec/code mismatch +- Verification finds spec compliance issues +- Developer explicitly requests evolution +- Implementation reveals better approach than spec +- Spec ambiguity discovered during implementation + +**Auto-triggered by:** +- `sdd:review-code` (when deviations found) +- `sdd:verification-before-completion` (when compliance fails) + +**Don't use this skill when:** +- No mismatch exists (everything compliant) +- Spec doesn't exist yet → Use `sdd:spec` +- Multiple specs need consolidation → Use `sdd:spec-refactoring` + +## Prerequisites + +Ensure spec-kit is initialized: + +{Skill: spec-kit} + +If spec-kit prompts for restart, pause this workflow and resume after restart. + +## The Process + +### 1. Detect Mismatches + +**Identify all spec/code divergences:** + +```bash +# Read spec +cat specs/features/[feature-name].md + +# Compare to implementation +# For each requirement in spec: +# - What does spec say? +# - What does code do? +# - Do they match? +``` + +**Categorize each mismatch:** +- **Missing in code**: Spec requires it, code doesn't have it +- **Extra in code**: Code implements it, spec doesn't mention it +- **Different behavior**: Spec says X, code does Y +- **Ambiguous spec**: Spec unclear, code made assumption + +**Document all mismatches with:** +- Spec requirement (quote from spec) +- Actual implementation (what code does) +- Location (file:line in code, section in spec) + +### 2. Analyze Each Mismatch + +**For each mismatch, determine:** + +**Type:** +- Architectural (affects system design) +- Behavioral (changes functionality) +- Cosmetic (naming, organization, details) + +**Severity:** +- **Critical**: Breaking change, security issue, data loss +- **Major**: Significant behavior change, API contract change +- **Minor**: Small deviation, non-breaking addition +- **Trivial**: Naming, formatting, implementation details + +**Impact:** +- User-facing vs internal +- Breaking vs non-breaking +- Risky vs safe + +### 3. Recommend Resolution + +**For each mismatch, recommend:** + +**Option A: Update Spec** +- When: Implementation reveals better approach +- Why: Spec was incomplete/wrong, code is better +- Impact: Spec changes to match reality + +**Option B: Fix Code** +- When: Code deviates from intended design +- Why: Spec is correct, code is wrong +- Impact: Code changes to match spec + +**Option C: Clarify Spec** +- When: Spec was ambiguous, code made reasonable choice +- Why: Make implicit explicit +- Impact: Spec expanded with details, code unchanged + +**Provide reasoning for recommendation:** +- Why this option is best +- Trade-offs of alternatives +- Risk assessment +- User impact + +### 4. Decide Resolution + +**Decision flow:** + +``` +Is this mismatch trivial/minor AND auto-update enabled? + Yes → Auto-update with notification + No → Ask user to decide + +User decides: + A) Update spec + B) Fix code + C) Clarify spec + D) Defer (mark as known deviation) +``` + +**Check user configuration:** + +```json +{ + "sdd": { + "auto_update_spec": { + "enabled": true, + "threshold": "minor", // "none", "minor", "moderate" + "notify": true + } + } +} +``` + +**Thresholds:** +- `none`: Never auto-update +- `minor`: Auto-update trivial/minor mismatches +- `moderate`: Include non-breaking behavioral changes + +### 5. Execute Resolution + +**Option A: Update Spec** + +1. Modify spec to match implementation +2. Add to spec changelog +3. Validate updated spec for soundness +4. Commit spec change with clear message + +```bash +# Update spec +vim specs/features/[feature].md + +# Add changelog entry +echo "- YYYY-MM-DD: Updated [requirement] to include [change]" >> specs/features/[feature].md + +# Commit +git add specs/features/[feature].md +git commit -m "Update spec: [change] + +Implementation revealed [reason for change]. + +Previous: [old requirement] +Updated: [new requirement] + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +Co-Authored-By: Claude " +``` + +**Option B: Fix Code** + +1. Modify code to match spec +2. Update tests if needed +3. Verify spec compliance +4. Commit code change + +```bash +# Fix code +[Make changes to match spec] + +# Update tests +[Adjust tests to match spec] + +# Verify compliance +[Run sdd:verification-before-completion] + +# Commit +git add [files] +git commit -m "Fix: Align [component] with spec + +Code was [what it did], spec requires [what spec says]. + +Updated to match spec requirement: [spec section] + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +Co-Authored-By: Claude " +``` + +**Option C: Clarify Spec** + +1. Add detail to spec (keep code unchanged) +2. Make implicit assumptions explicit +3. Add to spec changelog +4. Commit clarification + +**Option D: Defer** + +1. Document as known deviation +2. Add to spec's "Known Deviations" section +3. Note reason and plan to address +4. Commit documentation + +### 6. Verify Reconciliation + +**After resolution:** + +```bash +# Re-check spec compliance +# Ensure mismatch is resolved +# Verify no new mismatches introduced +``` + +**Confirm:** +- Spec and code now aligned +- Tests still passing +- No regressions introduced + +## Checklist + +Use TodoWrite to track: + +- [ ] Detect all spec/code mismatches +- [ ] Categorize each mismatch (type, severity, impact) +- [ ] Analyze and recommend resolution for each +- [ ] Check user configuration for auto-update +- [ ] Decide resolution (auto or ask user) +- [ ] Execute resolution (update spec, fix code, or clarify) +- [ ] Verify reconciliation complete +- [ ] Commit changes with clear messages +- [ ] Update documentation if needed + +## Examples + +### Example 1: Auto-Update (Minor Addition) + +``` +[During verification] + +Spec compliance check: 95% + +Mismatch detected: + +**Mismatch 1: Response includes timestamp (MINOR)** +- **Spec says:** Return `{ id, name, email }` +- **Code does:** Returns `{ id, name, email, updated_at }` +- **Location:** src/api/users.ts:45, specs/features/user-api.md#response + +**Analysis:** +- Type: Behavioral (but non-breaking addition) +- Severity: Minor +- Impact: Non-breaking, adds useful information + +**Recommendation: Update Spec (Option A)** + +**Reasoning:** +- `updated_at` is standard practice for update endpoints +- Provides useful information to clients +- Non-breaking addition (clients can ignore it) +- Implementation is better than spec + +**User config:** auto_update_spec.threshold = "minor" + +**Action:** Auto-updating spec... + +Updated specs/features/user-api.md: +- Added `updated_at` to response format +- Changelog: "2025-11-10: Added updated_at timestamp to responses" + +✅ Spec updated +✅ Compliance now 100% +✅ Committed to git + +Notification: Spec auto-updated with updated_at field (minor addition) +``` + +### Example 2: User Decision (Major Change) + +``` +[During code review] + +Spec compliance check: 85% + +Mismatch detected: + +**Mismatch 1: Validation behavior difference (MAJOR)** +- **Spec says:** "Reject requests with invalid avatar_url, return 422" +- **Code does:** "Accept invalid URLs, set avatar_url to null, return 200" +- **Location:** src/middleware/validation.ts:78, specs/features/user-profile.md#validation + +**Analysis:** +- Type: Behavioral (changes error handling) +- Severity: Major +- Impact: User-facing, affects API contract + +**Options:** + +**A) Update Spec - Lenient validation** +- Pros: More user-friendly, prevents frustration +- Cons: Inconsistent with other validation (strict) +- Risk: Users might not know avatar failed + +**B) Fix Code - Strict validation** +- Pros: Consistent with spec and other validation +- Cons: Worse UX when URL is invalid +- Risk: None (matches spec) + +**C) Clarify Spec - Explicit fallback** +- Pros: Best of both (validate but handle gracefully) +- Cons: More complex +- Risk: None + +**Recommendation: Option C** + +**Reasoning:** +Best practice is to validate input but handle gracefully. Update spec to explicitly define fallback behavior: validate URL, set to null if invalid, log warning, return success with indication. + +Which option do you prefer? + +User: C - explicit fallback + +You: Perfect. Updating spec to clarify fallback behavior... + +Updated spec: + +## Validation Rules + +### avatar_url +- Must be valid URL format if provided +- **Fallback behavior:** If URL validation fails: + - Set avatar_url to null + - Log validation error + - Return 200 (success) with warning in response + - Response includes: `warnings: ["avatar_url invalid, set to null"]` + +Code now matches clarified spec ✅ + +Spec compliance: 100% + +Committed to git ✅ +``` + +### Example 3: Fix Code (Spec Correct) + +``` +[During verification] + +Spec compliance check: 90% + +Mismatch detected: + +**Mismatch 1: Missing error handling (CRITICAL)** +- **Spec says:** "Handle database connection errors with retry logic (3 attempts)" +- **Code does:** "Single attempt, fails immediately on error" +- **Location:** src/db/client.ts:34, specs/features/data-persistence.md#error-handling + +**Analysis:** +- Type: Architectural (missing reliability mechanism) +- Severity: Critical +- Impact: Production reliability risk + +**Recommendation: Fix Code (Option B)** + +**Reasoning:** +- Spec defines critical reliability requirement +- Single-attempt fails too easily (production risk) +- Retry logic is standard practice +- Code is missing required feature + +**No user decision needed - critical spec requirement missing** + +Fixing code to implement retry logic... + +```typescript +// Added retry logic +async function queryWithRetry(sql, params, attempts = 3) { + for (let i = 0; i < attempts; i++) { + try { + return await db.query(sql, params); + } catch (error) { + if (i === attempts - 1) throw error; + await sleep(1000 * (i + 1)); // Exponential backoff + } + } +} +``` + +Tests updated to verify retry behavior ✅ +Spec compliance: 100% ✅ + +Committed code fix ✅ +``` + +## Auto-Update Configuration + +### Recommended Settings + +**For solo projects:** +```json +{ + "auto_update_spec": { + "enabled": true, + "threshold": "minor", + "notify": true + } +} +``` + +**For team projects:** +```json +{ + "auto_update_spec": { + "enabled": true, + "threshold": "none", // Always ask + "notify": true + } +} +``` + +**For experimental work:** +```json +{ + "auto_update_spec": { + "enabled": true, + "threshold": "moderate", + "notify": true + } +} +``` + +## Classification Guidelines + +### Minor (Auto-Update Eligible) +- Adding timestamps to responses +- Renaming variables/functions +- Reorganizing code structure +- Adding logging/instrumentation +- Implementation detail changes + +### Major (Always Ask) +- Changing API contracts +- Modifying behavior +- Adding/removing features +- Changing error handling +- Architectural changes + +### Critical (Usually Fix Code) +- Security issues +- Data integrity problems +- Missing required features +- Incorrect business logic + +## Common Patterns + +### Pattern: Better Error Messages + +**Mismatch:** Spec says "return error", code returns detailed error with context + +**Resolution:** Update spec (minor) +- More detailed errors are better +- Non-breaking improvement + +### Pattern: Missing Edge Case + +**Mismatch:** Spec doesn't mention empty array, code handles it + +**Resolution:** Clarify spec (add edge case) +- Make implicit explicit +- Document intended behavior + +### Pattern: Performance Optimization + +**Mismatch:** Spec doesn't specify caching, code adds cache + +**Resolution:** Update spec (moderate) +- Document optimization in spec +- Ensure cache behavior is correct + +### Pattern: Different Architecture + +**Mismatch:** Spec implies synchronous, code is async + +**Resolution:** Ask user (major) +- Significant architectural change +- May affect other components + +## Remember + +**Spec evolution is normal and healthy.** + +- Specs are not contracts set in stone +- Implementation reveals reality +- Better approaches emerge during coding +- Ambiguities get discovered + +**The goal is alignment, not rigidity.** + +- Specs guide implementation +- Implementation informs specs +- Both should reflect truth + +**Always provide reasoning:** +- Why update spec vs fix code +- What's the impact +- What are the trade-offs + +**Trust the process:** +- Detect mismatches early +- Analyze thoughtfully +- Recommend clearly +- Execute decisively +- Verify completely + +**Spec and code in sync = quality software.** diff --git a/skills/implement/SKILL.md b/skills/implement/SKILL.md new file mode 100644 index 0000000..f640bfb --- /dev/null +++ b/skills/implement/SKILL.md @@ -0,0 +1,432 @@ +--- +name: implement +description: Use when spec exists and is validated - generates implementation plan FROM spec, executes with TDD, and verifies spec compliance throughout +--- + +# Spec-Driven Implementation + +## Overview + +Implement features from validated specifications using Test-Driven Development, with continuous spec compliance checking throughout. + +This is the core SDD implementation workflow: Spec → Plan → TDD → Verify. + +**Critical Rule:** Implementation MUST match spec. Any deviation triggers spec evolution workflow. + +## When to Use + +**Use this skill when:** +- Spec exists and is validated +- Ready to write code +- Starting implementation of new feature + +**Don't use this skill when:** +- No spec exists → Use `sdd:spec` or `sdd:brainstorm` first +- Spec/code mismatch exists → Use `sdd:evolve` +- Debugging existing code → Use `systematic-debugging` + +## Technical Prerequisites + +Ensure spec-kit is initialized: + +{Skill: spec-kit} + +If spec-kit prompts for restart, pause this workflow and resume after restart. + +## Workflow Prerequisites + +**Before starting implementation:** +- [ ] Spec exists in `specs/features/[feature-name].md` +- [ ] Spec validated for soundness (`sdd:review-spec`) +- [ ] Spec validated against constitution (if exists) +- [ ] No open questions in spec that block implementation + +**If prerequisites not met:** Stop and address them first. + +## The Process + +### 1. Read and Understand Spec + +**Load the spec:** +```bash +cat specs/features/[feature-name].md +``` + +**Extract key information:** +- Functional requirements (what to build) +- Success criteria (how to verify) +- Error handling (what can go wrong) +- Dependencies (what's needed) +- Constraints (limitations) + +**Validate understanding:** +- Summarize spec back to user +- Confirm no ambiguities remain +- Identify any implementation questions + +### 2. Generate Implementation Plan FROM Spec + +**Use `sdd:writing-plans` skill** to create plan. + +**The plan MUST:** +- Derive directly from spec requirements +- Include all functional requirements +- Cover all error cases +- Address all edge cases +- Reference spec sections explicitly + +**Plan structure:** +```markdown +# Implementation Plan: [Feature Name] + +**Source Spec:** specs/features/[feature-name].md +**Date:** YYYY-MM-DD + +## Requirements Coverage + +### Functional Requirement 1: [From spec] +**Implementation approach:** +- [ ] Task 1 +- [ ] Task 2 +... + +[Repeat for all functional requirements] + +## Error Handling Implementation + +[For each error case in spec] +- **Error:** [From spec] +- **Implementation:** [How to handle] + +## Test Strategy + +[How we'll verify each requirement] + +## Files to Create/Modify + +[List with file paths] + +## Verification Steps + +- [ ] All tests pass +- [ ] Spec compliance check passes +- [ ] Code review against spec +``` + +**Save plan:** `docs/plans/[date]-[feature]-implementation.md` + +### 3. Set Up Isolated Workspace + +**Use `using-git-worktrees`** (optional but recommended): + +```bash +git worktree add ../feature-[name] -b feature/[name] +cd ../feature-[name] +``` + +**Or work in current branch:** +- Ensure clean working directory +- Create feature branch if needed + +### 4. Implement with Test-Driven Development + +**Use `test-driven-development` skill.** + +**For each requirement in spec:** + +1. **Write test first** (based on spec requirement) + - Test validates spec requirement directly + - Include error cases from spec + - Include edge cases from spec + +2. **Watch it fail** + - Confirms test is testing the right thing + - Red phase of TDD + +3. **Write minimal code to pass** + - Implement spec requirement + - Don't add features not in spec + - Green phase of TDD + +4. **Refactor** + - Clean up while keeping tests green + - Refactor phase of TDD + +5. **Verify spec compliance** + - Does code match spec requirement? + - Check implementation against spec section + - Document any necessary deviations + +**Track progress with TodoWrite:** +- Mark requirements as in_progress/completed +- One requirement at a time +- Don't skip or batch + +### 5. Continuous Spec Compliance Checking + +**During implementation, regularly check:** + +```bash +# Compare implementation to spec +# For each functional requirement: +# - ✓ Implemented as specified +# - ✗ Deviation detected → document reason +``` + +**If deviation needed:** +- Document WHY spec cannot be followed +- Note what changed and reason +- Will trigger `sdd:evolve` during review + +### 6. Code Review Against Spec + +**Use `sdd:review-code` skill.** + +**Review checks:** +- Code implements all spec requirements +- No extra features beyond spec +- Error handling matches spec +- Edge cases covered per spec +- Tests validate spec requirements + +**Output:** +- Compliance score (% of requirements met) +- List of deviations with reasons +- Recommendations: approve or evolve + +### 7. Verification Before Completion + +**Use `sdd:verification-before-completion` skill.** + +**Verification steps:** +1. All tests pass +2. Spec compliance validation passes +3. No unaddressed deviations +4. All success criteria met (from spec) + +**If verification fails:** Fix issues before claiming completion. + +## Checklist + +Use TodoWrite to track: + +- [ ] Read and understand spec +- [ ] Generate implementation plan from spec +- [ ] Set up workspace (worktree or branch) +- [ ] For each requirement: TDD cycle (test, fail, implement, pass, refactor) +- [ ] Check spec compliance continuously +- [ ] Request code review against spec +- [ ] Run verification (tests + spec compliance) +- [ ] Address any deviations (evolve spec or fix code) +- [ ] Commit implementation +- [ ] Clean up workspace + +## Example Flow + +``` +User: Let's implement the user profile API from the spec + +You: I'm using sdd:implement to build this feature from the spec. + +Reading spec: specs/features/user-profile-api.md + +The spec defines: +- PUT /api/users/:id/profile endpoint +- Fields: name (2-50 chars), bio (max 500), avatar_url +- Auth: JWT required +- Errors: 401, 403, 404, 422 +- Success criteria: authenticated users can update profiles + +Generating implementation plan from spec... +[Uses sdd:writing-plans] + +Plan created: docs/plans/2025-11-10-user-profile-api-implementation.md + +Plan includes: +1. Create route handler (src/api/users/profile.ts) +2. Add validation middleware (src/middleware/validate-profile.ts) +3. Update service layer (src/services/user.ts) +4. Add tests (tests/api/users/profile.test.ts) + +Ready to implement with TDD. Starting... + +[Uses test-driven-development] + +Test 1: Should reject unauthenticated requests (Spec: Error Handling) + +Writing test... +```typescript +test('PUT /api/users/:id/profile returns 401 without JWT', async () => { + const response = await request(app) + .put('/api/users/123/profile') + .send({ name: 'Test' }); + + expect(response.status).toBe(401); + expect(response.body.error).toBe('Authentication required'); +}); +``` + +Running test... ❌ FAIL (expected - no auth implemented yet) + +Implementing auth middleware... +[Adds JWT validation] + +Running test... ✅ PASS + +Spec compliance check: +✓ Matches spec requirement: "User must be authenticated with valid JWT" +✓ Error message matches spec: "Authentication required" + +--- + +Test 2: Should validate name length (Spec: Functional Requirements #2) + +Writing test... +```typescript +test('PUT /api/users/:id/profile validates name length', async () => { + const token = generateTestJWT({ sub: '123' }); + + // Too short + let response = await request(app) + .put('/api/users/123/profile') + .set('Authorization', `Bearer ${token}`) + .send({ name: 'A' }); + + expect(response.status).toBe(422); + + // Too long + response = await request(app) + .put('/api/users/123/profile') + .set('Authorization', `Bearer ${token}`) + .send({ name: 'A'.repeat(51) }); + + expect(response.status).toBe(422); + + // Valid + response = await request(app) + .put('/api/users/123/profile') + .set('Authorization', `Bearer ${token}`) + .send({ name: 'Valid Name' }); + + expect(response.status).toBe(200); +}); +``` + +Running test... ❌ FAIL + +Implementing validation... +[Adds name length validation] + +Running test... ✅ PASS + +Spec compliance check: +✓ Matches spec: "name: string, 2-50 characters" + +--- + +[Continues through all requirements...] + +All requirements implemented ✓ + +Requesting code review against spec... +[Uses sdd:review-code] + +Code Review Results: +✓ All functional requirements implemented (6/6) +✓ All error cases handled (4/4) +✓ All edge cases covered (3/3) +✓ Tests validate spec requirements + +Spec Compliance: 100% + +Deviations detected: 1 +- Added `updated_at` field to response (not in spec) + Reason: Standard practice for update endpoints + Recommendation: Update spec (minor addition) + +Running verification... +[Uses sdd:verification-before-completion] + +✅ All tests passing (24/24) +✅ Spec compliance validated +⚠️ Minor deviation: updated_at field + +Recommendation: Use sdd:evolve to update spec with updated_at field + +You: Should I update the spec to include the updated_at field? +``` + +## Handling Deviations + +**When code deviates from spec:** + +1. **Document the deviation** during implementation +2. **Note the reason** (technical constraint, better approach, etc.) +3. **Continue implementation** (don't block on it) +4. **Trigger evolution** during review +5. **Use `sdd:evolve`** to reconcile + +**Never:** +- Silently deviate without documentation +- Force-fit code to incorrect spec +- Skip spec compliance checks + +## Integration with Superpowers Skills + +**This skill orchestrates:** +- `sdd:writing-plans` - Generate plan from spec +- `test-driven-development` - TDD implementation +- `sdd:review-code` - Spec compliance review +- `sdd:verification-before-completion` - Tests + spec validation +- `sdd:evolve` - If deviations need reconciliation + +**Also compatible with:** +- `using-git-worktrees` - Isolated workspace +- `systematic-debugging` - If bugs found during implementation + +## Success Criteria + +**Implementation is complete when:** +- [ ] All spec requirements implemented +- [ ] All tests passing +- [ ] Spec compliance 100% (or deviations reconciled) +- [ ] Code review passed +- [ ] Verification passed +- [ ] All success criteria from spec met + +## Common Pitfalls + +**Avoid:** +- Implementing features not in spec +- Skipping TDD (spec doesn't mean no tests!) +- Ignoring error cases from spec +- Deviating without documentation +- Claiming completion before verification + +**Instead:** +- Implement only what's in spec (YAGNI) +- TDD for every requirement +- Test all error cases from spec +- Document all deviations +- Verify before completing + +## Remember + +**The spec is your contract.** + +- Don't add features not in spec +- Don't skip requirements from spec +- Don't ignore error cases in spec +- Don't deviate silently + +**If spec is wrong or incomplete:** +- Document the issue +- Continue implementation +- Use `sdd:evolve` to fix spec + +**Quality gates exist for a reason:** +- TDD ensures testability +- Code review ensures compliance +- Verification ensures correctness + +**Follow the process. Ship quality code that matches the spec.** diff --git a/skills/review-code/SKILL.md b/skills/review-code/SKILL.md new file mode 100644 index 0000000..217342c --- /dev/null +++ b/skills/review-code/SKILL.md @@ -0,0 +1,350 @@ +--- +name: review-code +description: Review code against spec compliance - checks implementation matches spec requirements, identifies deviations, reports compliance score, triggers evolution if needed +--- + +# Code Review Against Specification + +## Overview + +Review code implementation against specification to ensure compliance. + +**Key Difference from Standard Code Review:** +- Primary focus: **Does code match spec?** +- Secondary focus: Code quality, patterns, best practices +- Output: **Compliance score** + deviation list +- Triggers: **Spec evolution** if mismatches found + +## When to Use + +- After implementation complete (called by `sdd:implement`) +- Before merging/deploying code +- When validating existing code against spec +- As part of verification workflow + +## The Process + +### 1. Load Spec and Code + +**Read specification:** +```bash +cat specs/features/[feature-name].md +``` + +**Identify implementation files:** +```bash +# From implementation plan or code exploration +ls -la [implementation-files] +``` + +### 2. Review Functional Requirements + +**For each functional requirement in spec:** + +1. **Find implementation** in code +2. **Compare behavior**: Does code do what spec says? +3. **Check completeness**: All aspects implemented? +4. **Note deviations**: Any differences? + +**Create compliance matrix:** +``` +Requirement 1: [Spec text] + Implementation: [file:line] + Status: ✓ Compliant | ✗ Deviation | ? Missing + Notes: [If deviation, explain] + +Requirement 2: [Spec text] + ... +``` + +### 3. Review Error Handling + +**For each error case in spec:** + +1. **Find error handling** in code +2. **Check error response**: Matches spec? +3. **Verify error codes**: Correct HTTP status / error codes? +4. **Test error messages**: Clear and helpful? + +**Error handling compliance:** +``` +Error Case 1: [From spec] + Implemented: Yes/No + Location: [file:line] + Response: [What code returns] + Spec Expected: [What spec says] + Status: ✓ / ✗ +``` + +### 4. Review Edge Cases + +**For each edge case in spec:** + +1. **Find handling** in code +2. **Check behavior**: Matches spec? +3. **Verify tests**: Edge case tested? + +### 5. Check for Extra Features + +**Identify code features NOT in spec:** + +- Functions/endpoints not mentioned in spec +- Behavior beyond spec requirements +- Additional error handling +- Extra validations + +**For each extra feature:** +- Document what it does +- Assess: Helpful addition or scope creep? +- Note for potential spec update + +### 6. Calculate Compliance Score + +**Formula:** +``` +Compliance % = (Compliant Requirements / Total Requirements) × 100 +``` + +**Include:** +- Functional requirements +- Error cases +- Edge cases +- Non-functional requirements + +**Example:** +``` +Functional: 8/8 = 100% +Error Cases: 3/4 = 75% +Edge Cases: 2/3 = 67% +Non-Functional: 3/3 = 100% + +Overall: 16/18 = 89% +``` + +### 7. Generate Report + +**Report structure:** + +```markdown +# Code Review: [Feature Name] + +**Spec:** specs/features/[feature].md +**Date:** YYYY-MM-DD +**Reviewer:** Claude (sdd:review-code) + +## Compliance Summary + +**Overall Score: XX%** + +- Functional Requirements: X/X (XX%) +- Error Handling: X/X (XX%) +- Edge Cases: X/X (XX%) +- Non-Functional: X/X (XX%) + +## Detailed Review + +### Functional Requirements + +#### ✓ Requirement 1: [Spec text] +**Implementation:** src/[file]:line +**Status:** Compliant +**Notes:** Correctly implemented as specified + +#### ✗ Requirement 2: [Spec text] +**Implementation:** src/[file]:line +**Status:** Deviation +**Issue:** [What differs from spec] +**Impact:** [Minor/Major] +**Recommendation:** [Update spec / Fix code] + +### Error Handling + +[Similar format for each error case] + +### Edge Cases + +[Similar format for each edge case] + +### Extra Features (Not in Spec) + +#### [Feature name] +**Location:** src/[file]:line +**Description:** [What it does] +**Assessment:** [Helpful / Scope creep] +**Recommendation:** [Add to spec / Remove] + +## Code Quality Notes + +[Secondary observations about code quality, patterns, etc.] + +## Recommendations + +### Critical (Must Fix) +- [ ] [Issue requiring immediate attention] + +### Spec Evolution Candidates +- [ ] [Deviation that might warrant spec update] + +### Optional Improvements +- [ ] [Nice-to-have suggestions] + +## Conclusion + +[Overall assessment] + +**Next Steps:** +- If compliance < 100%: Use `sdd:evolve` to reconcile deviations +- If compliance = 100%: Proceed to verification +``` + +### 8. Trigger Evolution if Needed + +**If deviations found:** +- Present review results to user +- Recommend using `sdd:evolve` +- Don't proceed to verification until resolved + +**If 100% compliant:** +- Approve for verification +- Proceed to `sdd:verification-before-completion` + +## Review Checklist + +Use TodoWrite to track: + +- [ ] Load specification +- [ ] Identify all implementation files +- [ ] Review each functional requirement +- [ ] Review each error case +- [ ] Review each edge case +- [ ] Identify extra features not in spec +- [ ] Calculate compliance score +- [ ] Generate detailed review report +- [ ] Make recommendations +- [ ] Trigger evolution if deviations found + +## Example Output + +``` +# Code Review: User Profile Update API + +**Spec:** specs/features/user-profile-api.md +**Date:** 2025-11-10 +**Reviewer:** Claude (sdd:review-code) + +## Compliance Summary + +**Overall Score: 94%** + +- Functional Requirements: 6/6 (100%) +- Error Handling: 4/4 (100%) +- Edge Cases: 3/3 (100%) +- Non-Functional: 2/3 (67%) + +## Detailed Review + +### Functional Requirements + +#### ✓ Requirement 1: PUT endpoint accepts requests +**Implementation:** src/api/users/profile.ts:12 +**Status:** Compliant +**Notes:** Route correctly configured at PUT /api/users/:id/profile + +#### ✓ Requirement 2: Validates request body +**Implementation:** src/middleware/validation/profile.ts:5 +**Status:** Compliant +**Notes:** All validations match spec (name 2-50, bio max 500, avatar_url URL) + +[... all ✓ ...] + +### Error Handling + +#### ✓ Error: Missing/Invalid JWT +**Implementation:** src/middleware/auth.ts:22 +**Status:** Compliant +**Spec Expected:** 401 with "Authentication required" +**Actual:** 401 with "Authentication required" ✓ + +[... all ✓ ...] + +### Non-Functional Requirements + +#### ✗ Performance: Response time < 200ms +**Status:** Not Verified +**Issue:** No performance testing implemented +**Impact:** Minor (likely meets requirement but unverified) +**Recommendation:** Add performance test or update spec to remove specific timing + +### Extra Features (Not in Spec) + +#### Updated timestamp in response +**Location:** src/api/users/profile.ts:45 +**Description:** Adds `updated_at` timestamp to response object +**Assessment:** Helpful - standard practice for update endpoints +**Recommendation:** Add to spec (minor addition) + +## Recommendations + +### Spec Evolution Candidates +- [ ] Add `updated_at` field to response spec (minor addition) +- [ ] Remove specific performance timing or add perf tests + +## Conclusion + +Code implementation is 94% compliant with spec. All functional requirements and error handling correctly implemented. One non-functional requirement unverified and one helpful feature added beyond spec. + +**Next Steps:** +Use `sdd:evolve` to update spec with: +1. `updated_at` field (minor addition) +2. Clarify performance requirement (remove specific timing or add test) + +After spec evolution, compliance will be 100%. +``` + +## Assessment Criteria + +### Compliant (✓) +- Code does exactly what spec says +- No deviations in behavior +- All aspects covered + +### Minor Deviation (⚠) +- Small differences (naming, details) +- Non-breaking additions +- Better error messages than spec +- Typically → Update spec + +### Major Deviation (✗) +- Different behavior than spec +- Missing functionality +- Wrong error handling +- Typically → Fix code or evolve spec + +### Missing (?) +- Spec requires it, code doesn't have it +- Critical gap +- Must fix code + +## Remember + +**Spec compliance is primary concern.** + +This is not just code quality review - it's **spec validation**. + +- Does code match spec? (Most important) +- Is code quality good? (Secondary) +- Any improvements? (Tertiary) + +**100% compliance is the goal.** + +- < 90%: Significant issues, fix before proceeding +- 90-99%: Minor deviations, likely spec updates +- 100%: Perfect compliance, ready for verification + +**Deviations trigger evolution.** + +- Don't force-fit wrong spec +- Don't ignore deviations +- Use `sdd:evolve` to reconcile + +**The code and spec must tell the same story.** diff --git a/skills/review-spec/SKILL.md b/skills/review-spec/SKILL.md new file mode 100644 index 0000000..924e376 --- /dev/null +++ b/skills/review-spec/SKILL.md @@ -0,0 +1,498 @@ +--- +name: review-spec +description: Review specifications for soundness, completeness, and implementability - validates structure, identifies ambiguities, checks for gaps before implementation +--- + +# Reviewing Specifications for Soundness + +## Overview + +Validate specification quality before implementation begins. + +A poor spec leads to confusion, rework, and spec/code drift. A sound spec enables smooth implementation. + +This skill checks: completeness, clarity, implementability, and testability. + +## When to Use + +- After spec creation (before implementation) +- Before generating implementation plan +- When spec seems unclear or incomplete +- Periodically for important specs + +## Prerequisites + +Ensure spec-kit is initialized: + +{Skill: spec-kit} + +If spec-kit prompts for restart, pause this workflow and resume after restart. + +## Review Dimensions + +### 1. Completeness +- All sections filled +- No TBD or placeholder text +- All requirements defined +- Success criteria specified + +### 2. Clarity +- No ambiguous language +- Concrete, specific requirements +- Edge cases explicitly defined +- Error handling specified + +### 3. Implementability +- Can generate implementation plan +- Dependencies identified +- Constraints realistic +- Scope manageable + +### 4. Testability +- Success criteria measurable +- Requirements verifiable +- Acceptance criteria clear + +## The Process + +### 1. Load and Read Spec + +```bash +cat specs/features/[feature-name].md +``` + +Read thoroughly, take notes on issues. + +### 2. Check Structure + +**Required sections (should exist):** +- [ ] Purpose/Overview +- [ ] Functional Requirements +- [ ] Success Criteria +- [ ] Error Handling + +**Recommended sections:** +- [ ] Non-Functional Requirements +- [ ] Edge Cases +- [ ] Dependencies +- [ ] Constraints +- [ ] Out of Scope + +**If sections missing:** +- Note which ones +- Assess if truly needed for this spec +- Recommend additions + +### 3. Review Completeness + +**For each section, check:** + +**Purpose:** +- [ ] Clearly states why feature exists +- [ ] Describes problem being solved +- [ ] Avoids implementation details + +**Functional Requirements:** +- [ ] Numbered/listed clearly +- [ ] Each requirement is specific +- [ ] No "TBD" or placeholders +- [ ] All aspects covered + +**Success Criteria:** +- [ ] Measurable outcomes defined +- [ ] Clear completion indicators +- [ ] Testable assertions + +**Error Handling:** +- [ ] All error cases identified +- [ ] Handling approach specified +- [ ] Error messages/codes defined + +**Edge Cases:** +- [ ] Boundary conditions listed +- [ ] Expected behavior specified +- [ ] Not marked as "TBD" + +### 4. Check for Ambiguities + +**Red flag words/phrases:** +- "should" (vs "must") +- "might", "could", "probably" +- "fast", "slow" (without metrics) +- "user-friendly" (vague) +- "handle appropriately" (non-specific) +- "etc." (incomplete list) +- "similar to..." (unclear) + +**For each ambiguity:** +- Identify the vague requirement +- Note what's unclear +- Suggest specific alternative + +### 5. Validate Implementability + +**Ask:** +- Can I generate an implementation plan from this? +- Are file locations/components identifiable? +- Are dependencies clear? +- Is scope reasonable? + +**Check for:** +- Unknown dependencies +- Unrealistic constraints +- Scope too large +- Conflicting requirements + +### 6. Assess Testability + +**For each requirement:** +- How will this be tested? +- Is the outcome verifiable? +- Can success be measured? + +**For success criteria:** +- Are they specific enough to test? +- Can they be automated? +- Are they objective (not subjective)? + +### 7. Check Against Constitution + +**If constitution exists:** + +```bash +cat specs/constitution.md +``` + +**Validate:** +- Does spec follow project principles? +- Are patterns consistent? +- Does error handling match standards? +- Are architectural decisions aligned? + +**Note any violations with reasoning.** + +### 8. Generate Review Report + +**Report structure:** + +```markdown +# Spec Review: [Feature Name] + +**Spec:** specs/features/[feature].md +**Date:** YYYY-MM-DD +**Reviewer:** Claude (sdd:review-spec) + +## Overall Assessment + +**Status:** ✅ SOUND / ⚠️ NEEDS WORK / ❌ MAJOR ISSUES + +**Summary:** [1-2 sentence overall assessment] + +## Completeness: [Score/5] + +### Structure +- [✓/✗] All required sections present +- [✓/✗] Recommended sections included +- [✓/✗] No placeholder text + +### Coverage +- [✓/✗] All functional requirements defined +- [✓/✗] Error cases identified +- [✓/✗] Edge cases covered +- [✓/✗] Success criteria specified + +**Issues:** +- [List any completeness issues] + +## Clarity: [Score/5] + +### Language Quality +- [✓/✗] No ambiguous language +- [✓/✗] Requirements are specific +- [✓/✗] No vague terms + +**Ambiguities Found:** +1. [Quote ambiguous text] + - Issue: [What's unclear] + - Suggestion: [Specific alternative] + +## Implementability: [Score/5] + +### Plan Generation +- [✓/✗] Can generate implementation plan +- [✓/✗] Dependencies identified +- [✓/✗] Constraints realistic +- [✓/✗] Scope manageable + +**Issues:** +- [List any implementability issues] + +## Testability: [Score/5] + +### Verification +- [✓/✗] Success criteria measurable +- [✓/✗] Requirements verifiable +- [✓/✗] Acceptance criteria clear + +**Issues:** +- [List any testability issues] + +## Constitution Alignment + +[If constitution exists] + +- [✓/✗] Follows project principles +- [✓/✗] Patterns consistent +- [✓/✗] Error handling aligned + +**Violations:** +- [List any violations] + +## Recommendations + +### Critical (Must Fix Before Implementation) +- [ ] [Critical issue 1] +- [ ] [Critical issue 2] + +### Important (Should Fix) +- [ ] [Important issue 1] + +### Optional (Nice to Have) +- [ ] [Optional improvement 1] + +## Conclusion + +[Final assessment and recommendation] + +**Ready for implementation:** Yes / No / After fixes + +**Next steps:** +[What should be done] +``` + +### 9. Make Recommendation + +**If sound (minor issues only):** +- ✅ Ready for implementation +- Proceed with `sdd:implement` + +**If needs work (important issues):** +- ⚠️ Fix issues before implementing +- Update spec, re-review + +**If major issues:** +- ❌ Not ready for implementation +- Significant rework needed +- May need re-brainstorming + +## Review Checklist + +Use TodoWrite to track: + +- [ ] Load and read spec thoroughly +- [ ] Check structure (all sections present) +- [ ] Review completeness (no TBD, all covered) +- [ ] Identify ambiguities (vague language) +- [ ] Validate implementability (can plan from this) +- [ ] Assess testability (can verify requirements) +- [ ] Check constitution alignment (if exists) +- [ ] Generate review report +- [ ] Make recommendation (ready/needs work/major issues) + +## Example: Sound Spec + +``` +# Spec Review: User Profile Update API + +**Spec:** specs/features/user-profile-api.md +**Status:** ✅ SOUND + +## Overall Assessment + +Specification is well-written, complete, and ready for implementation. +Minor suggestions for improvement but no blocking issues. + +## Completeness: 5/5 + +✓ All required sections present +✓ All functional requirements clearly defined (6 requirements) +✓ All error cases identified (4 cases) +✓ All edge cases covered (3 cases) +✓ Success criteria specified and measurable + +## Clarity: 4.5/5 + +✓ Requirements are specific and unambiguous +✓ Error handling clearly defined +⚠️ One minor ambiguity (see below) + +**Ambiguities Found:** +1. "Response should be fast" + - Issue: "Fast" is subjective + - Suggestion: Specify "Response time < 200ms" or remove + +## Implementability: 5/5 + +✓ Can generate detailed implementation plan +✓ All dependencies identified (JWT auth, database) +✓ Constraints are realistic +✓ Scope is manageable (single endpoint) + +## Testability: 5/5 + +✓ All success criteria measurable +✓ Each requirement verifiable through tests +✓ Clear acceptance criteria + +## Constitution Alignment + +✓ Follows RESTful conventions (from constitution) +✓ Error handling matches project patterns +✓ Auth requirements aligned with standards + +## Recommendations + +### Important (Should Fix) +- [ ] Clarify "fast" response requirement (specify < 200ms or remove) + +### Optional +- [ ] Consider adding rate limiting requirement +- [ ] Specify audit logging if required by project + +## Conclusion + +Excellent spec, ready for implementation after minor clarification on +performance requirement. + +**Ready for implementation:** Yes (after performance clarification) + +**Next steps:** Clarify "fast" requirement, then proceed to sdd:implement +``` + +## Example: Needs Work + +``` +# Spec Review: Real-time Notifications + +**Spec:** specs/features/real-time-notifications.md +**Status:** ⚠️ NEEDS WORK + +## Overall Assessment + +Specification has good foundation but several important gaps that will +cause confusion during implementation. + +## Completeness: 3/5 + +✓ Purpose clearly stated +✗ Non-functional requirements missing +✗ Error handling incomplete +⚠️ Edge cases partially defined + +**Issues:** +- No specification of real-time latency requirements +- Database storage requirements unclear +- Error recovery not defined +- Scalability requirements missing + +## Clarity: 3/5 + +**Ambiguities Found:** +1. "Notifications should appear in real-time" + - Issue: "Real-time" undefined (< 100ms? < 1s? < 5s?) + - Suggestion: Specify exact latency requirement + +2. "Handle notification delivery failures appropriately" + - Issue: "Appropriately" is non-specific + - Suggestion: Define retry logic, fallback, user notification + +3. "Support many users" + - Issue: "Many" is vague + - Suggestion: Specify target (100? 1000? 10000?) + +## Implementability: 2/5 + +✗ Cannot generate complete implementation plan +✗ Technology stack not specified (WebSocket? SSE? Polling?) +✗ Storage mechanism unclear + +**Issues:** +- Is this WebSocket or polling? Spec doesn't say +- Where are notifications stored? For how long? +- What happens when user offline? +- No mention of infrastructure requirements + +## Testability: 3/5 + +⚠️ Some criteria measurable, others vague + +**Issues:** +- "Users receive notifications quickly" - not measurable +- "System handles failures" - no specific test criteria + +## Recommendations + +### Critical (Must Fix Before Implementation) +- [ ] Define exact real-time latency requirement (< Xms) +- [ ] Specify technology (WebSocket vs polling vs SSE) +- [ ] Define notification storage (where, how long) +- [ ] Specify error handling and retry logic +- [ ] Define scalability target (number of users) + +### Important (Should Fix) +- [ ] Add detailed error cases +- [ ] Specify offline handling +- [ ] Define notification expiration +- [ ] Add infrastructure requirements + +## Conclusion + +Spec has good intent but lacks critical technical details needed for +implementation. Requires significant expansion before coding can begin. + +**Ready for implementation:** No + +**Next steps:** +1. Address all critical issues +2. Re-review spec +3. Then proceed to implementation +``` + +## Quality Standards + +**A sound spec has:** +- All sections complete +- No ambiguous language +- Specific, measurable requirements +- Identified dependencies +- Realistic constraints +- Clear error handling +- Defined edge cases +- Testable success criteria + +**A poor spec has:** +- Missing sections +- Vague language +- Unmeasurable requirements +- Unknown dependencies +- Unrealistic constraints +- Unclear error handling +- Ignored edge cases +- Subjective criteria + +## Remember + +**Reviewing specs saves time in implementation.** + +- 1 hour reviewing spec saves 10 hours debugging +- Ambiguities caught early prevent rework +- Complete specs enable smooth TDD +- Sound specs reduce spec/code drift + +**Be thorough but not pedantic:** +- Flag real issues, not nitpicks +- Focus on what blocks implementation +- Suggest specific improvements +- Balance perfection with pragmatism + +**The goal is implementability, not perfection.** diff --git a/skills/spec-kit/SKILL.md b/skills/spec-kit/SKILL.md new file mode 100644 index 0000000..9783c61 --- /dev/null +++ b/skills/spec-kit/SKILL.md @@ -0,0 +1,371 @@ +--- +name: spec-kit +description: Technical integration layer for spec-kit CLI - handles automatic initialization, installation validation, project setup, and ensures proper file/directory layout. Called by all SDD workflow skills. +--- + +# Spec-Kit Technical Integration + +## Purpose + +This skill is the **single source of truth** for all spec-kit technical integration: +- Automatic initialization and setup +- Installation validation +- Project structure management +- CLI command wrappers +- Layout and file path enforcement + +**This is a low-level technical skill.** Workflow skills (brainstorm, implement, etc.) call this skill for setup, then proceed with their specific workflows. + +## Automatic Initialization Protocol + +**IMPORTANT: This runs automatically when called by any workflow skill.** + +Every SDD workflow skill calls this skill first via `{Skill: spec-kit}`. When called, execute this initialization sequence once per session. + +### Session Tracking + +```bash +# Check if already initialized this session +# Use an environment variable or similar mechanism +# If "sdd_init_done" flag is set, skip to step 4 +``` + +### Step 1: Check spec-kit CLI Installation + +```bash +which speckit +``` + +**If NOT found:** +``` +❌ ERROR: spec-kit is required but not installed + +spec-kit provides the templates, scripts, and tooling for SDD workflows. + +Installation: +1. Visit: https://github.com/github/spec-kit +2. Follow installation instructions +3. Ensure 'speckit' is in your PATH +4. Verify: run 'which speckit' + +After installation, restart this workflow. +``` + +**STOP workflow.** Do not proceed without spec-kit. + +**If found:** +```bash +# Get version for logging +speckit --version +``` + +Proceed to step 2. + +### Step 2: Check Project Initialization + +```bash +# Check if .specify/ directory exists +[ -d .specify ] && echo "initialized" || echo "not-initialized" +``` + +**If NOT initialized:** + +Display message: +``` +spec-kit is installed ✓ + +This project needs initialization... +Running: speckit init +``` + +Execute initialization: +```bash +speckit init +``` + +**Check for errors:** +- Permission denied → suggest running with proper permissions +- Command failed → display error and suggest manual init +- Success → proceed to step 3 + +**If already initialized:** +Skip to step 3. + +### Step 3: Check for New Commands (Restart Detection) + +After `speckit init` runs, check if local commands were installed: + +```bash +# Check if spec-kit installed Claude Code commands +if [ -d .claude/commands ]; then + ls .claude/commands/ | grep -q speckit + if [ $? -eq 0 ]; then + echo "commands-installed" + fi +fi +``` + +**If commands were installed:** + +Display restart prompt: +``` +✅ Project initialized successfully! + +⚠️ RESTART REQUIRED ⚠️ + +spec-kit has installed local slash commands in: + .claude/commands/speckit.* + +To load these new commands, please: +1. Save your work +2. Close this conversation +3. Restart Claude Code application +4. Return to this project +5. Continue your workflow + +After restart, you'll have access to: +- /sdd:* commands (from this plugin) +- /speckit.* commands (from local spec-kit installation) + +[Workflow paused - resume after restart] +``` + +**STOP workflow.** User must restart before continuing. + +**If no new commands installed:** +Proceed to step 4. + +### Step 4: Verify Installation + +Quick sanity check: +```bash +# Verify key files exist +[ -f .specify/templates/spec-template.md ] && \ +[ -f .specify/scripts/bash/common.sh ] && \ +echo "verified" || echo "corrupt" +``` + +**If verification fails:** +``` +❌ ERROR: .specify/ exists but appears incomplete + +This may be due to a failed initialization. + +Please run: speckit init --force + +Then restart this workflow. +``` + +**STOP workflow.** + +**If verification succeeds:** +- Set session flag: "sdd_init_done" +- Return success to calling skill +- Calling skill continues with its workflow + +## Layout Validation + +Use these helpers to validate spec-kit file structure: + +### Check Constitution + +```bash +# Constitution location (per spec-kit convention) +CONSTITUTION=".specify/memory/constitution.md" + +if [ -f "$CONSTITUTION" ]; then + echo "constitution-exists" +else + echo "no-constitution" +fi +``` + +### Get Feature Spec Path + +```bash +# Validate feature spec path follows spec-kit layout +# Expected: specs/NNNN-feature-name/spec.md +# Or: specs/features/feature-name.md + +validate_spec_path() { + local spec_path=$1 + + # Check if follows spec-kit conventions + if [[ $spec_path =~ ^specs/[0-9]+-[a-z-]+/spec\.md$ ]] || \ + [[ $spec_path =~ ^specs/features/[a-z-]+\.md$ ]]; then + echo "valid" + else + echo "invalid: spec must be in specs/ directory with proper naming" + fi +} +``` + +### Get Plan Path + +```bash +# Plan location (per spec-kit convention) +# Expected: specs/NNNN-feature-name/docs/plan.md + +get_plan_path() { + local feature_dir=$1 # e.g., "specs/0001-user-auth" + echo "$feature_dir/docs/plan.md" +} +``` + +### Ensure Directory Structure + +```bash +# Create spec-kit compliant feature structure +ensure_feature_structure() { + local feature_dir=$1 # e.g., "specs/0001-user-auth" + + mkdir -p "$feature_dir/docs" + mkdir -p "$feature_dir/checklists" + mkdir -p "$feature_dir/contracts" + + echo "created: $feature_dir structure" +} +``` + +## Spec-Kit CLI Commands + +Wrapper helpers for common spec-kit commands: + +### Initialize Project + +```bash +# Already covered in automatic initialization +speckit init +``` + +### Create Specification + +```bash +# Interactive spec creation +speckit specify [feature-description] + +# Uses template from .specify/templates/spec-template.md +``` + +### Validate Specification + +```bash +# Validate spec format and structure +speckit validate + +# Example: +speckit validate specs/0001-user-auth/spec.md +``` + +### Generate Plan + +```bash +# Generate implementation plan from spec +speckit plan + +# Example: +speckit plan specs/0001-user-auth/spec.md +``` + +### Create Constitution + +```bash +# Interactive constitution creation +speckit constitution + +# Creates .specify/memory/constitution.md +``` + +## Error Handling + +### spec-kit CLI Errors + +**Command not found after installation:** +- Check PATH configuration +- Suggest shell restart +- Provide which speckit output + +**Init fails:** +- Check write permissions +- Check disk space +- Suggest manual troubleshooting + +**Validation fails:** +- Display validation errors +- Suggest fixes based on error type +- Reference spec template + +### File System Errors + +**Permission denied:** +``` +Cannot write to project directory. + +Please ensure you have write permissions: + chmod +w . +``` + +**Path not found:** +``` +Expected file not found: + +This suggests incomplete initialization. +Run: speckit init --force +``` + +## Integration Points + +**Called by these workflow skills:** +- sdd:brainstorm (at start) +- sdd:implement (at start) +- sdd:evolve (at start) +- sdd:constitution (at start) +- sdd:review-spec (at start) +- All workflow skills that need spec-kit + +**Calls:** +- spec-kit CLI (external command) +- File system operations +- No other skills (this is a leaf skill) + +## Session Management + +**First call in session:** +- Run full initialization protocol +- Check installation, project, commands +- Prompt restart if needed +- Set session flag + +**Subsequent calls in session:** +- Check session flag +- Skip initialization if already done +- Optionally re-verify critical paths +- Return success immediately + +**Session reset:** +- New conversation = new session +- Re-run initialization protocol +- Ensures project state is current + +## Remember + +**This skill is infrastructure, not workflow.** + +- Don't make decisions about WHAT to build +- Don't route to other workflow skills +- Just ensure spec-kit is ready to use +- Validate paths and structure +- Handle technical errors + +**Workflow skills handle:** +- What to create (specs, plans, code) +- When to use which tool +- Process discipline and quality gates + +**This skill handles:** +- Is spec-kit installed? +- Is project initialized? +- Do files exist in correct locations? +- Are commands available? + +**The goal: Zero-config, automatic, invisible setup.** diff --git a/skills/spec-refactoring/SKILL.md b/skills/spec-refactoring/SKILL.md new file mode 100644 index 0000000..0ba4229 --- /dev/null +++ b/skills/spec-refactoring/SKILL.md @@ -0,0 +1,447 @@ +--- +name: spec-refactoring +description: Consolidate and improve evolved specs - identifies inconsistencies, removes redundancy, improves structure while maintaining feature coverage +--- + +# Specification Refactoring + +## Overview + +Refactor specifications that have grown organically to improve clarity, consistency, and maintainability. + +As specs evolve through `sdd:evolve`, they can accumulate: +- Inconsistencies +- Redundancies +- Unclear sections +- Poor organization + +This skill consolidates and improves specs while ensuring all implemented features remain covered. + +## When to Use + +- Spec has evolved significantly through multiple updates +- Multiple related specs have redundancy +- Spec is difficult to understand or implement from +- Before major feature work on legacy spec +- Periodic maintenance (quarterly review) + +**Warning:** Never refactor specs during active implementation. Wait until stable. + +## The Process + +### 1. Analyze Current State + +**Read all related specs:** +```bash +# Single spec +cat specs/features/[feature].md + +# Multiple related specs +cat specs/features/user-*.md +``` + +**Document current issues:** +- Inconsistencies (conflicting requirements) +- Redundancies (duplicate requirements) +- Unclear sections (ambiguities) +- Poor structure (hard to navigate) +- Outdated sections (no longer relevant) + +### 2. Review Implementation + +**Check what's actually implemented:** +```bash +# Find implementation +rg "[feature-related-terms]" src/ + +# Check tests +rg "[feature-related-terms]" tests/ +``` + +**Critical:** Refactored spec MUST cover all implemented features. + +**Create coverage map:** +``` +Implemented Feature 1 → Spec Requirement X +Implemented Feature 2 → Spec Requirement Y +... +``` + +If implementation exists without spec coverage, ADD it during refactor. + +### 3. Identify Consolidation Opportunities + +**Look for:** + +**Redundant requirements:** +- Same requirement stated multiple times +- Similar requirements that could merge +- Duplicate error handling + +**Inconsistent terminology:** +- Same concept called different names +- Inconsistent capitalization +- Different formats for similar things + +**Scattered related requirements:** +- Auth requirements in multiple places +- Error handling spread throughout +- Related features not grouped + +### 4. Design Improved Structure + +**Better organization:** +- Group related requirements +- Logical section order +- Consistent formatting +- Clear hierarchy + +**Example improvement:** + +**Before:** +```markdown +## Requirements +- User login +- Password validation +- Email validation +- Session management +- Logout +- Password reset +- Email verification +``` + +**After:** +```markdown +## Authentication Requirements + +### User Registration +- Email validation +- Email verification +- Password validation + +### Session Management +- User login +- Session creation +- Logout +- Session expiration + +### Password Management +- Password reset +- Password change +- Password strength requirements +``` + +### 5. Refactor Spec + +**Steps:** + +1. **Create refactored version** (new file or branch) +2. **Reorganize sections** for clarity +3. **Consolidate redundancies** +4. **Standardize terminology** +5. **Improve requirement clarity** +6. **Add missing coverage** (if implementation exists) +7. **Remove obsolete sections** (if truly no longer relevant) + +**Throughout:** Maintain traceability to old spec + +### 6. Validate Refactored Spec + +**Check:** +- [ ] All implemented features covered +- [ ] No requirements lost +- [ ] Terminology consistent +- [ ] Structure logical +- [ ] No new ambiguities introduced + +**Use `sdd:review-spec`** on refactored version. + +### 7. Create Changelog + +**Document changes:** + +```markdown +## Spec Refactoring Changelog + +**Date:** YYYY-MM-DD +**Previous Version:** [link or commit] + +### Changes Made + +**Structural Changes:** +- Reorganized requirements into logical groups +- Moved error handling to dedicated section +- Created sub-sections for clarity + +**Consolidated Requirements:** +- Merged requirements 3, 7, 12 (all about validation) +- Combined duplicate error cases +- Unified session management requirements + +**Terminology Standardization:** +- "User" → "Authenticated User" (consistent usage) +- "Login" → "Authentication" (aligned with codebase) + +**Added Coverage:** +- Requirement 15: Password strength (implemented but not in spec) +- Error case 8: Rate limiting (implemented but not in spec) + +**Removed:** +- Obsolete requirement 9 (feature removed in v2.0) + +### Migration Notes + +[How to map old spec sections to new spec sections] + +Old Section 2.1 → New Section 3.1.1 +Old Section 3.4 → New Section 2.3 +... +``` + +### 8. Transition Strategy + +**For active projects:** + +1. **Review with team** (if team project) +2. **Create PR for spec refactor** +3. **Get approval before merging** +4. **Keep old spec accessible** (git history) +5. **Update documentation** (if references spec) + +**For solo projects:** + +1. **Commit old spec** (ensure it's in git) +2. **Replace with refactored spec** +3. **Commit with detailed message** + +### 9. Verify Against Code + +**After refactoring:** + +```bash +# Check spec compliance with current code +# Use sdd:review-code +``` + +**Ensure:** +- Refactored spec still describes existing implementation +- No accidental requirement changes +- Compliance still 100% + +## Refactoring Checklist + +Use TodoWrite to track: + +- [ ] Analyze current spec state (issues, redundancies) +- [ ] Review actual implementation (what exists in code) +- [ ] Create coverage map (implementation → spec) +- [ ] Identify consolidation opportunities +- [ ] Design improved structure +- [ ] Refactor spec content +- [ ] Validate refactored spec for soundness +- [ ] Ensure all implemented features covered +- [ ] Create changelog documenting changes +- [ ] Verify refactored spec against code (compliance check) +- [ ] Commit with detailed message + +## Example: Before and After + +### Before Refactoring + +```markdown +# Feature: User System + +## Requirements +1. Users can register +2. Email must be validated +3. Password must be strong +4. Users can login +5. Sessions expire after 30 minutes +6. Users can logout +7. Passwords must have 8 characters +8. Passwords must have uppercase +9. Passwords must have lowercase +10. Passwords must have number +11. Email format must be valid +12. Users can reset password +13. Reset tokens expire after 1 hour +14. Users get logged out on password change +15. Sessions use JWT +16. JWT secret must be secure +... + +(Requirements scattered, no organization, redundancy) +``` + +### After Refactoring + +```markdown +# Feature: User Authentication System + +## Purpose +Provide secure user authentication with registration, login, and password management. + +## User Registration + +### Functional Requirements +1. Users can register with email and password +2. Registration creates user account and initial session + +### Email Validation +- Must be valid email format (RFC 5322) +- Email verification required before account activation +- Verification link expires after 24 hours + +### Password Requirements +- Minimum 8 characters +- Must contain: uppercase, lowercase, number +- Common passwords rejected (check against list) + +## Session Management + +### Authentication Flow +1. User provides credentials (email + password) +2. System validates credentials +3. On success: JWT token generated +4. Client stores token for subsequent requests + +### Session Configuration +- Token type: JWT (JSON Web Token) +- Token expiration: 30 minutes +- Secret: Stored in environment variable (not in code) +- Algorithm: HS256 + +### Logout +- Client discards token +- Optional: Server-side token invalidation (if implemented) + +## Password Management + +### Password Reset +- User requests reset via email +- Reset token generated and emailed +- Reset token expires after 1 hour +- On successful reset: all sessions invalidated + +### Password Change +- Requires current password confirmation +- On success: all sessions invalidated (forces re-login) +... + +(Organized, consolidated, clear) +``` + +### Changelog for Above + +```markdown +## Spec Refactoring Changelog + +**Date:** 2025-11-10 + +### Structural Changes +- Reorganized flat list into hierarchical sections: + - User Registration + - Session Management + - Password Management + +### Consolidated Requirements +- Requirements 7-10 → Single "Password Requirements" section +- Requirements 2, 11 → "Email Validation" section +- Requirements 4, 5, 6, 15, 16 → "Session Management" section + +### Terminology Standardization +- Consistently use "JWT" (not "token" and "JWT" interchangeably) +- "User" context now explicit (authenticated vs unauthenticated) + +### Added Coverage +- None (all features already in original spec) + +### Removed +- None (all requirements preserved, just reorganized) +``` + +## Types of Refactoring + +### 1. Structural Refactoring +- Reorganize sections +- Create hierarchy +- Group related items +- Improve navigation + +### 2. Consolidation Refactoring +- Merge duplicate requirements +- Combine scattered related items +- Remove redundancy + +### 3. Clarification Refactoring +- Remove ambiguities +- Add specificity +- Improve wording +- Standardize terminology + +### 4. Coverage Refactoring +- Add missing implemented features +- Remove obsolete requirements +- Align with current codebase + +## Common Patterns + +### Pattern: Password Requirements Scattered + +**Problem:** Password requirements in multiple places + +**Solution:** Consolidate into single "Password Requirements" section + +### Pattern: Inconsistent Error Handling + +**Problem:** Some requirements specify errors, others don't + +**Solution:** Create dedicated "Error Handling" section, reference from requirements + +### Pattern: Mixed Abstraction Levels + +**Problem:** High-level and low-level requirements mixed + +**Solution:** Create hierarchy - high-level functional requirements with detailed sub-sections + +### Pattern: Terminology Drift + +**Problem:** "User", "Account", "Profile" used interchangeably + +**Solution:** Standardize on one term, define others in glossary if needed + +## Warnings + +**Don't:** +- Change requirements (that's spec evolution, not refactoring) +- Remove coverage of implemented features +- Refactor during active implementation +- Make untracked changes (always document) + +**Do:** +- Preserve all requirement content +- Improve organization and clarity +- Maintain traceability +- Document all changes + +## Remember + +**Refactoring improves form, not function.** + +- Same requirements, better organization +- Same coverage, better clarity +- Same intent, better structure + +**Refactoring is maintenance, not change.** + +- Spec still describes same implementation +- No behavioral changes +- Only organizational improvements + +**Good specs enable good work.** + +- Clear specs enable smooth implementation +- Organized specs reduce confusion +- Consistent specs prevent errors + +**Periodic refactoring prevents spec decay.** diff --git a/skills/spec/SKILL.md b/skills/spec/SKILL.md new file mode 100644 index 0000000..ad7d6b7 --- /dev/null +++ b/skills/spec/SKILL.md @@ -0,0 +1,233 @@ +--- +name: spec +description: Create specifications directly from clear requirements - uses spec-kit tools to create formal, executable specs following WHAT/WHY principle (not HOW) +--- + +# Direct Specification Creation + +## Overview + +Create formal specifications directly when requirements are clear and well-defined. + +**Use this instead of brainstorm when:** +- Requirements are already clear +- User provides detailed description +- Feature scope is well-defined +- No exploratory dialogue needed + +**This skill creates specs using spec-kit tools and ensures WHAT/WHY focus (not HOW).** + +## When to Use + +**Use this skill when:** +- User provides clear, detailed requirements +- Feature scope is well-defined +- User wants to skip exploratory dialogue +- Requirements come from external source (PRD, ticket, etc.) + +**Don't use this skill when:** +- Requirements are vague or exploratory → Use `sdd:brainstorm` +- Spec already exists → Use `sdd:implement` or `sdd:evolve` +- Making changes to existing spec → Use `sdd:spec-refactoring` + +## Prerequisites + +Ensure spec-kit is initialized: + +{Skill: spec-kit} + +If spec-kit prompts for restart, pause this workflow and resume after restart. + +## Critical: Specifications are WHAT and WHY, NOT HOW + +**Specs define contracts and requirements, not implementation.** + +### ✅ Specs SHOULD include: +- **Requirements**: What the feature must do +- **Behaviors**: How the feature should behave (user-observable) +- **Contracts**: API structures, file formats, data schemas +- **Error handling rules**: What errors must be handled and how they should appear to users +- **Success criteria**: Measurable outcomes +- **Constraints**: Limitations and restrictions +- **User-visible paths**: File locations, environment variables users interact with + +### ❌ Specs should NOT include: +- **Implementation algorithms**: Specific sorting algorithms, data structure choices +- **Code**: Function signatures, class hierarchies, pseudocode +- **Technology choices**: "Use Redis", "Use React hooks", "Use Python asyncio" +- **Internal architecture**: How components communicate internally +- **Optimization strategies**: Caching mechanisms, performance tuning + +### 📋 Example: What belongs where + +**SPEC (WHAT/WHY):** +```markdown +## Requirements +- FR-001: System MUST validate email addresses before storing +- FR-002: System MUST return validation errors within 200ms +- FR-003: Invalid emails MUST return 422 status with error details + +## Error Handling +- Invalid format: Return `{"error": "Invalid email format", "field": "email"}` +- Duplicate email: Return `{"error": "Email already exists"}` +``` + +**PLAN (HOW):** +```markdown +## Validation Implementation +- Use regex pattern: `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` +- Cache validation results in Redis (TTL: 5 min) +- Database query: `SELECT COUNT(*) FROM users WHERE email = ?` +``` + +### Why this matters: +- **Specs remain stable** - Implementation details change, requirements don't +- **Implementation flexibility** - Can change HOW without changing WHAT +- **Clearer reviews** - Easy to see if requirements are met vs implementation quality +- **Better evolution** - When code diverges from spec, know which to update + +## The Process + +### 1. Gather Requirements + +**Extract from user input:** +- What needs to be built +- Why it's needed (purpose/problem) +- Success criteria +- Constraints and dependencies +- Error cases and edge conditions + +**Ask clarifying questions** (brief, targeted): +- Only if critical information is missing +- Keep questions focused and specific +- Don't turn this into full brainstorming session + +**If requirements are vague:** +Stop and use `sdd:brainstorm` instead. + +### 2. Check Project Context + +**Review existing specs:** +```bash +ls -la specs/features/ +# Or: ls -la specs/[NNNN]-*/ +``` + +**Check for constitution:** +```bash +cat .specify/memory/constitution.md +``` + +**Look for related features:** +- Similar functionality already specced +- Integration points +- Shared components + +### 3. Create Specification + +**Use spec-kit tools:** + +```bash +# Interactive spec creation using spec-kit template +speckit specify "[feature description]" + +# Or use spec-kit scripts directly +.specify/scripts/bash/create-new-feature.sh --json "[feature description]" +``` + +**This will:** +- Create feature directory (e.g., `specs/0001-feature-name/`) +- Initialize spec.md from template +- Set up directory structure (docs/, checklists/, contracts/) + +**Fill in the spec following template structure:** +- Purpose - WHY this feature exists +- Functional Requirements - WHAT it must do +- Non-Functional Requirements - Performance, security, etc. +- Success Criteria - Measurable outcomes +- Error Handling - What can go wrong +- Edge Cases - Boundary conditions +- Constraints - Limitations +- Dependencies - What this relies on +- Out of Scope - What this doesn't do + +**Follow WHAT/WHY principle:** +- Focus on observable behavior +- Avoid implementation details +- Use user/system perspective +- Keep technology-agnostic where possible + +### 4. Validate Against Constitution + +**If constitution exists:** + +```bash +cat .specify/memory/constitution.md +``` + +**Check alignment:** +- Does spec follow project principles? +- Are patterns consistent with constitution? +- Does error handling match standards? +- Are architectural decisions aligned? + +**Note any deviations** and justify them in spec. + +### 5. Review Spec Soundness + +**Before finishing, validate:** + +Use `sdd:review-spec` skill to check: +- Completeness (all sections filled) +- Clarity (no ambiguous language) +- Implementability (can generate plan from this) +- Testability (success criteria measurable) + +**If review finds issues:** +- Fix critical issues before proceeding +- Document any known gaps +- Mark unclear areas for clarification + +### 6. Commit Spec + +**Create git commit:** + +```bash +git add specs/[feature-dir]/ +git commit -m "Add spec for [feature-name]" +``` + +**Spec is now source of truth** for this feature. + +## Next Steps + +After spec creation: + +1. **Review spec soundness** (if not already done): + ``` + Use sdd:review-spec + ``` + +2. **Implement the feature**: + ``` + Use sdd:implement + ``` + +3. **Or refine spec further** if issues found + +## Remember + +**Spec is contract, not design doc:** +- Defines WHAT and WHY +- Defers HOW to implementation +- Remains stable as code evolves +- Is source of truth for compliance + +**Keep specs:**** +- Technology-agnostic +- User-focused +- Measurable +- Implementable + +**The goal:** +A clear, unambiguous specification that serves as the single source of truth for implementation and validation. diff --git a/skills/using-superpowers-sdd/SKILL.md b/skills/using-superpowers-sdd/SKILL.md new file mode 100644 index 0000000..4987faa --- /dev/null +++ b/skills/using-superpowers-sdd/SKILL.md @@ -0,0 +1,331 @@ +--- +name: using-superpowers-sdd +description: Establishes SDD methodology - workflow routing, process discipline, spec-first principle, and skill discovery. Use when starting any SDD conversation to determine which workflow skill to invoke. +--- + + +If you think there is even a 1% chance a skill might apply to what you are doing, you ABSOLUTELY MUST read the skill. + +IF A SKILL APPLIES TO YOUR TASK, YOU DO NOT HAVE A CHOICE. YOU MUST USE IT. + +This is not negotiable. This is not optional. You cannot rationalize your way out of this. + + +# Getting Started with Superpowers-SDD + +## What is SDD? + +**SDD = Specification-Driven Development** + +A development methodology where specifications are the single source of truth: +- Specs created before code +- Code validated against specs +- Specs evolve with implementation reality +- Quality gates enforce spec compliance + +This plugin combines: +- **Superpowers** process discipline (TDD, verification, quality gates) +- **Spec-Driven Development** (specs as source of truth) +- Result: High-quality software with specs that stay current + +## Technical Prerequisites + +**NOTE: The `spec-kit` skill handles all technical setup automatically.** + +Every SDD workflow skill calls `{Skill: spec-kit}` first, which: +- Checks if spec-kit CLI is installed +- Initializes the project if needed +- Prompts restart if new commands installed +- Validates file structure + +You don't need to worry about setup. Focus on choosing the right workflow. + +## MANDATORY FIRST RESPONSE PROTOCOL + +Before responding to ANY user message, you MUST complete this checklist: + +1. ☐ List available SDD skills in your mind +2. ☐ Ask yourself: "Does ANY SDD skill match this request?" +3. ☐ If yes → Use the Skill tool to read and run the skill file +4. ☐ Announce which skill you're using +5. ☐ Follow the skill exactly + +**Responding WITHOUT completing this checklist = automatic failure.** + +## The Specification-First Principle + +**CRITICAL RULE: Specs are the source of truth. Everything flows from and validates against specs.** + +Before ANY implementation work: +- Spec must exist OR be created first +- Spec must be reviewed for soundness +- Implementation must validate against spec +- Spec/code mismatches trigger evolution workflow + +**You CANNOT write code without a spec. Period.** + +## Critical Rules + +1. **Spec-first, always.** No code without spec. No exceptions. +2. **Follow mandatory workflows.** Brainstorm → Spec → Plan → TDD → Verify. +3. **Check for relevant skills before ANY task.** SDD has skills for each phase. +4. **Validate spec compliance.** Code review and verification check specs. +5. **Handle spec/code drift.** Use sdd:evolve when mismatches detected. + +## Available SDD Skills + +### Phase Entry Points +- **sdd:brainstorm** - Rough idea → spec through collaborative dialogue +- **sdd:implement** - Spec → code with TDD and compliance checking +- **sdd:evolve** - Handle spec/code mismatches with AI guidance + +### Modified Core Skills +- **sdd:writing-plans** - Generate plans FROM specs (not from scratch) +- **sdd:review-code** - Review code-to-spec compliance +- **sdd:verification-before-completion** - Tests + spec compliance validation + +### SDD-Specific Skills +- **sdd:review-spec** - Validate spec soundness and completeness +- **sdd:spec-refactoring** - Consolidate and improve evolved specs +- **sdd:spec-kit** - Technical integration for spec-kit CLI (called automatically) +- **sdd:constitution** - Create/manage project-wide principles + +### Compatible Superpowers Skills +These work as-is with spec context: +- **test-driven-development** - Use AFTER spec, during implementation +- **systematic-debugging** - Use spec as reference during debugging +- **using-git-worktrees** - For isolated feature development +- **dispatching-parallel-agents** - For independent parallel work + +## Workflow Decision Tree + +``` +User request arrives + ↓ +Is this a new feature/project? + Yes → Is it a rough idea? + Yes → sdd:brainstorm + No → Create spec using spec-kit tools + No → Does spec exist for this area? + Yes → Is there spec/code mismatch? + Yes → sdd:evolve + No → sdd:implement + No → Create spec first using spec-kit tools +``` + +## Creating Specifications + +### Rough Idea → Use Brainstorm + +``` +User: "I want to add authentication to my app" +→ Use sdd:brainstorm +``` + +**Brainstorm will:** +- Explore the idea through questions +- Propose approaches with trade-offs +- Refine requirements collaboratively +- Create formal spec using spec-kit + +### Clear Requirements → Direct Spec Creation + +``` +User: "Add a POST /api/users endpoint that validates email and returns 422 on invalid format" +→ Create spec directly using spec-kit tools +``` + +**Direct spec creation:** +- Requirements are already clear +- No exploratory dialogue needed +- Use spec-kit CLI or templates directly +- Follow spec-kit layout conventions + +**WHAT vs HOW principle:** +Specs define WHAT and WHY, not HOW. +- ✅ WHAT: Requirements, behaviors, contracts, success criteria +- ❌ HOW: Algorithms, code, technology choices, architecture + +## Common Rationalizations That Mean You're About To Fail + +If you catch yourself thinking ANY of these thoughts, STOP. You are rationalizing. Check for and use the skill. + +**Spec-avoidance rationalizations:** +- "This is too simple for a spec" → WRONG. Simple changes still need spec context. +- "I'll just write the code quickly" → WRONG. Code without spec creates drift. +- "The spec is obvious from the description" → WRONG. Make it explicit. +- "We can spec it after implementation" → WRONG. That's documentation, not SDD. + +**Skill-avoidance rationalizations:** +- "This is just a quick fix" → WRONG. Quick fixes need spec validation. +- "I can check the spec manually" → WRONG. Use sdd:verification-before-completion. +- "The spec is good enough" → WRONG. Use sdd:review-spec before implementing. +- "I remember this workflow" → WRONG. Skills evolve. Run the current version. + +**Why:** Specs prevent drift. Skills enforce discipline. Both save time by preventing mistakes. + +If a skill for your task exists, you must use it or you will fail at your task. + +## Skills with Checklists + +If a skill has a checklist, YOU MUST create TodoWrite todos for EACH item. + +**Don't:** +- Work through checklist mentally +- Skip creating todos "to save time" +- Batch multiple items into one todo +- Mark complete without doing them + +**Why:** Checklists without TodoWrite tracking = steps get skipped. Every time. + +## Announcing Skill Usage + +Before using a skill, announce that you are using it. + +"I'm using [Skill Name] to [what you're doing]." + +**Examples:** +- "I'm using sdd:brainstorm to refine your idea into a spec." +- "I'm using sdd:implement to build this feature from the spec." +- "I'm using sdd:evolve to reconcile the spec/code mismatch." + +**Why:** Transparency helps your human partner understand your process and catch errors early. + +## Spec Evolution is Normal + +Specs WILL diverge from code. This is expected and healthy. + +**When mismatch detected:** +1. DON'T panic or force-fit code to wrong spec +2. DO use sdd:evolve +3. AI analyzes: update spec vs. fix code +4. User decides (or auto-update if configured) + +**Remember:** Specs are source of truth, but truth can evolve based on reality. + +## Constitution: Optional but Powerful + +Consider creating a constitution for your project: + +**What is it?** +- Project-wide principles and standards +- Referenced during spec validation +- Ensures consistency across features + +**When to create:** +- New projects: Early, after first feature spec +- Existing projects: When patterns emerge +- Team projects: Always (defines shared understanding) + +**How to create:** +Use `/sdd:constitution` skill. + +## Instructions ≠ Permission to Skip Workflows + +Your human partner's specific instructions describe WHAT to do, not HOW. + +"Add X", "Fix Y" = the goal, NOT permission to skip spec-first or verification. + +**Red flags:** "Instruction was specific" • "Seems simple" • "Workflow is overkill" + +**Why:** Specific instructions mean clear requirements, which is when specs matter MOST. + +## Summary + +**Starting any task:** +1. Check this skill first for routing +2. Determine: brainstorm vs. direct spec vs. implement vs. evolve +3. Invoke the appropriate workflow skill +4. That skill will call spec-kit for setup automatically +5. Follow the workflow discipline exactly + +**The methodology is:** +- Specs first, always +- Code validates against specs +- Specs evolve when reality teaches us +- Quality gates prevent shortcuts +- Process discipline ensures quality + +**The tools are:** +- spec-kit (technical integration) +- Workflow skills (brainstorm, implement, evolve) +- Verification and validation skills +- TDD and debugging skills + +**The goal is:** +High-quality software with specs that remain the living source of truth. + +## Workflow Patterns + +### Pattern 1: New Feature from Rough Idea + +``` +User: "I want to add notifications to my app" + +1. Recognize: Rough idea +2. Route to: sdd:brainstorm +3. Brainstorm will: + - Call spec-kit (auto-setup) + - Explore idea collaboratively + - Create formal spec + - Hand off to sdd:implement +``` + +### Pattern 2: New Feature from Clear Requirements + +``` +User: "Add GET /api/stats endpoint returning JSON with user_count and post_count" + +1. Recognize: Clear requirements +2. Create spec using spec-kit tools +3. Route to: sdd:implement +4. Implement will: + - Call spec-kit (auto-setup) + - Generate plan from spec + - Use TDD + - Verify spec compliance +``` + +### Pattern 3: Code Exists, Spec Missing + +``` +User: "Document what this auth module does" + +1. Recognize: Code without spec +2. Create spec by analyzing code +3. Route to: sdd:evolve (to reconcile) +``` + +### Pattern 4: Code and Spec Diverged + +``` +User: "The login endpoint returns different errors than the spec says" + +1. Recognize: Spec/code mismatch +2. Route to: sdd:evolve +3. Evolve will: + - Call spec-kit (auto-setup) + - Analyze mismatch + - Recommend update spec vs. fix code + - User decides or auto-update +``` + +## Remember + +**You are the methodology enforcer.** + +- Route to correct workflow skill +- Enforce spec-first principle +- Catch rationalizations +- Ensure quality gates run + +**You are NOT:** +- The technical setup manager (that's spec-kit) +- The implementer (that's workflow skills) +- The spec creator (that's spec-kit + brainstorm) + +**Your job:** +Ensure the right skill gets used for the right task, and that SDD principles are followed. + +**The goal:** +Specs that stay current. Code that matches intent. Quality through discipline. diff --git a/skills/verification-before-completion/SKILL.md b/skills/verification-before-completion/SKILL.md new file mode 100644 index 0000000..ef4dafa --- /dev/null +++ b/skills/verification-before-completion/SKILL.md @@ -0,0 +1,419 @@ +--- +name: verification-before-completion +description: Extended verification including tests AND spec compliance - runs tests, validates spec compliance, checks for drift, blocks completion on failures +--- + +# Verification Before Completion (Spec-Aware) + +## Overview + +Verify implementation is complete by running tests AND validating spec compliance. + +**Key Additions from Standard Verification:** +- Step 1: Run tests (existing behavior) +- **Step 2: Validate spec compliance** (new) +- **Step 3: Check for spec drift** (new) +- Blocks completion if EITHER tests OR spec compliance fails + +## When to Use + +- After implementation and code review +- Before claiming work is complete +- Before committing/merging/deploying +- As final gate in `sdd:implement` workflow + +## The Process + +### 1. Run Tests + +**Execute all tests:** +```bash +# Run full test suite +npm test # or pytest, go test, etc. +``` + +**Check results:** +- All tests passing? +- No flaky tests? +- Coverage adequate? + +**If tests fail:** +- ❌ **STOP - Fix tests before proceeding** +- Do not skip this step +- Do not claim completion + +### 2. Validate Spec Compliance + +**Load spec:** +```bash +cat specs/features/[feature-name].md +``` + +**Check each requirement:** + +```markdown +Functional Requirement 1: [From spec] + ✓ / ✗ Implemented + ✓ / ✗ Tested + ✓ / ✗ Matches spec behavior + +Functional Requirement 2: [From spec] + ... +``` + +**Verify:** +- All requirements implemented +- All requirements tested +- All behavior matches spec +- No missing features +- No extra features (or documented) + +**Calculate compliance:** +``` +Spec Compliance: X/X requirements = XX% +``` + +**If compliance < 100%:** +- ❌ **STOP - Use `sdd:evolve` to reconcile** +- Document all deviations +- Do not proceed until resolved + +### 3. Check for Spec Drift + +**Compare:** +- What spec says NOW +- What code does NOW +- Any divergence? + +**Common drift sources:** +- Spec updated but code not +- Code changed but spec not +- Undocumented additions +- Forgotten requirements + +**If drift detected:** +- Document each instance +- Use `sdd:evolve` to reconcile +- Do not proceed with drift + +### 4. Verify Success Criteria + +**From spec, check each criterion:** + +```markdown +Success Criteria (from spec): +- [ ] Criterion 1: [Description] + Status: ✓ Met / ✗ Not met + Evidence: [How verified] + +- [ ] Criterion 2: [Description] + ... +``` + +**All criteria must be met.** + +If any criterion not met: +- ❌ **STOP - Criterion not met** +- Implement missing piece +- Re-verify + +### 5. Generate Verification Report + +**Report structure:** + +```markdown +# Verification Report: [Feature Name] + +**Date:** YYYY-MM-DD +**Spec:** specs/features/[feature].md + +## Test Results + +**Status:** ✅ PASS / ❌ FAIL + +``` +[Test output] +``` + +**Summary:** +- Total: X tests +- Passed: X +- Failed: X +- Coverage: XX% + +## Spec Compliance + +**Status:** ✅ COMPLIANT / ❌ NON-COMPLIANT + +**Compliance Score:** XX% + +### Requirements Status +- Functional: X/X (XX%) +- Error Cases: X/X (XX%) +- Edge Cases: X/X (XX%) +- Non-Functional: X/X (XX%) + +### Deviations +[List any deviations found] + +## Spec Drift Check + +**Status:** ✅ NO DRIFT / ⚠️ DRIFT DETECTED + +[Details if drift found] + +## Success Criteria + +**Status:** ✅ ALL MET / ❌ INCOMPLETE + +- [✓] Criterion 1 +- [✓] Criterion 2 +... + +## Overall Status + +✅ **VERIFIED - Ready for completion** + +OR + +❌ **NOT VERIFIED - Issues must be resolved** + +**Blocking Issues:** +- [Issue 1] +- [Issue 2] + +**Next Steps:** +[What needs to be done] +``` + +### 6. Make Go/No-Go Decision + +**All conditions must be true:** +- [x] All tests passing +- [x] Spec compliance 100% +- [x] No spec drift +- [x] All success criteria met + +**If ALL true:** +- ✅ **VERIFIED - Proceed to completion** +- Safe to commit/merge/deploy + +**If ANY false:** +- ❌ **NOT VERIFIED - Block completion** +- Fix issues before proceeding +- Re-run verification after fixes + +## Verification Checklist + +Use TodoWrite to track: + +- [ ] Run full test suite +- [ ] Verify all tests passing +- [ ] Load specification +- [ ] Validate spec compliance for all requirements +- [ ] Check for spec drift +- [ ] Verify all success criteria met +- [ ] Generate verification report +- [ ] Make go/no-go decision +- [ ] If not verified: Document blocking issues +- [ ] If verified: Proceed to completion + +## Example: Verification PASS + +``` +You: Running verification before completion... + +Step 1: Running tests... + +$ npm test + +✅ All tests passing (24/24) +✅ Coverage: 95% + +Step 2: Validating spec compliance... + +Reading spec: specs/features/user-profile-api.md + +Checking requirements: +✓ Functional Requirement 1: PUT endpoint - Implemented & tested +✓ Functional Requirement 2: Validation - Implemented & tested +✓ Functional Requirement 3: Auth - Implemented & tested +✓ Functional Requirement 4: Authorization - Implemented & tested +✓ Functional Requirement 5: Response format - Implemented & tested +✓ Functional Requirement 6: Partial updates - Implemented & tested + +✓ Error Case 1: Missing JWT - Handled & tested +✓ Error Case 2: User not found - Handled & tested +✓ Error Case 3: Validation failure - Handled & tested +✓ Error Case 4: Authorization failure - Handled & tested + +✓ Edge Case 1: Empty update - Handled & tested +✓ Edge Case 2: Invalid avatar URL - Handled & tested +✓ Edge Case 3: Special characters in name - Handled & tested + +Spec Compliance: 13/13 = 100% ✅ + +Step 3: Checking for spec drift... + +Comparing spec to implementation... +No drift detected ✅ + +Step 4: Verifying success criteria... + +From spec: +✓ Authenticated users can update their profile +✓ Validation errors return 422 with clear messages +✓ Users cannot update other users' profiles +✓ All edge cases handled gracefully + +All criteria met ✅ + +=== VERIFICATION REPORT === + +✅ Tests: PASS (24/24) +✅ Spec Compliance: 100% +✅ Spec Drift: None +✅ Success Criteria: All met + +**OVERALL: ✅ VERIFIED** + +Implementation is complete and verified. Ready for commit/merge. +``` + +## Example: Verification FAIL + +``` +You: Running verification before completion... + +Step 1: Running tests... + +$ npm test + +❌ Tests FAILED (22/24 passing, 2 failing) + +Failures: +1. "Should handle database connection errors" + Error: Connection retry not implemented + +2. "Should return 503 when database unavailable" + Error: Returns 500 instead of 503 + +**BLOCKING: Tests must pass before proceeding** + +Step 2: Validating spec compliance... + +Reading spec: specs/features/user-profile-api.md + +Checking requirements: +[checks requirements...] + +❌ Non-Functional Requirement 1: Database retry logic + Status: Not implemented + Spec says: "3 retry attempts with exponential backoff" + Code does: Single attempt, no retry + +Spec Compliance: 12/13 = 92% ❌ + +Step 3: Checking success criteria... + +From spec: +✓ Authenticated users can update their profile +✓ Validation errors return 422 +✗ Handles database failures gracefully (missing retry logic) +✓ Users cannot update other users' profiles + +=== VERIFICATION REPORT === + +❌ Tests: FAIL (2 failures) +❌ Spec Compliance: 92% (missing retry logic) +❌ Success Criteria: 3/4 met + +**OVERALL: ❌ NOT VERIFIED** + +**Blocking Issues:** +1. Database retry logic not implemented (from spec) +2. Tests failing for error handling +3. Returns wrong HTTP status (500 vs 503) + +**Next Steps:** +1. Implement database retry logic per spec +2. Fix HTTP status code +3. Re-run verification + +**DO NOT PROCEED until all issues resolved.** +``` + +## Common Failure Scenarios + +### Scenario: Tests Pass but Spec Compliance Fails + +``` +✅ Tests: 24/24 passing +❌ Spec Compliance: 85% +❌ BLOCKED + +Issue: Tests don't cover all spec requirements + +Action: Add tests for uncovered requirements, re-verify +``` + +### Scenario: Spec Compliant but Tests Fail + +``` +❌ Tests: 20/24 passing +✅ Spec Compliance: 100% +❌ BLOCKED + +Issue: Implementation exists but has bugs + +Action: Fix bugs, ensure tests pass, re-verify +``` + +### Scenario: Both Pass but Drift Detected + +``` +✅ Tests: 24/24 passing +✅ Spec Compliance: 100% +⚠️ Spec Drift: Spec updated after implementation +❌ BLOCKED + +Issue: Spec changed, code doesn't reflect changes + +Action: Update code or revert spec, re-verify +``` + +## Quality Gates + +**This skill enforces quality gates:** + +1. **All tests must pass** (from superpowers) +2. **100% spec compliance required** (new) +3. **No spec drift allowed** (new) +4. **All success criteria must be met** (new) + +**No exceptions. No shortcuts.** + +These gates exist to prevent: +- Incomplete implementations +- Untested code +- Spec/code divergence +- False claims of completion + +## Remember + +**Verification is not optional.** + +- Don't skip verification "just this once" +- Don't claim completion without verification +- Don't ignore failing gates + +**Verification failures are information.** + +- Tests failing? Code has bugs +- Spec compliance failing? Missing features +- Drift detected? Synchronization problem +- Criteria not met? Work incomplete + +**Fix issues, don't rationalize past them.** + +**Evidence before assertions. Always.** diff --git a/skills/writing-plans/SKILL.md b/skills/writing-plans/SKILL.md new file mode 100644 index 0000000..039b1df --- /dev/null +++ b/skills/writing-plans/SKILL.md @@ -0,0 +1,500 @@ +--- +name: writing-plans +description: Generate implementation plans FROM specifications - reads spec as input, extracts requirements, creates step-by-step tasks with validation against spec +--- + +# Writing Implementation Plans from Specifications + +## Overview + +Generate detailed implementation plans derived FROM specifications, not from scratch. + +The spec is the source of truth. The plan translates spec requirements into concrete, actionable implementation tasks. + +**Key Difference from Standard Writing-Plans:** +- **Input is SPEC** (not blank slate) +- Plan MUST cover all spec requirements +- Plan validates against spec for completeness +- Tasks reference spec sections explicitly + +## When to Use + +**Use this skill when:** +- Spec exists and is validated +- Ready to create implementation plan +- Called by `sdd:implement` workflow +- Need to break spec into tasks + +**Don't use this skill when:** +- No spec exists → Create spec first +- Plan already exists → Review/update existing plan +- Just clarifying approach → Use brainstorming + +## Prerequisites + +- [ ] Spec exists and is complete +- [ ] Spec validated for soundness +- [ ] No blocking open questions in spec +- [ ] Ready to start implementation + +## The Process + +### 1. Read and Parse Specification + +**Load the spec:** +```bash +cat specs/features/[feature-name].md +``` + +**Extract all elements:** +- **Functional requirements** (what to build) +- **Non-functional requirements** (how it should perform) +- **Success criteria** (how to verify) +- **Error handling** (what can go wrong) +- **Edge cases** (boundary conditions) +- **Dependencies** (what's needed) +- **Constraints** (limitations) + +**Create requirements checklist:** +- Number each requirement +- Reference spec section +- Mark coverage status + +### 2. Understand Project Context + +**Check existing codebase:** +```bash +# Find related files +rg "[relevant-terms]" + +# Check architecture +ls -la src/ + +# Review dependencies +cat package.json # or requirements.txt, go.mod, etc. +``` + +**Identify:** +- Where new code should live +- Existing patterns to follow +- Components to reuse +- Integration points + +### 3. Design Implementation Strategy + +**For each functional requirement, determine:** + +**Approach:** +- How will this be implemented? +- What components are needed? +- What patterns apply? + +**Files:** +- What files to create? +- What files to modify? +- Full file paths + +**Dependencies:** +- What needs to exist first? +- What can be done in parallel? +- What's the critical path? + +**Testing:** +- How will this be tested? +- What test files needed? +- What edge cases to cover? + +### 4. Create Implementation Plan + +**Use this structure:** + +```markdown +# Implementation Plan: [Feature Name] + +**Source Spec:** specs/features/[feature-name].md +**Date:** YYYY-MM-DD +**Estimated Effort:** [time estimate if relevant] + +## Overview + +[Brief summary of what we're implementing and why] + +## Requirements Coverage + +### Functional Requirement 1: [Quote from spec] +**Spec Reference:** specs/features/[feature].md#[section] + +**Implementation Approach:** +[How we'll implement this requirement] + +**Tasks:** +- [ ] [Specific actionable task] +- [ ] [Another task] + +**Files to Create/Modify:** +- `path/to/file.ext` - [What changes] + +**Tests:** +- [ ] [Test case for this requirement] + +--- + +### Functional Requirement 2: [Quote from spec] +[Repeat structure] + +--- + +[Continue for ALL functional requirements] + +## Non-Functional Requirements + +[For each non-functional requirement from spec] + +### [Requirement Name]: [Quote from spec] +**Spec Reference:** specs/features/[feature].md#[section] + +**Implementation:** +[How we'll achieve this] + +**Validation:** +[How we'll measure/verify this] + +## Error Handling Implementation + +[For each error case in spec] + +### Error: [From spec] +**Spec Reference:** specs/features/[feature].md#error-handling + +**Implementation:** +``` +[Code approach or pseudocode] +``` + +**Test Cases:** +- [ ] [Test for this error case] + +## Edge Cases Implementation + +[For each edge case in spec] + +### Edge Case: [From spec] +**Expected Behavior:** [From spec] + +**Implementation:** +[How we'll handle this] + +**Test:** +- [ ] [Test for edge case] + +## Dependencies + +**Required Before Implementation:** +- [ ] [Dependency 1 from spec] +- [ ] [Dependency 2 from spec] + +**Integration Points:** +- [Component/service 1]: [How we integrate] +- [Component/service 2]: [How we integrate] + +## Implementation Order + +**Phase 1: Foundation** +1. [Task] +2. [Task] + +**Phase 2: Core Functionality** +1. [Task] +2. [Task] + +**Phase 3: Error Handling** +1. [Task] +2. [Task] + +**Phase 4: Edge Cases & Polish** +1. [Task] +2. [Task] + +## Test Strategy + +**Unit Tests:** +- [ ] [Component/function to test] +- [ ] [Another component/function] + +**Integration Tests:** +- [ ] [Integration scenario] +- [ ] [Another scenario] + +**Spec Compliance Tests:** +- [ ] [Verify requirement 1] +- [ ] [Verify requirement 2] + +## Files to Create + +- `path/to/new/file1.ext` - [Purpose] +- `path/to/new/file2.ext` - [Purpose] + +## Files to Modify + +- `path/to/existing/file1.ext` - [What changes] +- `path/to/existing/file2.ext` - [What changes] + +## Success Criteria + +[From spec, repeated here for reference] +- [ ] [Criterion 1] +- [ ] [Criterion 2] + +## Spec Validation Checklist + +**All requirements covered:** +- [ ] All functional requirements have tasks +- [ ] All non-functional requirements addressed +- [ ] All error cases have implementation approach +- [ ] All edge cases have handling strategy +- [ ] All dependencies identified +- [ ] All success criteria have verification plan + +**Plan completeness:** +- [ ] All tasks are specific and actionable +- [ ] All file paths are complete (not "TBD") +- [ ] All requirements reference spec sections +- [ ] Test strategy covers all requirements +- [ ] Implementation order is logical + +## Notes + +[Any additional context, decisions, or considerations] +``` + +### 5. Validate Plan Against Spec + +**Completeness check:** + +For each requirement in spec: +- [ ] Plan has implementation approach +- [ ] Plan has specific tasks +- [ ] Plan has test coverage +- [ ] Plan references spec section + +**Coverage matrix:** +``` +Requirement 1 → Tasks [1,2,3], Tests [A,B] ✓ +Requirement 2 → Tasks [4,5], Tests [C,D] ✓ +Requirement 3 → Tasks [6], Tests [E,F,G] ✓ +... +``` + +**If any requirement uncovered:** Add tasks before proceeding. + +### 6. Review for Implementability + +**Check that plan:** +- Has concrete file paths (not "somewhere") +- Has specific tasks (not vague "implement X") +- Has realistic order (dependencies respected) +- Has test coverage (every requirement tested) + +**Red flags:** +- "Figure out how to..." +- "Implement [vague concept]" +- "TBD" +- Missing file paths +- No test strategy + +### 7. Save and Commit Plan + +**Save plan:** +```bash +# Location +docs/plans/[date]-[feature]-implementation.md +``` + +**Commit plan:** +```bash +git add docs/plans/[date]-[feature]-implementation.md +git commit -m "Add implementation plan for [feature] + +Generated from spec: specs/features/[feature].md + +Coverage: +- [N] functional requirements +- [N] error cases +- [N] edge cases + +Estimated [N] tasks + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +Co-Authored-By: Claude " +``` + +## Checklist + +Use TodoWrite to track: + +- [ ] Read and parse specification completely +- [ ] Extract all requirements, errors, edge cases +- [ ] Understand project context and codebase +- [ ] Design implementation strategy +- [ ] Create implementation plan with all sections +- [ ] Validate plan coverage against spec (100%) +- [ ] Review plan for implementability +- [ ] Ensure all file paths are complete +- [ ] Ensure all tasks are specific and actionable +- [ ] Save plan to docs/plans/ +- [ ] Commit plan to git + +## Example + +``` +[Called from sdd:implement] + +You: Generating implementation plan from spec... + +Reading spec: specs/features/user-profile-api.md + +Extracting requirements: +- Functional: 6 requirements +- Non-functional: 3 requirements +- Error cases: 4 +- Edge cases: 3 +- Dependencies: 2 + +Understanding project context... +- Existing API routes in: src/api/ +- Validation middleware in: src/middleware/ +- User service in: src/services/user.ts +- Tests in: tests/api/ + +Creating implementation plan... + +# Implementation Plan: User Profile Update API + +**Source Spec:** specs/features/user-profile-api.md +**Date:** 2025-11-10 + +## Overview + +Implement REST API endpoint for authenticated users to update their profiles. +Includes validation, error handling, and partial update support. + +## Requirements Coverage + +### Functional Requirement 1: PUT endpoint accepts requests +**Spec Reference:** specs/features/user-profile-api.md#functional-requirements + +**Implementation Approach:** +Create Express route handler at PUT /api/users/:id/profile using +existing route structure in src/api/users/ + +**Tasks:** +- [ ] Create route file at src/api/users/profile.ts +- [ ] Register route in src/api/users/index.ts +- [ ] Add route handler function + +**Files to Create/Modify:** +- `src/api/users/profile.ts` - New route handler +- `src/api/users/index.ts` - Register route + +**Tests:** +- [ ] Test route responds to PUT requests +- [ ] Test route path is /api/users/:id/profile + +--- + +### Functional Requirement 2: Validate request body +**Spec Reference:** specs/features/user-profile-api.md#functional-requirements + +**Implementation Approach:** +Create validation middleware using existing validation pattern. +Validate: name (2-50 chars), bio (max 500), avatar_url (URL format). + +**Tasks:** +- [ ] Create validation schema in src/middleware/validation/profile.ts +- [ ] Add validation middleware to route +- [ ] Return 422 on validation errors + +**Files to Create/Modify:** +- `src/middleware/validation/profile.ts` - Validation schema +- `src/api/users/profile.ts` - Apply middleware + +**Tests:** +- [ ] Test name length validation (too short) +- [ ] Test name length validation (too long) +- [ ] Test bio length validation +- [ ] Test avatar_url format validation + +[... continues for all requirements ...] + +## Spec Validation Checklist + +**All requirements covered:** +- [x] All 6 functional requirements have tasks +- [x] All 3 non-functional requirements addressed +- [x] All 4 error cases have implementation +- [x] All 3 edge cases handled +- [x] All 2 dependencies identified +- [x] All 5 success criteria have verification + +Plan validated against spec ✓ +Coverage: 100% + +Saving plan to: docs/plans/2025-11-10-user-profile-api-implementation.md + +Plan created ✓ +Committed to git ✓ + +Plan has 24 tasks across 4 phases. +Ready to implement with TDD? +``` + +## Quality Standards + +**Every plan MUST have:** +- Complete file paths (no "TBD") +- Specific tasks (not vague) +- Test coverage (every requirement) +- Error handling (every error case) +- Edge case coverage (every edge case) +- Spec references (every requirement linked) + +**Every task MUST be:** +- Actionable (clear what to do) +- Testable (can verify completion) +- Atomic (one clear outcome) +- Ordered (dependencies respected) + +## Common Pitfalls + +**Avoid:** +- Creating plan before spec exists +- Missing spec requirements in plan +- Vague tasks ("implement feature") +- Missing file paths +- No test strategy +- Skipping error cases +- Ignoring edge cases + +**Instead:** +- Always start from spec +- Cover 100% of spec requirements +- Make tasks concrete and specific +- Provide complete file paths +- Test every requirement +- Handle every error case +- Cover every edge case + +## Remember + +**The plan is a bridge from spec to code.** + +- Spec says WHAT +- Plan says HOW and WHERE and WHEN +- Code implements the plan + +**A good plan makes implementation smooth.** +**A poor plan causes confusion and rework.** + +**Validate against spec before proceeding.** +**100% coverage is non-negotiable.**