commit c0a5a7e86d87c9b0a3b59aa0338f0ac7d63c8e45 Author: Zhongwei Li Date: Sun Nov 30 08:42:25 2025 +0800 Initial commit diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..f57aa60 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,14 @@ +{ + "name": "prd-skills", + "description": "Complete PRD workflow: plan features with intelligent context loading, implement with automatic testing and code review, and ship with well-formatted commits and PRs. Supports core features, expansions, and tasks.", + "version": "1.1.0", + "author": { + "name": "Navid Emad", + "email": "design.navid@gmail.com" + }, + "skills": [ + "./skills/plan-prd", + "./skills/code-prd", + "./skills/publish" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..e03bb28 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# prd-skills + +Complete PRD workflow: plan features with intelligent context loading, implement with automatic testing and code review, and ship with well-formatted commits and PRs. Supports core features, expansions, and tasks. diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..b4759ee --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,57 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:navidemad/claude-code-plugins:prd-plugin", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "457139313795ad68571e8510f3f4518063ea5e8e", + "treeHash": "ba1f2c9dce5fccbb2c70341d16f9dc6c94099d693f670662165c1954d7350def", + "generatedAt": "2025-11-28T10:27:17.162054Z", + "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": "prd-skills", + "description": "Complete PRD workflow: plan features with intelligent context loading, implement with automatic testing and code review, and ship with well-formatted commits and PRs. Supports core features, expansions, and tasks.", + "version": "1.1.0" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "50d33093063c723ead0277ac9bb05510509877031aba09857facf8edae7f331c" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "c0b6f60e3dea933895fe4ee7e46a7360ca864ed6055f8a57524beaef59a48234" + }, + { + "path": "skills/code-prd/SKILL.md", + "sha256": "ad6c0e758f3555db679fb13383feec93cc2e675782f8c8345f590b30b54c888b" + }, + { + "path": "skills/code-prd/references/ux-enhancements.md", + "sha256": "232e12f38ca352bb1fa66cd021630d7f7fea522d78d8ae410962c10eb3f6d339" + }, + { + "path": "skills/publish/SKILL.md", + "sha256": "7ede07da302298ea6d1538e0f751def4eef77571d4b6015f193b11c6a3978a73" + }, + { + "path": "skills/plan-prd/SKILL.md", + "sha256": "7ad9833770c93913340b5d7049455658d497e406c274857f5e548ccac16fcd16" + } + ], + "dirSha256": "ba1f2c9dce5fccbb2c70341d16f9dc6c94099d693f670662165c1954d7350def" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file diff --git a/skills/code-prd/SKILL.md b/skills/code-prd/SKILL.md new file mode 100644 index 0000000..82779c6 --- /dev/null +++ b/skills/code-prd/SKILL.md @@ -0,0 +1,1590 @@ +--- +name: code-prd +description: Build features when user wants to implement PRDs, write code for specs, or develop functionality. Works incrementally substory-by-substory with automatic testing and code review. Automatically loads PRD context to maintain consistency. Also writes standalone tests for any file. +--- + +# Code PRD Implementation + +Write production-quality code for PRD substories with **automatic testing, code review, and iterative refinement** until ready. + +**Communication Style**: In all interactions and commit messages, be extremely concise and sacrifice grammar for the sake of concision. + +**UX Enhancements**: This skill includes advanced UX features detailed in `references/ux-enhancements.md`: +- Learning Mode (explain approach before substories) +- Smart PRD Discovery (auto-resume from last session) +- PRD Health Check (validate quality before implementing) +- Progress Visualization (visual progress bars) +- Dependency Warnings (detect blockers early) +- Smart Test Suggestions (complexity-based test plans) +- Code Review Insights (trends and gamification) +- Rollback Protection (auto-checkpoints at phases) +- Context-Aware Expansion Suggestions (data-driven next steps) +- Parallel Work Detection (merge conflict prevention) +- Adaptive Difficulty (workflow speeds up as you improve) + +## Philosophy + +- **Substory-by-substory**: Implement incrementally with progress tracking +- **Phase-level approval**: Auto-test and review each phase, get user approval before continuing +- **Auto-refinement**: Run code-review internally, fix issues, re-review until satisfied +- **Context-aware**: Load PRD context to maintain consistency (especially for expansions) +- **Flexible**: Can implement full PRD OR write standalone tests for any file + +## When to Activate + +This skill activates when user says things like: +- "implement [feature/PRD]" +- "build this feature" +- "code this" +- "develop [feature name]" +- "start implementation" +- "write code for [PRD/feature]" +- "write tests for [file/feature]" (standalone test mode) +- Any request to implement, build, or code a feature or PRD + +## Implementation Workflow + +### Phase 0: Validate Prerequisites and Configure Session + +**FIRST: Check for CLAUDE.md** + +```bash +if [[ ! -f "CLAUDE.md" ]]; then + cat <> .gitignore + echo "# Claude Code user-specific preferences (do not commit)" >> .gitignore + echo ".claude/user-preferences.json" >> .gitignore + fi +else + cat > .gitignore <<'GITIGNORE' +# Claude Code user-specific preferences (do not commit) +.claude/user-preferences.json +GITIGNORE +fi + +# Write user preferences +echo "{ + \"skill_level\": \"$user_level\", + \"learning_mode\": $learning_mode, + \"auto_approve_safe_changes\": $auto_approve_safe_changes, + \"last_updated\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" +}" > .claude/user-preferences.json + +echo "βœ… Preferences saved (local only, not committed to git)" +``` + +### Mode Detection + +**Check user request:** + +1. **PRD Implementation Mode** - User mentions PRD or says "implement" + - Full workflow with phases, substories, auto-testing, review + +2. **Standalone Test Mode** - User says "write tests for [file/feature]" + - Skip PRD, just write tests for specified files + - Detect testing framework + - Write comprehensive tests + - Run tests + - Done + +**For Standalone Test Mode**, jump to Step 8 (Write Tests). + +**For PRD Implementation Mode**, continue below: + +### Step 1: Load PRD, Context, and Project Conventions + +**First, ensure directory structure and load PRD:** + +```bash +# Ensure .claude directory structure exists +mkdir -p .claude/prds/context +mkdir -p .claude/prds/archive/context +mkdir -p .claude/checkpoints + +# Ensure checkpoints are gitignored +if [[ -f ".gitignore" ]]; then + if ! grep -q "\.claude/checkpoints" .gitignore; then + echo ".claude/checkpoints/" >> .gitignore + fi +fi + +# Source context manager +source skills/shared/scripts/context-manager.sh + +# Validate PRD file exists +if [[ ! -f "$prd_file" ]]; then + echo "❌ ERROR: PRD file not found: $prd_file" + exit 1 +fi + +# Read the PRD file +prd_content=$(cat "$prd_file") + +# Read project conventions from CLAUDE.md +if [[ ! -f "CLAUDE.md" ]]; then + echo "❌ ERROR: CLAUDE.md not found" + exit 1 +fi +claude_md=$(cat "CLAUDE.md") + +# Load or initialize PRD context +if context_exists "$prd_file"; then + context=$(read_context "$prd_file") + echo "βœ… Loaded existing context" +else + context_file=$(init_context "$prd_file") + context=$(read_context "$prd_file") + echo "βœ… Initialized new context" +fi +``` + +**If no PRD specified - Smart PRD Discovery:** + +```bash +# Strategy 1: Check for in-progress PRD from last session +last_prd="" +last_timestamp=0 + +# Check context files for most recently updated in-progress PRD +for context_file in .claude/prds/context/*.json; do + if [[ -f "$context_file" ]]; then + # Get last updated timestamp + timestamp=$(jq -r '.last_updated // 0' "$context_file" 2>/dev/null || echo 0) + prd_file=$(basename "$context_file" .json) + prd_path=".claude/prds/${prd_file}.md" + + # Check if PRD exists and is in progress + if [[ -f "$prd_path" ]] && grep -q "Status.*In Progress" "$prd_path"; then + if [[ $timestamp -gt $last_timestamp ]]; then + last_timestamp=$timestamp + last_prd=$prd_path + last_context=$context_file + fi + fi + fi +done + +# Strategy 2: Check git log for recently committed PRD references +recent_prd=$(git log -10 --oneline 2>/dev/null | grep -o '.claude/prds/[^)]*\.md' | head -1) + +# Strategy 3: Check recently modified files in .claude/prds/ +recent_file=$(ls -t .claude/prds/*.md 2>/dev/null | head -1) +``` + +**If found recent PRD in progress:** +``` +πŸ” Detected context from your last session: + +Working on: .claude/prds/2025-10-26-hello-world-core.md +Type: Core Feature +Status: Phase 1 - In Progress (2/3 substories complete) +Last worked: 2 hours ago + +Completed: +βœ… Substory 1.1: Basic MVC structure +βœ… Substory 1.2: RESTful routing + +Next up: +⏳ Substory 1.3: Integration tests + +Continue where you left off? [yes/choose-different/new]: +``` + +**If user says "choose-different" or no recent PRD found:** +``` +Available PRDs: + +In Progress: + 1. πŸ”„ [Core] hello-world-core - Basic hello world feature + Progress: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘ 66% (2/3 substories) + Last updated: 2 hours ago + +Not Started: + 2. ⏸️ [Expansion] hello-world-personalized - Add name parameter + Depends on: hello-world-core (not complete) + + 3. ⏸️ [Task] setup-ci-cd - Configure GitHub Actions + Estimated: 5 steps + +Completed: + 4. βœ… [Core] auth-core - OAuth authentication + Completed: 3 days ago + (Move to archive? Type 'archive 4') + +Which PRD? [1/2/3/4/new]: +``` + +**Determine PRD Type:** +Check PRD frontmatter for: +- `**Type:** Core Feature` +- `**Type:** Expansion` +- `**Type:** Task` + +**For Core PRDs:** +- Load CLAUDE.md for project conventions +- Load context file (patterns, libraries, decisions from previous sessions) +- Goal: Establish clean patterns that expansions will follow + +**For Task PRDs:** +- Load CLAUDE.md for project conventions +- Work through Implementation Checklist sequentially +- No phases/substories - just step-by-step execution +- Update checkboxes as steps complete +- Goal: Complete technical task efficiently + +**For Expansion PRDs (CRITICAL - AUTO-LOAD CORE CONTEXT):** + +**Step 1: Validate core PRD exists and is complete:** +```bash +# Extract core PRD path from "Builds On" field +core_prd=$(grep "Builds On:" "$prd_file" | sed 's/.*Builds On:.*\(docs\/prds\/[^)]*\).*/\1/') + +# Validate core PRD exists +if [[ ! -f "$core_prd" ]]; then + echo "❌ ERROR: Core PRD not found: $core_prd" + echo "This expansion requires a completed core PRD." + exit 1 +fi + +# Check core is marked complete +if ! grep -q "Status.*Complete" "$core_prd"; then + echo "⚠️ WARNING: Core PRD is not marked complete" + echo "Building expansions on incomplete cores may cause inconsistencies." + echo "Continue anyway? [yes/no]" +fi + +# Validate core context exists +core_context_file=".claude/prds/context/$(basename $core_prd .md).json" +if [[ ! -f "$core_context_file" ]]; then + echo "⚠️ WARNING: Core context file not found: $core_context_file" + echo "Context loading will be limited. Continue? [yes/no]" +fi +``` + +**Step 2: Load and analyze core context comprehensively:** +```bash +# Load CLAUDE.md for project conventions +claude_md=$(cat "CLAUDE.md") + +# Read core PRD +core_prd_content=$(cat "$core_prd") + +# Read core context file +core_context=$(cat "$core_context_file") + +# Extract structured data from context +core_files=$(echo "$core_context" | jq -r '.files_created[]') +core_patterns=$(echo "$core_context" | jq -r '.patterns') +core_libraries=$(echo "$core_context" | jq -r '.libraries') +core_decisions=$(echo "$core_context" | jq -r '.architectural_decisions[]') +testing_framework=$(echo "$core_context" | jq -r '.testing_framework') + +# Read and analyze each core implementation file +echo "πŸ“– Analyzing core implementation..." +for file in $core_files; do + if [[ -f "$file" ]]; then + # Read file to understand: + # - Class/function naming patterns + # - Code organization and structure + # - Error handling approaches + # - Validation patterns + # - API/interface design + # - Data access patterns + fi +done +``` + +**Step 3: Document comprehensive findings:** +``` +πŸ” Core Implementation Analysis (AUTO-LOADED): + +Core PRD: .claude/prds/YYYY-MM-DD-{feature}-core.md +Context: .claude/prds/context/YYYY-MM-DD-{feature}-core.json +Status: βœ… Complete + +Implementation Files ([X] files analyzed): +- path/to/model.ext - Data model with validations [describe key aspects] +- path/to/service.ext - Business logic service [describe key aspects] +- path/to/controller.ext - API endpoints [describe key aspects] +- path/to/repository.ext - Data access layer [describe key aspects] + +Established Patterns ([Y] patterns identified): +1. [Pattern Name] - [Description] + Location: [where used in core] + Example: [specific code example or approach] + +2. [Pattern Name] - [Description] + Location: [where used in core] + Example: [specific code example or approach] + +Libraries in Use ([Z] libraries): +- [Library 1] ([Version]) - [Purpose in core implementation] +- [Library 2] ([Version]) - [Purpose in core implementation] + +Architectural Decisions ([W] decisions): +1. [Decision]: [Rationale from context] +2. [Decision]: [Rationale from context] + +Code Analysis Insights: +- Naming convention: [Observed pattern, e.g., "FeatureService", "FeatureRepository"] +- Error handling: [Approach, e.g., "Custom exception hierarchy with FeatureError base"] +- Validation: [Approach, e.g., "Joi schemas in validators/ directory"] +- Data access: [Pattern, e.g., "Repository pattern with TypeORM"] +- Testing: [Framework and approach, e.g., "Jest with 95% coverage requirement"] + +Project Conventions (from CLAUDE.md): +- Tech stack: [List from CLAUDE.md] +- Architecture: [Pattern from CLAUDE.md] +- Code style: [Standards from CLAUDE.md] + +βœ… Expansion will EXTEND these patterns consistently. + - Will modify existing files where appropriate + - Will create new files following established naming + - Will use same libraries and approaches + - Will maintain architectural consistency +``` + +### Step 2: Analyze Existing Architecture + +**Before writing code, understand the codebase:** + +```bash +# Explore existing architecture patterns +# Find similar features/components +# Identify naming conventions +# Locate relevant directories +``` + +**Analyze:** +- Existing code structure and patterns +- Current architecture (layering, separation of concerns) +- Naming conventions in use +- Where similar features are implemented +- Data layer patterns (if applicable - database, ORM, storage) +- API patterns (if applicable - REST, GraphQL, gRPC) + +**Document findings based on your project's CLAUDE.md and codebase analysis.** + +### Step 2a: PRD Health Check + +**Before implementing, validate PRD quality:** + +```bash +# Run automated PRD quality analysis +prd_score=0 +issues=() +warnings=() + +# Check 1: Acceptance criteria defined +if grep -q "Acceptance Criteria:" "$prd_file"; then + prd_score=$((prd_score + 20)) +else + issues+=("❌ Missing acceptance criteria") +fi + +# Check 2: Success metrics defined +if grep -q "Success Criteria:" "$prd_file"; then + prd_score=$((prd_score + 15)) +else + warnings+=("⚠️ Missing success metrics") +fi + +# Check 3: Security considerations +if grep -qi "security\|auth\|permission\|sanitiz" "$prd_file"; then + prd_score=$((prd_score + 15)) +else + warnings+=("⚠️ No security considerations documented") +fi + +# Check 4: Performance requirements +if grep -qi "performance\|latency\|speed\|optimize" "$prd_file"; then + prd_score=$((prd_score + 10)) +else + warnings+=("⚠️ No performance requirements") +fi + +# Check 5: Error handling approach +if grep -qi "error\|exception\|failure\|fallback" "$prd_file"; then + prd_score=$((prd_score + 10)) +else + warnings+=("⚠️ No error handling strategy") +fi + +# Check 6: Testing strategy +if grep -qi "test\|testing\|coverage" "$prd_file"; then + prd_score=$((prd_score + 15)) +else + warnings+=("⚠️ No testing strategy defined") +fi + +# Check 7: Clear substories with phases +substory_count=$(grep -c "Substory" "$prd_file" || echo 0) +if [[ $substory_count -gt 0 ]]; then + prd_score=$((prd_score + 15)) +else + issues+=("❌ No substories defined") +fi +``` + +**Show health check results:** +``` +πŸ” PRD Health Check + +Analyzing: .claude/prds/2025-10-26-hello-world-core.md + +Quality Score: ${prd_score}/100 $(if [[ $prd_score -ge 80 ]]; then echo "(Excellent βœ…)"; elif [[ $prd_score -ge 60 ]]; then echo "(Good πŸ‘)"; elif [[ $prd_score -ge 40 ]]; then echo "(Acceptable ⚠️)"; else echo "(Needs Improvement ❌)"; fi) + +[If issues found:] +Critical Issues: +${issues[@]} + +[If warnings found:] +Recommendations: +${warnings[@]} + +[If prd_score >= 60:] +βœ… PRD quality is sufficient for implementation + +[If prd_score < 60:] +⚠️ PRD quality is below recommended threshold + +Options: +1. πŸ”§ Fix issues now (pause to improve PRD) +2. ⏭️ Implement anyway (accept risks) +3. πŸ“‹ Show detailed recommendations + +Choice [1/2/3/default: 2]: +``` + +**If user chooses "3 - Show detailed recommendations":** +``` +πŸ“‹ Detailed Recommendations + +To improve this PRD to ${100 - prd_score}% better quality: + +1. Add acceptance criteria for each substory + Why: Defines "done" clearly, prevents scope creep + How: For each substory, add checklist of verifiable outcomes + +2. Define success metrics + Why: Measurable goals help track feature effectiveness + How: Add metrics like "response time < 200ms" or "95% test coverage" + +3. Document security approach + Why: Security considerations upfront prevent vulnerabilities + How: Add section covering auth, input validation, data protection + +[etc for each missing element] + +Would you like to improve the PRD now? [yes/no/implement-anyway] +``` + +### Step 3: Parse PRD and Create Implementation Plan + +**Parse PRD for:** +- Phases and substories +- Current status (⏳ Not Started / πŸ”„ In Progress / βœ… Completed) +- Dependencies between substories +- Acceptance criteria for each + +**For new implementation:** +- Start at Phase 1, Substory 1 +- Show implementation plan +- Confirm approach with user + +**For continuation:** +- Load current_phase from context +- Find last in-progress (πŸ”„) or next pending (⏳) +- Show completion summary +- Confirm continuation point + +**Show plan with Progress Visualization:** +``` +πŸ“‹ Implementation Plan: [Feature Name] + +Overall Progress: β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ 0% (0/4 substories complete) + +Phase 1: [Phase Name] (4 substories) +β”œβ”€ ⏳ Substory 1.1: [Name] - Not Started +β”œβ”€ ⏳ Substory 1.2: [Name] - Not Started +β”œβ”€ ⏳ Substory 1.3: [Name] - Not Started +└─ ⏳ Substory 1.4: [Name] - Not Started + +Context loaded: βœ… +Patterns to follow: [list from context and CLAUDE.md] + +Ready to begin Phase 1? [yes/show-details/skip-to] +``` + +**For continuation (resuming in-progress PRD):** +``` +πŸ“‹ Implementation Plan: Hello World Core + +Overall Progress: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘ 66% (2/3 substories complete) + +Phase 1: Core Foundation (3 substories) +β”œβ”€ βœ… Substory 1.1: Basic MVC structure - Completed +β”œβ”€ βœ… Substory 1.2: RESTful routing - Completed +└─ πŸ”„ Substory 1.3: Integration tests - In Progress + +Context loaded: βœ… +Patterns established: Rails MVC, Thin controller pattern +Files created so far: 3 files, 1 modified + +Resume at Substory 1.3? [yes/show-details/restart-substory] +``` + +### Step 4: Implement Phase (Substory-by-Substory) + +**For each substory in the phase:** + +#### Step 4.0: Learning Mode Explanation (If Enabled) + +**πŸ“š See references/ux-enhancements.md Section 1 for full implementation** + +If Learning Mode is enabled, explain approach before implementing: +- Show what will be built and why +- Explain pattern choices and decisions +- List files to be created/modified +- Estimate complexity + +Give user option to proceed, request more details, or adjust approach. + +#### Step 4.1: Dependency Warnings Check + +**⚠️ See references/ux-enhancements.md Section 2 for full implementation** + +Before implementing substory, detect and warn about dependencies: +- Check for required API keys/credentials +- Verify external services are running +- Check for pending migrations +- Validate package dependencies + +If blockers found, offer to resolve, skip, or continue anyway. + +#### Mark Substory In Progress + +Update PRD: +```markdown +- πŸ”„ [1.1] User OAuth integration - In Progress + - Current: Implementing OAuth flow + - Started: YYYY-MM-DD HH:MM +``` + +Update context: +```bash +set_current_phase "$prd_file" "Phase 1: Substory 1.1" +``` + +#### Write Code + +**For Core PRDs:** +Establish clean, simple patterns that will be extended later. + +**For Expansion PRDs (CRITICAL - USE LOADED PATTERNS):** +- Reference loaded core implementation files +- Follow established patterns exactly +- Extend, don't replace core code +- Maintain consistency in naming, structure, and approach +- Use same libraries/services as core + +Follow project conventions from CLAUDE.md and established patterns from context. +- **For expansions**: Extend core code following established patterns + +**Quality Requirements:** +- Follow project conventions (CLAUDE.md, .editorconfig, linting) +- Write clean, readable code +- Add comments for complex logic +- Use consistent naming (especially in expansions - match core naming) +- Handle errors properly +- Validate inputs +- Log appropriately + +**Track files created/modified:** +```bash +# Add to context +add_created_file "$prd_file" "src/models/user.model.ts" +add_created_file "$prd_file" "src/services/oauth.service.ts" +``` + +**Track decisions made:** +```bash +# If using a new library or pattern +add_decision "$prd_file" "[Your architectural decision]" +set_library "$prd_file" "[category]" "[library name]" +set_pattern "$prd_file" "[pattern name]" "[pattern location/description]" +``` + +#### Mark Substory Complete + +Update PRD: +```markdown +- βœ… [1.1] User OAuth integration - Completed (YYYY-MM-DD) + Files: src/models/user.model.ts, src/services/oauth.service.ts + Summary: Implemented OAuth flow with provider support +``` + +#### Show Progress After Each Substory + +```markdown +βœ… Substory 1.1 complete! + +πŸ“ Files created/modified: +- src/models/user.model.ts (User model with OAuth fields) +- src/services/oauth.service.ts (OAuth service) +- src/dto/oauth-response.dto.ts (Response DTO) + +πŸ“Š Progress: 1/4 substories (25% of Phase 1) + +⏭️ Next: Substory 1.2 - OAuth callback handler +``` + +**Continue to next substory automatically** until phase is complete. + +### Step 4.9: Rollback Protection Checkpoint + +**πŸ’Ύ See references/ux-enhancements.md Section 3 for full implementation** + +Before starting each new phase, create automatic checkpoint: +- Save git state (diffs, status, commit hash) +- Backup PRD and context files +- Create rollback script +- Auto-add to .gitignore + +Show checkpoint confirmation with rollback instructions. + +### Step 5: Phase Complete - Auto-Test and Review Loop + +**When all substories in a phase are complete:** + +```markdown +πŸŽ‰ Phase 1 Complete: [Phase Name] + +βœ… Completed substories: +- [1.1] User OAuth integration +- [1.2] OAuth callback handler +- [1.3] Token management +- [1.4] Account linking + +πŸ“Š Phase Stats: +- Files: 8 files created/modified +- Lines: +350 lines +- Patterns: Service layer pattern established + +πŸ§ͺ Now running testing and review... +``` + +#### Step 5a: Auto-Run Tests + +**πŸ§ͺ See references/ux-enhancements.md Section 4 for Smart Test Suggestions** + +Before writing tests, analyze code complexity and suggest test strategy: +- Calculate cyclomatic complexity +- Count public methods and edge cases +- Recommend test coverage level (minimal/standard/comprehensive) +- Let user choose or customize test plan + +**Check if testing is applicable:** + +```bash +# Read CLAUDE.md for testing info +if grep -qi "no tests\|testing: none\|tests: n/a" CLAUDE.md; then + testing_disabled=true +fi +``` + +**If testing is disabled in CLAUDE.md:** +```markdown +ℹ️ Testing skipped (CLAUDE.md indicates no tests for this project) + +Proceeding to code review... +``` + +**If testing is enabled, analyze project testing setup comprehensively:** + +**Step 1: Identify testing framework and conventions:** +```bash +# Check CLAUDE.md for testing info +testing_info=$(grep -A 10 -i "testing\|test" CLAUDE.md) + +# Detect testing framework from multiple sources: +# 1. CLAUDE.md explicit mention +# 2. package.json/requirements.txt dependencies +# 3. Existing test file patterns +# 4. Test configuration files + +# Common framework detection: +if grep -q "jest" package.json 2>/dev/null; then + framework="Jest" + test_pattern="**/*.test.ts" +elif grep -q "pytest" requirements.txt 2>/dev/null; then + framework="pytest" + test_pattern="**/test_*.py" +elif grep -q "rspec" Gemfile 2>/dev/null; then + framework="RSpec" + test_pattern="**/spec/**/*_spec.rb" +elif grep -q "vitest" package.json 2>/dev/null; then + framework="Vitest" + test_pattern="**/*.test.ts" +fi + +# Find test command from package.json, Makefile, or CLAUDE.md +if [[ -f "package.json" ]]; then + test_cmd=$(jq -r '.scripts.test // empty' package.json) +elif [[ -f "Makefile" ]]; then + test_cmd=$(grep "^test:" Makefile | cut -d':' -f2 | xargs) +fi + +# Examine existing test files for patterns +existing_tests=$(find . -name "*test*" -o -name "*spec*" | head -5) +``` + +**Step 2: Analyze existing test patterns:** +``` +πŸ“Š Testing Framework Detected: [Framework] + +Test Configuration: +- Framework: [Framework and version] +- Test pattern: [File pattern, e.g., "*.test.ts"] +- Test command: [Command, e.g., "npm test"] +- Coverage tool: [Tool if detected, e.g., "Istanbul"] + +Existing Test Patterns (from analysis): +- Test file location: [Pattern, e.g., "__tests__/" or "spec/"] +- Naming convention: [Pattern, e.g., "feature.test.ts" or "feature_spec.rb"] +- Test structure: [Describe/it, test/expect, etc.] +- Mocking approach: [Library and pattern used] +- Setup/teardown: [How tests are initialized] + +Conventions from CLAUDE.md: +- Coverage requirement: [E.g., ">= 90%"] +- Test types required: [Unit, integration, e2e] +- Mock strategy: [Real vs mocked dependencies] +``` + +**Step 3: Write comprehensive tests following established patterns:** +- **Unit tests** for core logic (business logic, utilities, domain models) +- **Integration tests** for component interactions +- **Coverage** for all acceptance criteria from substories +- **Test cases**: + - Happy paths (expected successful flows) + - Error scenarios (validation failures, exceptions) + - Edge cases (boundary conditions, null/empty values) + - Business rule validation +- **Follow project conventions**: + - Match file naming and location patterns + - Use same test structure and assertions + - Follow mocking strategy from existing tests + - Match code style and organization + +**Step 4: Update context with testing info:** +```bash +# Save testing framework for future reference +update_context "$prd_file" "testing_framework" "$framework" +update_context "$prd_file" "test_command" "$test_cmd" +update_context "$prd_file" "test_pattern" "$test_pattern" +``` + +**Run tests:** +```bash +# Identify test command from CLAUDE.md or project config +# Execute tests +# Capture results + +# If test command fails or not found: +if [[ $test_exit_code -ne 0 ]] && [[ "$test_output" == *"command not found"* ]]; then + cat </dev/null || echo "unknown") +base_branch=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@' || echo "main") + +# Check if on main/master +on_main=false +if [[ "$current_branch" == "main" ]] || [[ "$current_branch" == "master" ]] || [[ "$current_branch" == "$base_branch" ]]; then + on_main=true +fi + +# Check for uncommitted changes +has_changes=false +if [[ -n $(git status --porcelain 2>/dev/null) ]]; then + has_changes=true +fi +``` + +Then show contextual completion message: + +```markdown +πŸŽ‰ Core PRD Complete! + +βœ… All phases implemented and tested: +- Phase 1: Core Foundation (3 substories) + +πŸ“Š Core Stats: +- Files created: 3 files +- Files modified: 1 file +- Tests: 2 tests, 3 assertions, 100% passing +- Patterns established: + * Rails MVC structure + * Thin controller pattern + * RESTful routing + * Minitest integration testing + * frozen_string_literal pragma + +🌱 Core foundation is ready! + +Context saved: .claude/prds/context/2025-10-26-hello-world-core.json +This context will be auto-loaded when creating expansion PRDs. + +πŸ’‘ Next steps: + +[If on_main == true && has_changes == true:] +**Git Status:** On main branch with uncommitted changes + +Choose an option or type your own: +1. πŸš€ Create pull request (creates feature branch, commits, pushes, opens PR) +2. πŸ“‹ Plan expansion (create expansion PRD to add more features) +3. ✏️ Continue coding (keep working on this branch) + +[If on_main == false && has_changes == true:] +**Git Status:** On branch '${current_branch}' with uncommitted changes + +Choose an option or type your own: +1. πŸ’Ύ Commit changes (creates commit on current branch) +2. πŸ“‹ Plan expansion (create expansion PRD to add more features) +3. ✏️ Continue coding (keep working without committing) + +[If on_main == false && has_changes == false:] +**Git Status:** On branch '${current_branch}' - ready to ship + +Choose an option or type your own: +1. πŸš€ Create pull request (push branch and open PR to ${base_branch}) +2. πŸ’Ύ Commit more changes (continue working on branch) +3. πŸ“‹ Plan expansion (create expansion PRD to add more features) + +[If on_main == true && has_changes == false:] +**Git Status:** On main branch - all changes committed + +**🎯 See references/ux-enhancements.md Section 7 for Context-Aware Expansion Suggestions** + +Analyze core implementation for smart expansion suggestions: +- Check "Out of Scope" section from PRD +- Find TODO comments in implemented files +- Analyze data model for missing relationships +- Rank by effort, impact, and dependencies + +Choose an option or type your own: +1. πŸ“‹ Plan expansion (create expansion PRD to add more features): + [Smart suggestions based on code analysis:] + - Personalized greeting (accept name parameter) + - Styling with CSS/Tailwind + - Interactive form version + - API endpoint version (JSON response) +2. ✏️ Start new feature (plan a different PRD) +3. 🎯 Other (describe what you'd like to do) + +What would you like to do? [1/2/3 or type your request]: +``` + +**For EXPANSION PRD:** + +First, detect git state (same as Core PRD), then show contextual completion: + +```markdown +πŸŽ‰ Expansion Complete: [Expansion Name] + +βœ… All phases implemented and tested: +- Phase 1: [Expansion Name] (3 substories) + +πŸ“Š Expansion Stats: +- Core files extended: 3 +- New files created: 5 +- Tests: 18 tests, 93% coverage +- Followed core patterns: βœ… + +Extended core with: +- [New functionality 1] +- [New functionality 2] + +Context updated: .claude/prds/context/2024-10-25-invoice-{expansion}.json + +πŸ’‘ Next steps: + +[If on_main == true && has_changes == true:] +**Git Status:** On main branch with uncommitted changes + +Choose an option or type your own: +1. πŸš€ Create pull request (creates feature branch, commits, pushes, opens PR) +2. πŸ“‹ Plan another expansion (add more features to core) +3. ✏️ Continue coding (keep working on this branch) + +[If on_main == false && has_changes == true:] +**Git Status:** On branch '${current_branch}' with uncommitted changes + +Choose an option or type your own: +1. πŸ’Ύ Commit changes (creates commit on current branch) +2. πŸ“‹ Plan another expansion (add more features to core) +3. ✏️ Continue coding (keep working without committing) + +[If on_main == false && has_changes == false:] +**Git Status:** On branch '${current_branch}' - ready to ship + +Choose an option or type your own: +1. πŸš€ Create pull request (push branch and open PR to ${base_branch}) +2. πŸ’Ύ Commit more changes (continue working on branch) +3. πŸ“‹ Plan another expansion (add more features to core) + +[If on_main == true && has_changes == false:] +**Git Status:** On main branch - all changes committed + +Choose an option or type your own: +1. πŸ“‹ Plan another expansion (continue building on core) +2. ✏️ Start new feature (plan a different PRD) +3. 🎯 Other (describe what you'd like to do) + +What would you like to do? [1/2/3 or type your request]: +``` + +**Handling User Response:** + +The user can respond in three ways: +1. **Select numbered option**: "1" or "2" or "3" +2. **Type natural language**: "I want to add authentication" or "let's create a PR" +3. **Use skill keywords**: "ship", "plan", "implement" + +**Map responses to actions:** +```bash +# If user selects option 1-3, map to the corresponding action +# If user types natural language, interpret intent: +# - Words like "commit", "save", "ship" β†’ trigger publish skill +# - Words like "pr", "pull request", "merge" β†’ trigger publish skill in PR mode +# - Words like "plan", "expansion", "add feature" β†’ trigger plan-prd skill +# - Otherwise, treat as continuation of conversation +``` + +### Step 8: Standalone Test Mode (No PRD) + +**When user says "write tests for [file/feature]":** + +**Step 1: Identify and validate target:** +```bash +# Specific files mentioned +if [[ -f "$target_file" ]]; then + target_files=("$target_file") +else + # Feature area - find related files + target_files=$(find . -name "*$feature*" -type f ! -path "*/test/*" ! -path "*/spec/*") +fi + +# Validate files exist +if [[ ${#target_files[@]} -eq 0 ]]; then + echo "❌ ERROR: No files found for: $target" + exit 1 +fi + +echo "πŸ“‹ Found ${#target_files[@]} files to test" +``` + +**Step 2: Comprehensive testing setup analysis:** +```bash +# Read CLAUDE.md for testing framework and conventions +testing_info=$(grep -A 10 -i "testing\|test" CLAUDE.md) + +# Detect framework (same logic as Phase implementation) +# - Check package.json, requirements.txt, Gemfile +# - Identify test command +# - Find test file patterns + +# Analyze existing test files +existing_tests=$(find . -name "*test*" -o -name "*spec*" | head -5) + +# For each existing test file, analyze: +# - File structure and organization +# - Test naming patterns +# - Assertion style +# - Mocking patterns +# - Setup/teardown approach +``` + +**Step 3: Present testing plan:** +``` +πŸ“Š Testing Setup Detected: + +Framework: [Framework name] +Test command: [Command to run tests] +Test file pattern: [Where to place tests] + +Files to test ([X] files): +- path/to/file1.ext - [Brief description of what it does] +- path/to/file2.ext - [Brief description of what it does] + +Test plan: +- Unit tests: [Estimated count] tests for [specific areas] +- Integration tests: [If applicable] +- Coverage goals: [From CLAUDE.md or project standard] + +Proceeding with test generation... +``` + +**Step 4: Analyze implementation files deeply:** +```bash +# For each target file, analyze: +# - Public API (exported functions, classes, methods) +# - Business logic and algorithms +# - Error handling paths +# - Input validation +# - Edge cases and boundary conditions +# - Dependencies and interactions +``` + +**Step 5: Write comprehensive tests following patterns:** +- **Unit tests** for: + - Each public method/function + - Business logic and calculations + - Validation rules + - Error handling + - Edge cases (null, empty, boundary values) + +- **Integration tests** (if applicable): + - Component interactions + - Database operations + - External service calls + - Full feature workflows + +- **Follow established patterns**: + - Match test file naming and location + - Use same test structure (describe/it, test/expect) + - Follow mocking strategy from existing tests + - Match assertion style and organization + - Include setup/teardown as needed + +**Step 6: Run tests and verify:** +```bash +# Run test command +$test_cmd + +# Capture results: +# - Pass/fail count +# - Coverage percentage +# - Any failures or errors +``` + +**Step 7: Report comprehensive results:** +```markdown +βœ… Tests written for [file/feature] + +πŸ“ Test files created: +- tests/unit/feature.test.ts (15 tests) + * Happy path scenarios: 5 tests + * Error handling: 4 tests + * Edge cases: 6 tests +- tests/integration/feature-flow.test.ts (8 tests) + * End-to-end workflows: 8 tests + +πŸ§ͺ Test results: +βœ… 23/23 tests passing +πŸ“Š Coverage: + - Overall: 96% (+12% from baseline) + - Branches: 94% + - Functions: 100% + - Lines: 96% + +⏱️ Duration: 2.3s + +Test breakdown: +- Unit tests: 15/15 passing +- Integration tests: 8/8 passing + +All acceptance criteria verified βœ… +Done! +``` + +**Important**: No PRD updates, no context management, just comprehensive tests following project patterns. + +## Blocker Handling + +If implementation is blocked: +1. Mark substory as πŸ”„ with blocker note +2. Document blocker in PRD: + ```markdown + - πŸ”„ [1.2] OAuth callback handler - Blocked + - Blocker: Need OAuth credentials from PM + - Waiting for: Client IDs and secrets + ``` +3. Ask user for resolution or skip to next non-blocked substory +4. Suggest workarounds if possible + +## Key Principles + +**This skill DOES:** +- Implement code substory-by-substory +- Show progress after each substory +- Auto-run tests after each phase +- Auto-run code review after each phase +- Auto-fix critical/major issues +- Ask for approval at phase boundaries +- Update PRD with status automatically +- Update context with patterns/decisions automatically +- Load core context for expansions automatically +- Write standalone tests without PRD + +**This skill DOES NOT:** +- Auto-continue to next phase without approval +- Auto-commit changes (that's "ship" skill's job) +- Auto-create PRs (that's "ship" skill's job) +- Skip testing or review +- Hide review findings from user + +**Workflow:** +``` +Implement substories β†’ Show progress β†’ Phase complete β†’ +Auto-test β†’ Auto-review β†’ Auto-fix β†’ Ask approval β†’ +Continue or stop +``` + +## Directory Structure + +The skill works with this directory structure: + +``` +.claude/ +β”œβ”€β”€ prds/ +β”‚ β”œβ”€β”€ YYYY-MM-DD-feature-core.md # Active PRD files +β”‚ β”œβ”€β”€ YYYY-MM-DD-feature-expansion.md +β”‚ β”œβ”€β”€ context/ # Active context files +β”‚ β”‚ β”œβ”€β”€ YYYY-MM-DD-feature-core.json +β”‚ β”‚ └── YYYY-MM-DD-feature-expansion.json +β”‚ └── archive/ # Manual archival (user responsibility) +β”‚ β”œβ”€β”€ old-feature.md # Archived PRD +β”‚ └── context/ +β”‚ └── old-feature.json # Archived context +β”œβ”€β”€ user-preferences.json # User-specific settings (GITIGNORED) +└── checkpoints/ # Rollback protection (GITIGNORED) + └── phase-1-20251026-143022/ + β”œβ”€β”€ git-diff.patch + β”œβ”€β”€ prd.md + └── rollback.sh + +.gitignore additions: +# Claude Code user-specific files (do not commit) +.claude/user-preferences.json +.claude/checkpoints/ +``` + +**Important Notes:** +- **PRDs and context files**: Committed to git (team-shared) +- **User preferences**: Local only, auto-gitignored (personal settings) +- **Checkpoints**: Local only, auto-gitignored (temporary rollback points) +- **Archive folder**: When archiving, move both .md and .json files to maintain the pair + +## UX Enhancement Reference Map + +This skill includes advanced UX features. At each workflow step, refer to references/ux-enhancements.md: + +| Workflow Step | UX Enhancement | Section | +|---------------|----------------|---------| +| **Phase 0** | Learning Mode Toggle | Section 1 | +| **Phase 0** | Adaptive Difficulty Check | Section 8 | +| **Step 1** | Smart PRD Discovery | Built-in | +| **Step 2a** | PRD Health Check | Built-in | +| **Step 3** | Progress Visualization | Built-in | +| **Step 4.0** | Learning Mode Explanation | Section 1 | +| **Step 4.1** | Dependency Warnings | Section 2 | +| **Step 4.9** | Rollback Protection | Section 3 | +| **Step 5a** | Smart Test Suggestions | Section 4 | +| **Step 5b** | Code Review Insights | Section 5 | +| **Step 6.5** | Parallel Work Detection | Section 6 | +| **Step 7** | Context-Aware Expansions | Section 7 | + +**When to read references/ux-enhancements.md:** +- At workflow step callouts (πŸ“š πŸ§ͺ πŸ“‹ πŸ’Ύ πŸ” 🎯 markers) +- When user requests specific feature (e.g., "enable learning mode") +- To understand full implementation details for any enhancement + +## Guidelines + +- Work incrementally (one substory at a time) +- Always load PRD context and CLAUDE.md at start +- For expansions: auto-load core context and files +- Always analyze existing architecture before coding +- Follow project conventions from CLAUDE.md and established patterns religiously +- Update PRD status after each substory +- Update context with patterns/libraries/decisions +- Auto-test after each phase (not per substory) +- Auto-review after tests pass +- Auto-fix critical/major issues +- Get approval at phase boundaries +- Track files created in context +- Communicate clearly and frequently +- Handle blockers gracefully +- Support standalone test mode +- **Reference references/ux-enhancements.md at callout steps for full feature implementation** diff --git a/skills/code-prd/references/ux-enhancements.md b/skills/code-prd/references/ux-enhancements.md new file mode 100644 index 0000000..70c7b70 --- /dev/null +++ b/skills/code-prd/references/ux-enhancements.md @@ -0,0 +1,646 @@ +# UX Enhancements Reference + +**Purpose:** Detailed implementation specifications for all UX enhancements in the code-prd skill. + +**Location:** `skills/code-prd/references/ux-enhancements.md` + +**How to use this reference:** +- Main workflow is in `SKILL.md` with callout markers (πŸ“š πŸ§ͺ πŸ“‹ πŸ’Ύ πŸ” 🎯) +- When you see a callout, read the corresponding section here for full implementation +- See "UX Enhancement Reference Map" in `SKILL.md` for quick navigation + +**File Type:** Reference documentation (loaded as needed, not executed directly) + +--- + +## Section 1: Learning Mode (Step 4.0 - Before each substory) + +**When enabled**, show explanation before implementing: + +```markdown +πŸ’‘ Learning Mode: ON + +About to implement: Substory 1.2 - OAuth callback handler + +πŸ“š My Approach: + +**What I'll build:** +Create `/auth/callback` endpoint to handle OAuth provider redirects + +**Why this pattern:** +- Follows RESTful routing (established in Substory 1.1) +- Separates concerns: Controller handles HTTP, Service handles OAuth logic +- Pattern from CLAUDE.md: Thin controller pattern + +**Key decisions:** +1. Use OAuthService (created in 1.1) for token exchange +2. Store tokens in encrypted format (Security best practice) +3. Handle errors with custom OAuthError class (Consistent error handling) + +**Files I'll create/modify:** +- `app/controllers/auth_controller.rb` - Add callback action +- `app/services/oauth_service.rb` - Add token_exchange method +- `spec/controllers/auth_controller_spec.rb` - Test callback flow + +**Estimated complexity:** Medium (involves external API calls) + +Ready to proceed? [yes/explain-more/adjust-approach] +``` + +**Smart mode** (only explain new patterns): +- Only shows explanation when introducing a pattern not seen in prior substories +- Skips explanation for repetitive patterns + +**Disabled mode:** +- Proceeds directly to implementation without explanation + +## Section 2: Dependency Warnings (Step 4.1 - Before substory execution) + +Before implementing each substory, check for dependencies: + +```bash +# Detect dependencies from substory description and acceptance criteria +dependencies=() + +# Check for API keys/credentials +if grep -qi "api\|oauth\|key\|secret\|credential" <<< "$substory_text"; then + # Check environment or config files + if ! grep -q "GOOGLE_CLIENT_ID\|GITHUB_CLIENT_ID" .env 2>/dev/null; then + dependencies+=("oauth_credentials") + fi +fi + +# Check for database migrations +if grep -qi "database\|migration\|schema\|table" <<< "$substory_text"; then + # Check if migrations are pending + if [[ $(rails db:migrate:status 2>/dev/null | grep -c "down") -gt 0 ]]; then + dependencies+=("pending_migrations") + fi +fi + +# Check for external services +if grep -qi "redis\|elasticsearch\|postgres\|mysql" <<< "$substory_text"; then + # Check if services are running + if ! pgrep -x "redis-server" > /dev/null 2>&1; then + dependencies+=("redis_not_running") + fi +fi + +# Check for package dependencies +if grep -qi "npm install\|bundle install\|pip install" <<< "$substory_text"; then + # Check if lock file is newer than node_modules + if [[ package-lock.json -nt node_modules ]]; then + dependencies+=("packages_outdated") + fi +fi +``` + +**Show dependency warnings:** + +```markdown +⚠️ Dependency Check: Substory 1.3 - Token encryption + +Found 2 potential blockers: + +1. πŸ”‘ OAuth Credentials Required + - Need: GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET + - Status: ❌ Not found in .env file + + Options: + a. Set up credentials now (I'll guide you) + b. Skip this substory for now (mark as blocked) + c. Use mock credentials for testing + +2. πŸ“¦ Package Dependencies + - Package 'jose' (JWT library) not installed + - Required for token encryption + + Options: + a. Install now: npm install jose + b. Use alternative library + c. Skip encryption for now (not recommended) + +How would you like to proceed? [resolve-all/skip/continue-anyway] +``` + +**If user chooses "resolve-all":** +Guide through each dependency setup step-by-step. + +**If user chooses "skip":** +Mark substory as blocked, move to next unblocked substory. + +**If user chooses "continue-anyway":** +Warn about potential failures, proceed with implementation. + +## Section 3: Rollback Protection (Step 4.9 - Phase boundaries) + +Before starting each new phase, create automatic checkpoint: + +```bash +# Create rollback checkpoint before Phase start +phase_number="$1" +checkpoint_dir=".claude/checkpoints" +checkpoint_name="phase-${phase_number}-$(date +%Y%m%d-%H%M%S)" +checkpoint_path="${checkpoint_dir}/${checkpoint_name}" + +mkdir -p "$checkpoint_path" + +# Note: checkpoints directory and gitignore are created in Phase 0/Step 1 + +# Save git state +git diff > "${checkpoint_path}/git-diff.patch" +git diff --cached > "${checkpoint_path}/git-diff-staged.patch" +git status --porcelain > "${checkpoint_path}/git-status.txt" +git rev-parse HEAD > "${checkpoint_path}/git-commit.txt" + +# Save PRD state +cp "$prd_file" "${checkpoint_path}/prd.md" +cp "$context_file" "${checkpoint_path}/context.json" + +# Save file list +find . -type f -newer "${checkpoint_path}/../last-checkpoint" 2>/dev/null > "${checkpoint_path}/modified-files.txt" || true + +# Create rollback script +cat > "${checkpoint_path}/rollback.sh" <<'ROLLBACK' +#!/bin/bash +echo "πŸ”„ Rolling back to checkpoint: ${checkpoint_name}" +echo "" +echo "This will:" +echo "- Restore PRD and context files" +echo "- Undo all uncommitted changes since checkpoint" +echo "- Restore modified files" +echo "" +read -p "Continue with rollback? [yes/no]: " confirm + +if [[ "$confirm" == "yes" ]]; then + git apply --reverse git-diff.patch 2>/dev/null || true + git apply --reverse git-diff-staged.patch 2>/dev/null || true + cp prd.md "$prd_file" + cp context.json "$context_file" + echo "βœ… Rollback complete" +else + echo "Rollback cancelled" +fi +ROLLBACK + +chmod +x "${checkpoint_path}/rollback.sh" + +# Update last checkpoint marker +touch "${checkpoint_dir}/last-checkpoint" +``` + +**Show checkpoint confirmation:** + +```markdown +πŸ’Ύ Checkpoint Created: Phase 2 Start + +Saved current state before beginning Phase 2 + +Checkpoint includes: +- Current code state (3 files modified) +- PRD status (Phase 1 complete, 66% overall) +- Context data (patterns, decisions, files) + +If something goes wrong during Phase 2: +- Type "rollback" to undo Phase 2 changes +- Run: .claude/checkpoints/phase-2-20251026-143022/rollback.sh + +Checkpoint expires: 24 hours (auto-cleanup) + +Proceeding to Phase 2... +``` + +## Section 4: Smart Test Suggestions (Step 5a - Test writing) + +Analyze code complexity before writing tests: + +```bash +# Analyze code complexity for smart test suggestions +analyze_code_complexity() { + local file="$1" + + # Cyclomatic complexity (count branches: if, case, for, while, &&, ||) + complexity=$(grep -c "if\|case\|for\|while\|&&\|||" "$file" 2>/dev/null || echo 0) + + # Count public methods/functions + public_methods=$(grep -c "def \|function \|export function" "$file" 2>/dev/null || echo 0) + + # Count edge cases (null checks, empty checks, error handling) + edge_cases=$(grep -c "nil?\|null\|undefined\|empty?\|rescue\|catch\|raise\|throw" "$file" 2>/dev/null || echo 0) + + # Lines of code + loc=$(wc -l < "$file" 2>/dev/null || echo 0) + + # Determine complexity level + if [[ $complexity -lt 3 ]] && [[ $loc -lt 50 ]]; then + echo "low" + elif [[ $complexity -lt 8 ]] && [[ $loc -lt 150 ]]; then + echo "medium" + else + echo "high" + fi +} +``` + +**Show test strategy suggestion:** + +```markdown +πŸ§ͺ Test Strategy: Substory 1.3 - OAuth token encryption + +πŸ“Š Code Complexity Analysis: +- Complexity score: Medium (cyclomatic complexity: 5) +- Public API: 3 methods (encrypt_token, decrypt_token, validate_token) +- Edge cases detected: 4 (nil token, invalid format, expired token, encryption error) +- Lines of code: 87 lines + +🎯 Recommended Test Coverage: + +Unit Tests (Recommended: 10 tests) + βœ… Happy paths: 3 tests + - encrypt_token with valid data + - decrypt_token with valid encrypted token + - validate_token with valid token + + βœ… Error handling: 4 tests + - nil/empty token input + - malformed encrypted data + - expired token validation + - encryption key missing + + βœ… Edge cases: 3 tests + - Very long tokens (>4KB) + - Special characters in tokens + - Concurrent encryption requests + +Integration Tests (Optional: 1 test) + ⚑ Full OAuth flow with token encryption/decryption + +E2E Tests (Skip) + ⏭️ Not needed - no direct user interaction + +πŸ“‹ Test Plan Summary: +- Total tests: 10-11 +- Estimated coverage: 95%+ +- Focus: Error handling (high risk area) + +Proceed with this test plan? [yes/add-more/minimal/custom] +``` + +**If user chooses "minimal":** +Only write happy path tests (3 tests). + +**If user chooses "add-more":** +Ask what additional scenarios to cover. + +**If user chooses "custom":** +Let user specify exact test cases. + +## Section 5: Code Review Insights Summary (Step 5b - After review) + +Enhanced review output with trends and gamification: + +```markdown +πŸ“‹ Code Review Complete: Substory 1.3 + +🎯 Quality Score: 89/100 (Excellent βœ…) + +πŸ“ˆ Trend Analysis: + Security: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ 95% (+5% from last substory ⬆️) + Performance: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘ 85% (+2% ⬆️) + Readability: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘ 92% (same) + Testability: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘ 88% (+8% ⬆️) + Maintainability: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘ 87% (+3% ⬆️) + +πŸ† Achievements Unlocked: + ✨ Security Champion - 3 substories in a row with 90%+ security score + 🎯 Test Master - Achieved 95%+ test coverage + πŸ“š Pattern Consistency - 100% adherence to established patterns + +βœ… Top Wins: + β€’ Excellent error handling with custom exception hierarchy + β€’ Clear naming conventions throughout + β€’ Comprehensive test coverage (96%) + β€’ Good documentation in complex methods + +πŸ’‘ Focus Areas for Next Substory: + β€’ Consider extracting magic constants (found 2 instances) + β€’ Add database index for oauth_tokens.user_id (performance optimization) + β€’ Document the encryption algorithm choice (maintainability) + +πŸ”„ Iteration History: + β€’ Iteration 1: Found 2 major issues β†’ Auto-fixed + β€’ Iteration 2: Clean βœ… + +All critical and major issues resolved! +``` + +## Section 6: Parallel Work Detection (Step 6.5 - Before continuing to next phase) + +Check for concurrent changes on main branch: + +```bash +# Detect parallel work that might conflict +current_branch=$(git rev-parse --abbrev-ref HEAD) +base_branch=$(git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@') + +# Get files changed in current branch +our_files=$(git diff --name-only $base_branch...HEAD) + +# Fetch latest from remote +git fetch origin $base_branch --quiet 2>/dev/null + +# Get files changed on base branch since we branched off +their_files=$(git diff --name-only HEAD...origin/$base_branch) + +# Find overlapping files +conflicts=$(comm -12 <(echo "$our_files" | sort) <(echo "$their_files" | sort)) + +if [[ -n "$conflicts" ]]; then + # Analyze conflict risk + conflict_count=$(echo "$conflicts" | wc -l) + + # Get commit authors + for file in $conflicts; do + author=$(git log -1 --format='%an <%ae>' origin/$base_branch -- "$file") + timestamp=$(git log -1 --format='%ar' origin/$base_branch -- "$file") + done +fi +``` + +**Show parallel work warning:** + +```markdown +⚠️ Parallel Work Detected + +While working on this PRD, changes were made to ${base_branch}: + +Potentially Conflicting Files: + 1. src/services/oauth_service.rb + - Modified by: Sarah Chen + - When: 2 hours ago + - Commit: "refactor: extract token validation logic" + + 2. app/controllers/auth_controller.rb + - Modified by: Mike Johnson + - When: 45 minutes ago + - Commit: "feat: add rate limiting to auth endpoints" + +Risk Level: 🟑 MEDIUM + - 2 files overlap with your changes + - Affects Substories: 1.2, 1.3 + +πŸ“Š Impact Analysis: + - Both files are in your current phase + - oauth_service.rb: Moderate overlap (refactored same methods) + - auth_controller.rb: Minor overlap (different endpoints) + +Options: +1. πŸ”„ Merge ${base_branch} now (recommended) + - Pauses PRD implementation + - Resolves conflicts immediately + - Continues with updated code + +2. ⏭️ Continue and merge later + - Higher risk of complex conflicts + - May require rework + +3. πŸ“ž Coordinate with team + - Notify Sarah and Mike + - Discuss approach before proceeding + +4. πŸ” Show detailed diff + - Review exactly what changed + +What would you like to do? [1/2/3/4] +``` + +## Section 7: Context-Aware Expansion Suggestions (Step 7 - Core PRD completion) + +Analyze codebase to suggest smart expansions: + +```bash +# Analyze core implementation for expansion suggestions +analyze_for_expansions() { + local prd_file="$1" + local context_file="$2" + + suggestions=() + + # Strategy 1: Analyze "Out of Scope" section from PRD + out_of_scope=$(sed -n '/Out of Scope/,/^##/p' "$prd_file") + + # Strategy 2: Find TODO comments in implemented files + files_created=$(jq -r '.files_created[]' "$context_file") + todos=$(grep -rh "TODO\|FIXME\|ENHANCEMENT" $files_created 2>/dev/null || true) + + # Strategy 3: Analyze data model for missing relationships + # Look for foreign keys without inverse relationships + + # Strategy 4: Check CLAUDE.md for planned features + planned_features=$(sed -n '/Planned Features\|Roadmap/,/^##/p' CLAUDE.md 2>/dev/null || true) + + # Strategy 5: Analyze usage patterns (if analytics/logs available) + # Find commonly accessed fields that don't exist yet + + # Rank suggestions by: + # - Effort (lines of code, complexity) + # - Impact (usage frequency, business value from comments) + # - Dependencies (what else is needed) +} +``` + +**Show smart expansion suggestions:** + +```markdown +🎯 Smart Expansion Suggestions + +Based on your core implementation, here are natural next steps: + +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 1. πŸ”₯ Customer Details (HIGH PRIORITY) β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Why recommended: β”‚ +β”‚ β€’ Found 73% of invoices reference 'customer_id' in DB β”‚ +β”‚ β€’ Listed in "Out of Scope" section of core PRD β”‚ +β”‚ β€’ 5 TODO comments mention customer information β”‚ +β”‚ β”‚ +β”‚ Effort: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘ Medium (2-3 substories) β”‚ +β”‚ Impact: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ Very High (critical for production) β”‚ +β”‚ Builds on: Invoice model, InvoiceService pattern β”‚ +β”‚ β”‚ +β”‚ Would add: β”‚ +β”‚ β€’ Customer model with name, email, address β”‚ +β”‚ β€’ Invoice-Customer association β”‚ +β”‚ β€’ Customer selection in invoice forms β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 2. πŸ’‘ Line Items (QUICK WIN) β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Why recommended: β”‚ +β”‚ β€’ Follows same service pattern as InvoiceService β”‚ +β”‚ β€’ Mentioned in CLAUDE.md planned features β”‚ +β”‚ β€’ Low complexity, high value β”‚ +β”‚ β”‚ +β”‚ Effort: β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘ Small (1-2 substories) β”‚ +β”‚ Impact: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘ High (enables itemized invoices) β”‚ +β”‚ Builds on: Invoice model, existing CRUD patterns β”‚ +β”‚ β”‚ +β”‚ Would add: β”‚ +β”‚ β€’ LineItem model (description, quantity, unit_price) β”‚ +β”‚ β€’ Has-many relationship with Invoice β”‚ +β”‚ β€’ Automatic total calculation β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 3. πŸš€ Tax Calculations (HIGH IMPACT) β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Why recommended: β”‚ +β”‚ β€’ TODO comment: "Add tax calculation for compliance" β”‚ +β”‚ β€’ Required for production use β”‚ +β”‚ β€’ Blocked until Line Items implemented β”‚ +β”‚ β”‚ +β”‚ Effort: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘ Large (4-5 substories) β”‚ +β”‚ Impact: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ Critical (regulatory requirement) β”‚ +β”‚ Depends on: Line Items expansion β”‚ +β”‚ Complexity: Tax rules, multi-jurisdiction support β”‚ +β”‚ β”‚ +β”‚ Would add: β”‚ +β”‚ β€’ TaxRule model with regional rates β”‚ +β”‚ β€’ Tax calculation service β”‚ +β”‚ β€’ Tax line items in invoices β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + +πŸ“Š Recommended Order: + 1st: Customer Details (unblocks other features) + 2nd: Line Items (enables Tax Calculations) + 3rd: Tax Calculations (compliance requirement) + +Which expansion interests you? [1/2/3/custom/plan-all]: +``` + +**If user selects number:** +Trigger plan-prd skill with pre-filled expansion context. + +**If user chooses "plan-all":** +Create PRDs for all three expansions in sequence. + +**If user chooses "custom":** +Let user describe their own expansion idea. + +## Section 8: Adaptive Difficulty (Phase 0 - Session configuration) + +Track user progress and adapt workflow: + +```bash +# Calculate user skill level based on history +calculate_skill_level() { + local prds_completed=$(find .claude/prds/context -name "*.json" -exec jq -r 'select(.status=="complete") | .prd_name' {} \; | wc -l) + local avg_quality=$(find .claude/prds/context -name "*.json" -exec jq -r '.code_quality_scores[]' {} \; | awk '{sum+=$1; n++} END {if (n>0) print sum/n; else print 0}') + local avg_coverage=$(find .claude/prds/context -name "*.json" -exec jq -r '.test_coverage' {} \; | awk '{sum+=$1; n++} END {if (n>0) print sum/n; else print 0}') + + # Determine level + if [[ $prds_completed -ge 10 ]] && [[ $(echo "$avg_quality > 90" | bc) -eq 1 ]]; then + echo "advanced" + elif [[ $prds_completed -ge 5 ]] && [[ $(echo "$avg_quality > 80" | bc) -eq 1 ]]; then + echo "intermediate" + else + echo "beginner" + fi +} +``` + +**Advanced mode unlocked message:** + +```markdown +πŸŽ“ Level Up! Advanced Mode Unlocked + +Based on your track record: +- βœ… PRDs completed: 12 +- βœ… Avg code quality: 94/100 +- βœ… Test coverage: Consistently 92%+ +- βœ… Pattern consistency: Excellent + +You've unlocked Advanced Mode features: + +πŸš€ Speed Optimizations: + β€’ Auto-approve low-risk changes (skip simple confirmations) + β€’ Skip repetitive explanations in Learning Mode + β€’ Parallel substory execution where possible + β€’ Fast-track phase approvals for clean code + +🎯 Advanced Features: + β€’ Custom code review rules + β€’ Configurable test thresholds + β€’ Advanced refactoring suggestions + β€’ Performance profiling integration + +βš™οΈ Customization: + β€’ Define your own quality gates + β€’ Set preferred patterns per project + β€’ Custom commit message templates + +Enable Advanced Mode? [yes/not-yet/customize] + +(You can always change this in .claude/user-preferences.json) +``` + +**Adaptive behaviors by level:** + +**Beginner:** +- Learning Mode ON by default +- Detailed explanations +- All confirmations required +- Guided dependency resolution +- Thorough code review + +**Intermediate:** +- Learning Mode Smart by default +- Condensed explanations +- Skip trivial confirmations +- Suggested fixes with approval +- Standard code review + +**Advanced:** +- Learning Mode OFF by default +- Minimal explanations +- Auto-approve safe changes +- Auto-fix simple issues +- Streamlined code review with trends + +--- + +## Implementation Notes + +All these features integrate seamlessly into the existing code-prd workflow: + +1. **Learning Mode**: Triggered before each substory if enabled (Step 4.0) +2. **Dependency Warnings**: Checked before substory execution (Step 4.1) +3. **Rollback Protection**: Created at phase boundaries (Step 4.9) +4. **Smart Test Suggestions**: Integrated into test writing step (Step 5a) +5. **Code Review Insights**: Enhanced review output format (Step 5b) +6. **Parallel Work Detection**: Checked at phase boundaries before continuing (Step 6.5) +7. **Context-Aware Suggestions**: Shown at PRD completion (Step 7) +8. **Adaptive Difficulty**: Calculated at session start, influences all steps (Phase 0) + +User preferences stored in `.claude/user-preferences.json` (auto-gitignored): +```json +{ + "skill_level": "intermediate", + "learning_mode": true, + "auto_approve_safe_changes": false, + "last_updated": "2025-10-26T14:30:22Z" +} +``` + +**Important:** This file is automatically added to `.gitignore` to prevent: +- Merge conflicts between developers +- Accidentally committing personal preferences +- Team preferences overwriting individual settings + +The skill automatically ensures `.gitignore` contains: +```gitignore +# Claude Code user-specific files (do not commit) +.claude/user-preferences.json +.claude/checkpoints/ +``` diff --git a/skills/plan-prd/SKILL.md b/skills/plan-prd/SKILL.md new file mode 100644 index 0000000..c907b46 --- /dev/null +++ b/skills/plan-prd/SKILL.md @@ -0,0 +1,796 @@ +--- +name: plan-prd +description: Create product requirement documents when user wants to plan features, write specs, or document new functionality. Supports minimal core features, focused expansions, and task-based changes. Automatically loads context from related PRDs to maintain consistency. +--- + +# Plan PRD + +Create structured PRDs using the **"land then expand"** approach with automatic context management for consistency. + +**Communication Style**: In all interactions and commit messages, be extremely concise and sacrifice grammar for the sake of concision. + +## Philosophy: Land Then Expand + +Modern Claude models work best when they establish patterns first, then layer complexity. This skill creates: + +1. **Core PRDs**: Minimal foundation with essential fields only (2-4 substories max) +2. **Expansion PRDs**: Focused enhancements building on completed core with auto-loaded context + +**Why**: Large comprehensive PRDs lead to incorrect assumptions, token inefficiency, and inconsistent results. + +## Activation Context + +Use when user says things like: +- "plan a feature for..." +- "write a PRD for..." +- "I want to build..." +- "document requirements for..." +- "create a spec for..." +- "plan [feature name]" +- Any request to plan, design, or document new functionality + +## Workflow + +### Phase 0: Validate Prerequisites + +**FIRST: Check for CLAUDE.md** + +```bash +if [[ ! -f "CLAUDE.md" ]]; then + cat <> .gitignore + fi +fi + +# Note: archive/ is for user manual archival only +# Users should move both .md and corresponding .json to archive/ +# to keep PRD and context paired together +``` diff --git a/skills/publish/SKILL.md b/skills/publish/SKILL.md new file mode 100644 index 0000000..3a3f9a0 --- /dev/null +++ b/skills/publish/SKILL.md @@ -0,0 +1,1006 @@ +--- +name: publish +description: Ship code when user wants to commit changes, create pull requests, or save work. Auto-detects whether to create commits or PRs based on git state. Generates well-formatted messages with PRD references. Always waits for approval before executing git commands. +--- + +# Publish Changes + +Create well-formatted git commits and GitHub pull requests with automatic PRD referencing. This skill is a **git assistant** - it helps you ship code, you stay in control. + +## When to Activate + +This skill activates when user says things like: +- "ship this" +- "commit changes" +- "save my work" +- "create a commit" +- "make a PR" +- "create pull request" +- "submit for review" +- "push this code" +- Any request to commit, ship, or create a pull request + +## Mode Detection + +The skill **automatically detects** what you want to do based on git state: + +1. **Commit Mode** - When uncommitted changes exist + - Detects: Uncommitted changes in working directory + - Creates: Conventional commit with PRD reference + - Shows: Preview before execution + +2. **Pull Request Mode** - When branch is clean and ahead of base + - Detects: Clean working directory + commits ahead of main/master + - Creates: GitHub PR with comprehensive description + - Shows: Preview before execution + +**User says "ship" β†’ Skill detects mode β†’ Confirms with user β†’ Executes** + +## Workflow + +### Mode 1: Commit + +#### Step 0: Confirm Mode Detection + +**Show detected mode to user:** +``` +πŸ” Detected uncommitted changes + +Mode: Commit +Files changed: 8 files (+247/-58 lines) + +Proceed with commit creation? [yes/show-changes/cancel] +``` + +**If user says "show-changes":** +- Show full `git diff --stat` +- Then ask again: "Proceed with commit? [yes/cancel]" + +**If user says "cancel":** +- Exit without doing anything + +**If user says "yes":** +- Continue to Step 1 + +#### Step 1: Analyze Changes Comprehensively + +**Load git tools and analyze changes:** +```bash +# Source shared git tools +source skills/shared/scripts/git-tools.sh + +# Analyze changes with detailed stats +changes=$(analyze_git_changes "HEAD") + +# Parse the output +files_changed=$(echo "$changes" | grep "FILES_CHANGED=" | cut -d'=' -f2) +insertions=$(echo "$changes" | grep "INSERTIONS=" | cut -d'=' -f2) +deletions=$(echo "$changes" | grep "DELETIONS=" | cut -d'=' -f2) + +# Get detailed file list with status +git diff HEAD --name-status + +# Categorize changes by type +new_files=$(git diff HEAD --name-only --diff-filter=A) +modified_files=$(git diff HEAD --name-only --diff-filter=M) +deleted_files=$(git diff HEAD --name-only --diff-filter=D) +``` + +**Analyze change patterns:** +```bash +# Group files by directory/area +# Detect if changes span multiple features +# Identify primary area of change + +# Analyze actual diff content to understand nature of changes: +# - Are we adding new functionality? (new classes, functions) +# - Are we fixing bugs? (error handling, validation) +# - Are we refactoring? (moving code, renaming) +# - Are we updating tests? (test files changed) +``` + +**Show comprehensive change summary:** +``` +πŸ“Š Changes Analyzed: + +Statistics: +- 8 files changed (+247/-58 lines) +- New files: 2 +- Modified files: 5 +- Deleted files: 1 + +Changes by area: +- Authentication (5 files, +180/-20 lines) + * app/models/user.rb + * app/services/auth/oauth_service.rb + * app/controllers/auth_controller.rb + * spec/models/user_spec.rb + * spec/services/oauth_service_spec.rb + +- Testing (3 files, +67/-38 lines) + * spec/models/user_spec.rb + * spec/services/oauth_service_spec.rb + * spec/integration/oauth_flow_spec.rb + +Nature of changes: +- New functionality: OAuth provider integration +- Modified: User model with OAuth fields +- Tests: Comprehensive test coverage added +``` + +**Check for multiple unrelated areas:** +If changes span multiple distinct features, suggest splitting: +``` +πŸ’‘ Notice: Changes span multiple areas: + - Authentication (5 files) + - Booking system (3 files) + + These appear to be unrelated changes. Recommend splitting into: + 1. Commit for authentication changes + 2. Commit for booking changes + + Benefits: Cleaner history, easier review, better git bisect + + Continue with single commit? [yes/split/cancel] +``` + +**If user chooses "split":** +- Help create multiple commits by feature area +- Process each area separately through commit workflow + +#### Step 2: Analyze Changed Files + +```bash +# Get changed files +changed_files=$(git diff HEAD --name-only) + +# Optionally detect scope from common directory patterns +# Scope is optional and can be omitted if not clear +scope=$(detect_scope_from_files "$changed_files") +``` + +**Note**: Scope detection uses simple heuristics (most common directory). Claude will analyze the changes and may choose to omit scope if it's not meaningful or use a more descriptive scope based on the actual changes. + +#### Step 3: Determine Commit Type + +Analyze changes to identify type: + +- **feat**: New feature or capability +- **fix**: Bug fix +- **refactor**: Code refactoring (no functional change) +- **docs**: Documentation only +- **test**: Adding or updating tests +- **chore**: Maintenance (dependencies, config, etc.) +- **perf**: Performance improvement +- **style**: Code style/formatting (no logic change) + +#### Step 4: Find Related PRD Intelligently + +**Multi-strategy PRD detection:** +```bash +# Source context manager +source skills/shared/scripts/context-manager.sh + +# Strategy 1: Check recent commits for PRD references +prd_from_commits=$(git log -5 --oneline | grep -o '.claude/prds/[^)]*\.md' | head -1) + +# Strategy 2: Find PRD from changed files +# - Match file paths to PRD context files +# - Check .claude/prds/context/*.json for files_created +for context_file in .claude/prds/context/*.json; do + if [[ -f "$context_file" ]]; then + context_files=$(jq -r '.files_created[]' "$context_file") + # Check if any changed files match context files + for changed_file in $changed_files; do + if echo "$context_files" | grep -q "$changed_file"; then + prd_file=$(basename "$context_file" .json) + related_prd=".claude/prds/${prd_file}.md" + break 2 + fi + done + fi +done + +# Strategy 3: Check for in-progress PRDs +# - Find PRDs with status "In Progress" +# - Suggest most recently modified PRD +in_progress_prds=$(grep -l "Status.*In Progress" .claude/prds/*.md 2>/dev/null) + +# Strategy 4: Ask user if multiple matches or no match found +if [[ -z "$related_prd" ]] && [[ -n "$in_progress_prds" ]]; then + # Present options to user +fi +``` + +**Show PRD detection results:** +``` +πŸ” PRD Detection: + +Strategy used: [Strategy name] +Related PRD: .claude/prds/2024-10-25-oauth-core.md + +PRD Details: +- Type: Core Feature +- Status: In Progress +- Phase: Phase 1 - OAuth Integration (3/4 substories complete) + +This commit relates to: [Substory 1.3] Token management + +βœ… Will include PRD reference in commit message +``` + +**If no PRD detected:** +``` +ℹ️ No related PRD detected + +Checked: +- Recent commits (no PRD references found) +- Context files (changed files don't match any PRD) +- In-progress PRDs (none found) + +Options: +1. Continue without PRD reference (standalone commit) +2. Manually specify PRD: [enter path] + +Choice: [1/2] +``` + +#### Step 5: Generate Commit Message + +**Format:** +``` +(): +# or if scope is not meaningful: +: + + + +