diff --git a/plugins/claude-config-maintainer/commands/analyze.md b/plugins/claude-config-maintainer/commands/analyze.md index 3df813b..18a3ecc 100644 --- a/plugins/claude-config-maintainer/commands/analyze.md +++ b/plugins/claude-config-maintainer/commands/analyze.md @@ -4,29 +4,18 @@ description: Analyze CLAUDE.md for optimization opportunities and plugin integra # Analyze CLAUDE.md -This command analyzes your project's CLAUDE.md file and provides a detailed report on optimization opportunities and plugin integration status. +Analyze your CLAUDE.md and provide a scored report with recommendations. + +## Skills to Load + +- skills/visual-header.md +- skills/analysis-workflow.md +- skills/optimization-patterns.md +- skills/pre-change-protocol.md ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ ⚙️ CONFIG-MAINTAINER · CLAUDE.md Analysis │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the analysis. - -## What This Command Does - -1. **Read CLAUDE.md** - Locates and reads the project's CLAUDE.md file -2. **Analyze Structure** - Evaluates organization, headers, and flow -3. **Check Content** - Reviews clarity, completeness, and conciseness -4. **Identify Issues** - Finds redundancy, verbosity, and missing sections -5. **Detect Active Plugins** - Identifies marketplace plugins enabled in the project -6. **Check Plugin Integration** - Verifies CLAUDE.md references active plugins -7. **Generate Report** - Provides scored assessment with recommendations +Display: `CONFIG-MAINTAINER - CLAUDE.md Analysis` ## Usage @@ -34,202 +23,27 @@ Then proceed with the analysis. /config-analyze ``` -Or invoke the maintainer agent directly: +## Workflow -``` -Analyze the CLAUDE.md file in this project -``` +1. Locate and parse CLAUDE.md +2. Evaluate structure, clarity, completeness, conciseness +3. Find redundancy, verbosity, missing sections +4. Detect active marketplace plugins +5. Verify plugin integration in CLAUDE.md +6. Generate scored report with recommendations -## Analysis Criteria +## Scoring (100 points) -### Structure (25 points) -- Logical section ordering -- Clear header hierarchy -- Easy navigation -- Appropriate grouping - -### Clarity (25 points) -- Clear instructions -- Good examples -- Unambiguous language -- Appropriate detail level - -### Completeness (25 points) -- Project overview present -- Quick start commands documented -- Critical rules highlighted -- Key workflows covered -- **Pre-Change Protocol section present** (MANDATORY - see below) - -### Conciseness (25 points) -- No unnecessary repetition -- Efficient information density -- Appropriate length for project size -- No generic filler content - -## Pre-Change Protocol Check (MANDATORY) - -**This check is CRITICAL.** The Pre-Change Protocol section ensures Claude performs comprehensive dependency analysis before making any code changes, preventing missed references and incomplete updates. - -### What to Check - -Search CLAUDE.md for: -- Section header containing "Pre-Change" or "Before Any Code Change" -- References to `grep -rn` or impact search -- Checklist with "Files That Will Be Affected" -- Requirement for user verification before proceeding - -### If Missing - -**Flag as HIGH PRIORITY issue:** - -``` -1. [HIGH] Missing Pre-Change Protocol section - CLAUDE.md lacks mandatory dependency-check protocol. - Impact: Claude may miss file references when making changes, - leading to broken dependencies and incomplete updates. - - Recommendation: Add Pre-Change Protocol section immediately. - This is the #1 cause of cascading bugs from incomplete changes. -``` - -### Required Section Content - -The Pre-Change Protocol section must include: -1. Requirement to run grep search and show results -2. List of files that will be affected -3. List of files searched but not changed (with reasoning) -4. Documentation that references the change target -5. User verification checkpoint before proceeding -6. Post-change verification step - -## Plugin Integration Analysis - -After the content analysis, the command detects and analyzes marketplace plugin integration: - -### Detection Method - -1. **Read `.claude/settings.local.json`** - Check for enabled MCP servers -2. **Map MCP servers to plugins** - Use marketplace registry to identify active plugins: - - `gitea` → projman - - `netbox` → cmdb-assistant -3. **Check for hooks** - Identify hook-based plugins (project-hygiene) -4. **Scan CLAUDE.md** - Look for plugin integration content - -### Plugin Coverage Scoring - -For each detected plugin, verify CLAUDE.md contains: -- Plugin section header or mention -- Available commands documentation -- MCP tools reference (if applicable) -- Usage guidelines - -Coverage is reported as percentage: `(plugins referenced / plugins detected) * 100` - -## Expected Output - -``` -CLAUDE.md Analysis Report -========================= - -File: /path/to/project/CLAUDE.md -Lines: 245 -Last Modified: 2025-01-18 - -Overall Score: 72/100 - -Category Scores: -- Structure: 20/25 (Good) -- Clarity: 18/25 (Good) -- Completeness: 22/25 (Excellent) -- Conciseness: 12/25 (Needs Work) - -Strengths: -+ Clear project overview with good context -+ Critical rules prominently displayed -+ Comprehensive coverage of workflows - -Issues Found: - -1. [HIGH] Verbose explanations (lines 45-78) - Section "Running Tests" has 34 lines that could be 8 lines. - Impact: Harder to scan, important info buried - -2. [MEDIUM] Duplicate content (lines 102-115, 189-200) - Same git workflow documented twice. - Impact: Maintenance burden, inconsistency risk - -3. [MEDIUM] Missing Quick Start section - No clear "how to get started" instructions. - Impact: Slower onboarding for Claude - -4. [LOW] Inconsistent header formatting - Mix of "## Title" and "## Title:" styles. - Impact: Minor readability issue - -Recommendations: -1. Add Quick Start section at top (priority: high) -2. Condense Testing section to essentials (priority: high) -3. Remove duplicate git workflow (priority: medium) -4. Standardize header formatting (priority: low) - -Estimated improvement: 15-20 points after changes - ---- - -Plugin Integration Analysis -=========================== - -Detected Active Plugins: - ✓ projman (via gitea MCP server) - ✓ cmdb-assistant (via netbox MCP server) - ✓ project-hygiene (via PostToolUse hook) - -Plugin Coverage: 33% (1/3 plugins referenced) - - ✓ projman - Referenced in CLAUDE.md - ✗ cmdb-assistant - NOT referenced - ✗ project-hygiene - NOT referenced - -Missing Integration Content: - -1. cmdb-assistant - Add infrastructure management commands and NetBox MCP tools reference. - -2. project-hygiene - Add cleanup hook documentation and configuration options. - ---- - -Would you like me to: -[1] Implement all content recommendations -[2] Add missing plugin integrations to CLAUDE.md -[3] Do both (recommended) -[4] Show preview of changes first -``` - -## When to Use - -Run `/config-analyze` when: -- Setting up a new project with existing CLAUDE.md -- CLAUDE.md feels too long or hard to use -- Claude seems to miss instructions -- Before major project changes -- Periodic maintenance (quarterly) -- After installing new marketplace plugins -- When Claude doesn't seem to use available plugin tools +| Category | Points | +|----------|--------| +| Structure | 25 | +| Clarity | 25 | +| Completeness | 25 | +| Conciseness | 25 | ## Follow-Up Actions -After analysis, you can: -- Run `/config-optimize` to automatically improve the file -- Manually address specific issues -- Request detailed recommendations for any section -- Compare with best practice templates - -## Tips - -- Run analysis after significant project changes -- Address HIGH priority issues first -- Keep scores above 70/100 for best results -- Re-analyze after making changes to verify improvement +1. Implement content recommendations +2. Add missing plugin integrations +3. Do both (recommended) +4. Show preview first diff --git a/plugins/claude-config-maintainer/commands/config-diff.md b/plugins/claude-config-maintainer/commands/config-diff.md index c2372ae..cd09750 100644 --- a/plugins/claude-config-maintainer/commands/config-diff.md +++ b/plugins/claude-config-maintainer/commands/config-diff.md @@ -4,248 +4,45 @@ description: Show diff between current CLAUDE.md and last commit # Compare CLAUDE.md Changes -This command shows differences between your current CLAUDE.md file and previous versions, helping track configuration drift and review changes before committing. +Show differences between CLAUDE.md versions to track configuration drift. + +## Skills to Load + +- skills/visual-header.md +- skills/diff-analysis.md ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ ⚙️ CONFIG-MAINTAINER · CLAUDE.md Diff │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the diff. - -## What This Command Does - -1. **Detect CLAUDE.md Location** - Finds the project's CLAUDE.md file -2. **Compare Versions** - Shows diff against last commit or specified revision -3. **Highlight Sections** - Groups changes by affected sections -4. **Summarize Impact** - Explains what the changes mean for Claude's behavior +Display: `CONFIG-MAINTAINER - CLAUDE.md Diff` ## Usage ``` -/config-diff +/config-diff # Working vs last commit +/config-diff --commit=abc1234 # Working vs specific commit +/config-diff --from=v1.0 --to=v2.0 # Compare two commits +/config-diff --section="Critical Rules" # Specific section only ``` -Compare against a specific commit: +## Workflow -``` -/config-diff --commit=abc1234 -/config-diff --commit=HEAD~3 -``` - -Compare two specific commits: - -``` -/config-diff --from=abc1234 --to=def5678 -``` - -Show only specific sections: - -``` -/config-diff --section="Critical Rules" -/config-diff --section="Quick Start" -``` - -## Comparison Modes - -### Default: Working vs Last Commit -Shows uncommitted changes to CLAUDE.md: -``` -/config-diff -``` - -### Working vs Specific Commit -Shows changes since a specific point: -``` -/config-diff --commit=v1.0.0 -``` - -### Commit to Commit -Shows changes between two historical versions: -``` -/config-diff --from=v1.0.0 --to=v2.0.0 -``` - -### Branch Comparison -Shows CLAUDE.md differences between branches: -``` -/config-diff --branch=main -/config-diff --from=feature-branch --to=main -``` - -## Expected Output - -``` -CLAUDE.md Diff Report -===================== - -File: /path/to/project/CLAUDE.md -Comparing: Working copy vs HEAD (last commit) -Commit: abc1234 "Update build commands" (2 days ago) - -Summary: -- Lines added: 12 -- Lines removed: 5 -- Net change: +7 lines -- Sections affected: 3 - -Section Changes: ----------------- - -## Quick Start [MODIFIED] - - Added new environment variable requirement - - Updated test command with coverage flag - -## Critical Rules [ADDED CONTENT] - + New rule: "Never modify database migrations directly" - -## Architecture [UNCHANGED] - -## Common Operations [MODIFIED] - - Removed deprecated deployment command - - Added new Docker workflow - -Detailed Diff: --------------- - ---- CLAUDE.md (HEAD) -+++ CLAUDE.md (working) - -@@ -15,7 +15,10 @@ - ## Quick Start - - ```bash -+export DATABASE_URL=postgres://... # Required - pip install -r requirements.txt --pytest -+pytest --cov=src # Run with coverage - uvicorn main:app --reload - ``` - -@@ -45,6 +48,7 @@ - ## Critical Rules - - - Never modify `.env` files directly -+- Never modify database migrations directly - - Always run tests before committing - -Behavioral Impact: ------------------- - -These changes will affect Claude's behavior: - -1. [NEW REQUIREMENT] Claude will now export DATABASE_URL before running -2. [MODIFIED] Test command now includes coverage reporting -3. [NEW RULE] Claude will avoid direct migration modifications - -Review: Do these changes reflect your intended configuration? -``` - -## Section-Focused View - -When using `--section`, output focuses on specific areas: - -``` -/config-diff --section="Critical Rules" - -CLAUDE.md Section Diff: Critical Rules -====================================== - ---- HEAD -+++ Working - - ## Critical Rules - - - Never modify `.env` files directly -+- Never modify database migrations directly -+- Always use type hints in Python code - - Always run tests before committing --- Keep functions under 50 lines - -Changes: - + 2 rules added - - 1 rule removed - -Impact: Claude will follow 2 new constraints and no longer enforce -the 50-line function limit. -``` +1. Find project's CLAUDE.md file +2. Show diff against target revision +3. Group changes by affected sections +4. Explain behavioral implications ## Options | Option | Description | |--------|-------------| -| `--commit=REF` | Compare working copy against specific commit/tag | -| `--from=REF` | Starting point for comparison | -| `--to=REF` | Ending point for comparison (default: HEAD) | -| `--branch=NAME` | Compare against branch tip | -| `--section=NAME` | Show only changes to specific section | -| `--stat` | Show only statistics, no detailed diff | -| `--no-color` | Disable colored output | -| `--context=N` | Lines of context around changes (default: 3) | - -## Understanding the Output - -### Change Indicators - -| Symbol | Meaning | -|--------|---------| -| `+` | Line added | -| `-` | Line removed | -| `@@` | Location marker showing line numbers | -| `[MODIFIED]` | Section has changes | -| `[ADDED]` | New section created | -| `[REMOVED]` | Section deleted | -| `[UNCHANGED]` | No changes to section | - -### Impact Categories - -- **NEW REQUIREMENT** - Claude will now need to do something new -- **REMOVED REQUIREMENT** - Claude no longer needs to do something -- **MODIFIED** - Existing behavior changed -- **NEW RULE** - New constraint added -- **RELAXED RULE** - Constraint removed or softened +| `--commit=REF` | Compare against specific commit | +| `--from=REF` | Starting point | +| `--to=REF` | Ending point (default: HEAD) | +| `--section=NAME` | Show only specific section | +| `--stat` | Statistics only | ## When to Use -Run `/config-diff` when: - Before committing CLAUDE.md changes -- Reviewing what changed after pulling updates -- Debugging unexpected Claude behavior -- Auditing configuration changes over time -- Comparing configurations across branches - -## Integration with Other Commands - -| Workflow | Commands | -|----------|----------| -| Review before commit | `/config-diff` then `git commit` | -| After optimization | `/config-optimize` then `/config-diff` | -| Audit history | `/config-diff --from=v1.0.0 --to=HEAD` | -| Branch comparison | `/config-diff --branch=main` | - -## Tips - -1. **Review before committing** - Always check what changed -2. **Track behavioral changes** - Focus on rules and requirements sections -3. **Use section filtering** - Large files benefit from focused diffs -4. **Compare across releases** - Use tags to track major changes -5. **Check after merges** - Ensure CLAUDE.md didn't get conflict artifacts - -## Troubleshooting - -### "No changes detected" -- CLAUDE.md matches the comparison target -- Check if you're comparing the right commits - -### "File not found in commit" -- CLAUDE.md didn't exist at that commit -- Use `git log -- CLAUDE.md` to find when it was created - -### "Not a git repository" -- This command requires git history -- Initialize git or use file backup comparison instead +- Reviewing changes after pull +- Debugging unexpected behavior diff --git a/plugins/claude-config-maintainer/commands/config-lint.md b/plugins/claude-config-maintainer/commands/config-lint.md index 232efab..bfc8fe8 100644 --- a/plugins/claude-config-maintainer/commands/config-lint.md +++ b/plugins/claude-config-maintainer/commands/config-lint.md @@ -4,343 +4,45 @@ description: Lint CLAUDE.md for common anti-patterns and best practices # Lint CLAUDE.md -This command checks your CLAUDE.md file against best practices and detects common anti-patterns that can cause issues with Claude Code. +Check CLAUDE.md against best practices and detect common anti-patterns. + +## Skills to Load + +- skills/visual-header.md +- skills/lint-rules.md ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ ⚙️ CONFIG-MAINTAINER · CLAUDE.md Lint │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the linting. - -## What This Command Does - -1. **Parse Structure** - Validates markdown structure and hierarchy -2. **Check Security** - Detects hardcoded paths, secrets, and sensitive data -3. **Validate Content** - Identifies anti-patterns and problematic instructions -4. **Verify Format** - Ensures consistent formatting and style -5. **Generate Report** - Provides actionable findings with fix suggestions +Display: `CONFIG-MAINTAINER - CLAUDE.md Lint` ## Usage ``` -/config-lint +/config-lint # Full lint +/config-lint --fix # Auto-fix issues +/config-lint --rules=security # Check specific category ``` -Lint with auto-fix: +## Workflow -``` -/config-lint --fix -``` - -Check specific rules only: - -``` -/config-lint --rules=security,structure -``` - -## Linting Rules - -### Security Rules (SEC) - -| Rule | Description | Severity | -|------|-------------|----------| -| SEC001 | Hardcoded absolute paths | Warning | -| SEC002 | Potential secrets/API keys | Error | -| SEC003 | Hardcoded IP addresses | Warning | -| SEC004 | Exposed credentials patterns | Error | -| SEC005 | Hardcoded URLs with tokens | Error | -| SEC006 | Environment variable values (not names) | Warning | - -### Structure Rules (STR) - -| Rule | Description | Severity | -|------|-------------|----------| -| STR001 | Missing required sections | Error | -| STR002 | Invalid header hierarchy (h3 before h2) | Warning | -| STR003 | Orphaned content (text before first header) | Info | -| STR004 | Excessive nesting depth (>4 levels) | Warning | -| STR005 | Empty sections | Warning | -| STR006 | Missing section content | Warning | - -### Content Rules (CNT) - -| Rule | Description | Severity | -|------|-------------|----------| -| CNT001 | Contradictory instructions | Error | -| CNT002 | Vague or ambiguous rules | Warning | -| CNT003 | Overly long sections (>100 lines) | Info | -| CNT004 | Duplicate content | Warning | -| CNT005 | TODO/FIXME in production config | Warning | -| CNT006 | Outdated version references | Info | -| CNT007 | Broken internal links | Warning | - -### Format Rules (FMT) - -| Rule | Description | Severity | -|------|-------------|----------| -| FMT001 | Inconsistent header styles | Info | -| FMT002 | Inconsistent list markers | Info | -| FMT003 | Missing code block language | Info | -| FMT004 | Trailing whitespace | Info | -| FMT005 | Missing blank lines around headers | Info | -| FMT006 | Inconsistent indentation | Info | - -### Best Practice Rules (BPR) - -| Rule | Description | Severity | -|------|-------------|----------| -| BPR001 | No Quick Start section | Warning | -| BPR002 | No Critical Rules section | Warning | -| BPR003 | Instructions without examples | Info | -| BPR004 | Commands without explanation | Info | -| BPR005 | Rules without rationale | Info | -| BPR006 | Missing plugin integration docs | Info | - -## Expected Output - -``` -CLAUDE.md Lint Report -===================== - -File: /path/to/project/CLAUDE.md -Rules checked: 25 -Time: 0.3s - -Summary: - Errors: 2 - Warnings: 5 - Info: 3 - -Findings: ---------- - -[ERROR] SEC002: Potential secret detected (line 45) - │ api_key = "sk-1234567890abcdef" - │ ^^^^^^^^^^^^^^^^^^^^^^ - └─ Hardcoded API key found. Use environment variable reference instead. - - Suggested fix: - - api_key = "sk-1234567890abcdef" - + api_key = $OPENAI_API_KEY # Set in environment - -[ERROR] CNT001: Contradictory instructions (lines 23, 67) - │ Line 23: "Always run tests before committing" - │ Line 67: "Skip tests for documentation-only changes" - │ - └─ These rules conflict. Clarify the exception explicitly. - - Suggested fix: - + "Always run tests before committing, except for documentation-only - + changes (files in docs/ directory)" - -[WARNING] SEC001: Hardcoded absolute path (line 12) - │ Database location: /home/user/data/myapp.db - │ ^^^^^^^^^^^^^^^^^^^^^^^^ - └─ Absolute paths break portability. Use relative or variable. - - Suggested fix: - - Database location: /home/user/data/myapp.db - + Database location: ./data/myapp.db # Or $DATA_DIR/myapp.db - -[WARNING] STR002: Invalid header hierarchy (line 34) - │ ### Subsection - │ (no preceding ## header) - │ - └─ H3 header without parent H2. Add H2 or promote to H2. - -[WARNING] CNT004: Duplicate content (lines 45-52, 89-96) - │ Same git workflow documented twice - │ - └─ Remove duplicate or consolidate into single section. - -[WARNING] STR005: Empty section (line 78) - │ ## Troubleshooting - │ (no content) - │ - └─ Add content or remove empty section. - -[WARNING] BPR002: No Critical Rules section - │ Missing "Critical Rules" or "Important Rules" section - │ - └─ Add a section highlighting must-follow rules for Claude. - -[INFO] FMT003: Missing code block language (line 56) - │ ``` - │ npm install - │ ``` - │ - └─ Specify language for syntax highlighting: ```bash - -[INFO] CNT003: Overly long section (lines 100-215) - │ "Architecture" section is 115 lines - │ - └─ Consider breaking into subsections or condensing. - -[INFO] FMT001: Inconsistent header styles - │ Line 10: "## Quick Start" - │ Line 25: "## Architecture:" - │ (colon suffix inconsistent) - │ - └─ Standardize header format throughout document. - ---- - -Auto-fixable: 4 issues (run with --fix) -Manual review required: 6 issues - -Run `/config-lint --fix` to apply automatic fixes. -``` +1. Parse markdown structure and hierarchy +2. Check for hardcoded paths, secrets, sensitive data +3. Identify content anti-patterns +4. Verify consistent formatting +5. Generate report with fix suggestions ## Options | Option | Description | |--------|-------------| -| `--fix` | Automatically fix auto-fixable issues | -| `--rules=LIST` | Check only specified rule categories | -| `--ignore=LIST` | Skip specified rules (e.g., `--ignore=FMT001,FMT002`) | -| `--severity=LEVEL` | Show only issues at or above level (error/warning/info) | -| `--format=FORMAT` | Output format: `text` (default), `json`, `sarif` | -| `--config=FILE` | Use custom lint configuration | +| `--fix` | Auto-fix issues | +| `--rules=LIST` | Check specific categories | +| `--ignore=LIST` | Skip specified rules | +| `--severity=LEVEL` | Filter by severity | | `--strict` | Treat warnings as errors | -## Rule Categories - -Use `--rules` to focus on specific areas: - -``` -/config-lint --rules=security # Only security checks -/config-lint --rules=structure # Only structure checks -/config-lint --rules=security,content # Multiple categories -``` - -Available categories: -- `security` - SEC rules -- `structure` - STR rules -- `content` - CNT rules -- `format` - FMT rules -- `bestpractice` - BPR rules - -## Custom Configuration - -Create `.claude-lint.json` in project root: - -```json -{ - "rules": { - "SEC001": "warning", - "FMT001": "off", - "CNT003": { - "severity": "warning", - "maxLines": 150 - } - }, - "ignore": [ - "FMT*" - ], - "requiredSections": [ - "Quick Start", - "Critical Rules", - "Project Overview" - ] -} -``` - -## Anti-Pattern Examples - -### Hardcoded Secrets (SEC002) -```markdown -# BAD -API_KEY=sk-1234567890abcdef - -# GOOD -API_KEY=$OPENAI_API_KEY # Set via environment -``` - -### Hardcoded Paths (SEC001) -```markdown -# BAD -Config file: /home/john/projects/myapp/config.yml - -# GOOD -Config file: ./config.yml -Config file: $PROJECT_ROOT/config.yml -``` - -### Contradictory Rules (CNT001) -```markdown -# BAD -- Always use TypeScript -- JavaScript files are acceptable for scripts - -# GOOD -- Always use TypeScript for source code -- JavaScript (.js) is acceptable only for config files and scripts -``` - -### Vague Instructions (CNT002) -```markdown -# BAD -- Be careful with the database - -# GOOD -- Never run DELETE without WHERE clause -- Always backup before migrations -``` - -### Invalid Hierarchy (STR002) -```markdown -# BAD -# Main Title -### Skipped Level - -# GOOD -# Main Title -## Section -### Subsection -``` - ## When to Use -Run `/config-lint` when: - Before committing CLAUDE.md changes -- During code review for CLAUDE.md modifications -- Setting up CI/CD checks for configuration files -- After major edits to catch introduced issues -- Periodically as maintenance check - -## Integration with CI/CD - -Add to your CI pipeline: - -```yaml -# GitHub Actions example -- name: Lint CLAUDE.md - run: claude /config-lint --strict --format=sarif > lint-results.sarif - -- name: Upload SARIF - uses: github/codeql-action/upload-sarif@v2 - with: - sarif_file: lint-results.sarif -``` - -## Tips - -1. **Start with errors** - Fix errors before warnings -2. **Use --fix carefully** - Review auto-fixes before committing -3. **Configure per-project** - Different projects have different needs -4. **Integrate in CI** - Catch issues before they reach main -5. **Review periodically** - Run lint check monthly as maintenance - -## Related Commands - -| Command | Relationship | -|---------|--------------| -| `/config-analyze` | Deeper content analysis (complements lint) | -| `/config-optimize` | Applies fixes and improvements | -| `/config-diff` | Shows what changed (run lint before commit) | +- During code review +- Periodically as maintenance diff --git a/plugins/claude-config-maintainer/commands/init.md b/plugins/claude-config-maintainer/commands/init.md index 43c2eb1..1396d43 100644 --- a/plugins/claude-config-maintainer/commands/init.md +++ b/plugins/claude-config-maintainer/commands/init.md @@ -4,255 +4,46 @@ description: Initialize a new CLAUDE.md file for a project # Initialize CLAUDE.md -This command creates a new CLAUDE.md file tailored to your project, gathering context and generating appropriate content. +Create a new CLAUDE.md file tailored to your project. + +## Skills to Load + +- skills/visual-header.md +- skills/claude-md-structure.md +- skills/pre-change-protocol.md ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ ⚙️ CONFIG-MAINTAINER · CLAUDE.md Initialization │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the initialization. - -## What This Command Does - -1. **Gather Context** - Analyzes project structure and asks clarifying questions -2. **Detect Stack** - Identifies technologies, frameworks, and tools -3. **Generate Content** - Creates tailored CLAUDE.md sections -4. **Review & Refine** - Allows customization before saving -5. **Save File** - Creates the CLAUDE.md in project root +Display: `CONFIG-MAINTAINER - CLAUDE.md Initialization` ## Usage ``` -/config-init +/config-init # Interactive +/config-init --minimal # Minimal version +/config-init --comprehensive # Detailed version ``` -Or with options: +## Workflow -``` -/config-init --template=api # Use API project template -/config-init --minimal # Create minimal version -/config-init --comprehensive # Create detailed version -``` - -## Initialization Workflow - -``` -CLAUDE.md Initialization -======================== - -Step 1: Project Analysis ------------------------- -Scanning project structure... - -Detected: -- Language: Python 3.11 -- Framework: FastAPI -- Package Manager: pip (requirements.txt found) -- Testing: pytest -- Docker: Yes (Dockerfile found) -- Git: Yes (.git directory) - -Step 2: Clarifying Questions ----------------------------- - -1. Project Description: - What does this project do? (1-2 sentences) - > [User provides description] - -2. Build/Run Commands: - Detected commands - are these correct? - - Install: pip install -r requirements.txt - - Test: pytest - - Run: uvicorn main:app --reload - [Y/n/edit] - -3. Critical Rules: - Any rules Claude MUST follow? - Examples: "Never modify migrations", "Always use type hints" - > [User provides rules] - -4. Sensitive Areas: - Any files/directories Claude should be careful with? - > [User provides or skips] - -Step 3: Generate CLAUDE.md --------------------------- - -Generating content based on: -- Project type: FastAPI web API -- Detected technologies -- Your provided context - -Preview: - ---- -# CLAUDE.md - -## Project Overview -[Generated description] - -## Quick Start - -```bash -pip install -r requirements.txt # Install dependencies -pytest # Run tests -uvicorn main:app --reload # Start dev server -``` - -## Architecture -[Generated based on structure] - -## Critical Rules -[Your provided rules] - -## File Structure -[Generated from analysis] ---- - -Save this CLAUDE.md? [Y/n/edit] - -Step 4: Complete ----------------- - -CLAUDE.md created successfully! - -Location: /path/to/project/CLAUDE.md -Lines: 87 -Score: 85/100 (following best practices) - -Recommendations: -- Run /config-analyze periodically to maintain quality -- Update when adding major features -- Add troubleshooting section as issues are discovered -``` +1. Analyze project structure, ask clarifying questions +2. Detect technologies, frameworks, tools +3. Generate tailored CLAUDE.md sections +4. Allow review and customization +5. Save file in project root ## Templates -### Minimal Template -For small projects or when starting fresh: -- Project Overview (required) -- Quick Start (required) -- Critical Rules (required) -- **Pre-Change Protocol (required)** +| Template | Sections | +|----------|----------| +| Minimal | Overview, Quick Start, Critical Rules, Pre-Change Protocol | +| Standard | + Architecture, Common Operations, File Structure | +| Comprehensive | + Troubleshooting, Integration Points, Workflow | -### Standard Template (default) -For typical projects: -- Project Overview -- Quick Start -- Architecture -- Critical Rules -- **Pre-Change Protocol** -- Common Operations -- File Structure - -### Comprehensive Template -For large or complex projects: -- All standard sections plus: -- Detailed Architecture -- **Pre-Change Protocol** -- Troubleshooting -- Integration Points -- Development Workflow -- Deployment Notes - -### Pre-Change Protocol Section (MANDATORY in ALL templates) - -**This section MUST be included in every generated CLAUDE.md:** - -```markdown -## ⛔ MANDATORY: Before Any Code Change - -**Claude MUST show this checklist BEFORE editing any file:** - -### 1. Impact Search Results -Run and show output of: -\`\`\`bash -grep -rn "PATTERN" --include="*.sh" --include="*.md" --include="*.json" --include="*.py" | grep -v ".git" -\`\`\` - -### 2. Files That Will Be Affected -Numbered list of every file to be modified, with the specific change for each. - -### 3. Files Searched But Not Changed (and why) -Proof that related files were checked and determined unchanged. - -### 4. Documentation That References This -List of docs that mention this feature/script/function. - -**User verifies this list before Claude proceeds. If Claude skips this, stop immediately.** - -### After Changes -Run the same grep and show results proving no references remain unaddressed. -``` - -**Rationale:** This protocol prevents incomplete changes where Claude modifies some files but misses others that reference the same code, causing cascading bugs. - -## Auto-Detection - -The command automatically detects: - -| What | How | -|------|-----| -| Language | File extensions, config files | -| Framework | package.json, requirements.txt, etc. | -| Build system | Makefile, package.json scripts, etc. | -| Testing | pytest.ini, jest.config, etc. | -| Docker | Dockerfile, docker-compose.yml | -| Database | Connection strings, ORM configs | - -## Customization - -After generation, you can: -- Edit any section before saving -- Add additional sections -- Remove unnecessary sections -- Adjust detail level -- Add project-specific content +**Note:** Pre-Change Protocol is MANDATORY in all templates. ## When to Use -Run `/config-init` when: - Starting a new project - Project lacks CLAUDE.md -- Existing CLAUDE.md is outdated/poor quality -- Taking over an unfamiliar project - -## Tips - -1. **Provide accurate description** - This shapes the whole file -2. **Include critical rules** - What must Claude never do? -3. **Review generated content** - Auto-detection isn't perfect -4. **Start minimal, grow as needed** - Add sections when required -5. **Keep it current** - Update when project changes significantly - -## Examples - -### For a CLI Tool -``` -/config-init - -> Description: CLI tool for managing cloud infrastructure -> Critical rules: Never delete resources without confirmation, always show dry-run first -``` - -### For a Web App -``` -/config-init - -> Description: E-commerce platform with React frontend and Node.js backend -> Critical rules: Never expose API keys, always validate user input, follow the existing component patterns -``` - -### For a Library -``` -/config-init --template=minimal - -> Description: Python library for parsing log files -> Critical rules: Maintain backward compatibility, all public functions need docstrings -``` +- Taking over unfamiliar project diff --git a/plugins/claude-config-maintainer/commands/optimize.md b/plugins/claude-config-maintainer/commands/optimize.md index e02f541..fef2ac7 100644 --- a/plugins/claude-config-maintainer/commands/optimize.md +++ b/plugins/claude-config-maintainer/commands/optimize.md @@ -4,231 +4,47 @@ description: Optimize CLAUDE.md structure and content # Optimize CLAUDE.md -This command automatically optimizes your project's CLAUDE.md file based on best practices and identified issues. +Automatically optimize CLAUDE.md based on best practices. + +## Skills to Load + +- skills/visual-header.md +- skills/optimization-patterns.md +- skills/pre-change-protocol.md +- skills/claude-md-structure.md ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ ⚙️ CONFIG-MAINTAINER · CLAUDE.md Optimization │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the optimization. - -## What This Command Does - -1. **Analyze Current File** - Identifies all optimization opportunities -2. **Plan Changes** - Determines what to restructure, condense, or add -3. **Show Preview** - Displays before/after comparison -4. **Apply Changes** - Updates the file with your approval -5. **Verify Results** - Confirms improvements achieved +Display: `CONFIG-MAINTAINER - CLAUDE.md Optimization` ## Usage ``` -/config-optimize +/config-optimize # Full optimization +/config-optimize --condense # Reduce verbosity +/config-optimize --dry-run # Preview only ``` -Or specify specific optimizations: +## Workflow -``` -/config-optimize --condense # Focus on reducing verbosity -/config-optimize --restructure # Focus on reorganization -/config-optimize --add-missing # Focus on adding missing sections -``` - -## Optimization Actions - -### Restructure -- Reorder sections by importance -- Group related content together -- Improve header hierarchy -- Add navigation aids - -### Condense -- Remove redundant explanations -- Convert verbose text to bullet points -- Eliminate duplicate content -- Shorten overly detailed sections - -### Enhance -- Add missing essential sections -- **Add Pre-Change Protocol if missing (HIGH PRIORITY)** -- Improve unclear instructions -- Add helpful examples -- Highlight critical rules - -### Format -- Standardize header styles -- Fix code block formatting -- Align list formatting -- Improve table layouts - -## Expected Output - -``` -CLAUDE.md Optimization -====================== - -Current Analysis: -- Score: 72/100 -- Lines: 245 -- Issues: 4 - -Planned Optimizations: - -1. ADD: Quick Start section (new, ~15 lines) - + Build command - + Test command - + Run command - -2. CONDENSE: Testing section (34 → 8 lines) - Before: Verbose explanation with redundant setup info - After: Concise command reference with comments - -3. REMOVE: Duplicate git workflow (lines 189-200) - Keeping: Original at lines 102-115 - -4. FORMAT: Standardize headers - Changing 12 headers from "## Title:" to "## Title" - -Preview Changes? [Y/n] y - ---- CLAUDE.md (before) -+++ CLAUDE.md (after) - -@@ -1,5 +1,20 @@ - # CLAUDE.md - -+## Quick Start -+ -+```bash -+# Install dependencies -+pip install -r requirements.txt -+ -+# Run tests -+pytest -+ -+# Start development server -+python manage.py runserver -+``` -+ - ## Project Overview - ... - -[Full diff shown] - -Apply these changes? [Y/n] y - -Optimization Complete! -- Previous score: 72/100 -- New score: 89/100 -- Lines reduced: 245 → 198 (-19%) -- Issues resolved: 4/4 - -Backup saved to: .claude/backups/CLAUDE.md.2025-01-18 -``` - -## Safety Features - -### Backup Creation -- Automatic backup before changes -- Stored in `.claude/backups/` -- Easy restoration if needed - -### Preview Mode -- All changes shown before applying -- Diff format for easy review -- Option to approve/reject - -### Selective Application -- Can apply individual changes -- Skip specific optimizations -- Iterative refinement +1. Identify optimization opportunities +2. Plan restructure, condense, or add actions +3. Show before/after preview +4. Apply changes with approval +5. Verify improvements ## Options | Option | Description | |--------|-------------| -| `--dry-run` | Show changes without applying | -| `--no-backup` | Skip backup creation | +| `--dry-run` | Preview without applying | +| `--no-backup` | Skip backup | | `--aggressive` | Maximum condensation | -| `--preserve-comments` | Keep all existing comments | -| `--section=NAME` | Optimize specific section only | +| `--section=NAME` | Optimize specific section | -## Pre-Change Protocol (Mandatory Addition) +**Priority:** Add Pre-Change Protocol if missing. -**If CLAUDE.md is missing the Pre-Change Protocol section, optimization MUST add it.** +## Safety -This is the highest priority enhancement because it prevents cascading bugs from incomplete code changes. - -### Detection - -Search CLAUDE.md for: -- "Pre-Change" or "Before Any Code Change" in headers -- References to impact search or grep verification -- User verification checkpoint - -### If Missing - -Add this section (position: after Critical Rules, before Common Operations): - -```markdown -## ⛔ MANDATORY: Before Any Code Change - -**Claude MUST show this checklist BEFORE editing any file:** - -### 1. Impact Search Results -Run and show output of: -\`\`\`bash -grep -rn "PATTERN" --include="*.sh" --include="*.md" --include="*.json" --include="*.py" | grep -v ".git" -\`\`\` - -### 2. Files That Will Be Affected -Numbered list of every file to be modified, with the specific change for each. - -### 3. Files Searched But Not Changed (and why) -Proof that related files were checked and determined unchanged. - -### 4. Documentation That References This -List of docs that mention this feature/script/function. - -**User verifies this list before Claude proceeds. If Claude skips this, stop immediately.** - -### After Changes -Run the same grep and show results proving no references remain unaddressed. -``` - -## When to Use - -Run `/config-optimize` when: -- Analysis shows score below 70 -- File has grown too long -- Structure needs reorganization -- Missing critical sections -- After major refactoring - -## Best Practices - -1. **Run analysis first** - Understand current state -2. **Review preview carefully** - Ensure nothing important lost -3. **Test after changes** - Verify Claude follows instructions -4. **Keep backups** - Restore if issues arise -5. **Iterate** - Multiple small optimizations beat one large one - -## Rollback - -If optimization causes issues: - -```bash -# Restore from backup -cp .claude/backups/CLAUDE.md.TIMESTAMP ./CLAUDE.md -``` - -Or ask: -``` -Restore CLAUDE.md from the most recent backup -``` +- Auto backup to `.claude/backups/` +- Preview before applying diff --git a/plugins/claude-config-maintainer/skills/analysis-workflow.md b/plugins/claude-config-maintainer/skills/analysis-workflow.md new file mode 100644 index 0000000..3420d0d --- /dev/null +++ b/plugins/claude-config-maintainer/skills/analysis-workflow.md @@ -0,0 +1,112 @@ +# CLAUDE.md Analysis Workflow + +This skill defines the workflow for analyzing CLAUDE.md files. + +## Analysis Steps + +1. **Locate File** - Find CLAUDE.md in project root +2. **Parse Structure** - Extract headers and sections +3. **Evaluate Content** - Score against criteria +4. **Detect Plugins** - Identify active marketplace plugins +5. **Check Integration** - Verify plugin references +6. **Generate Report** - Provide scored assessment + +## Content Analysis + +### What to Check + +| Area | Check For | +|------|-----------| +| Structure | Header hierarchy, section ordering, grouping | +| Clarity | Clear instructions, examples, unambiguous language | +| Completeness | Required sections present, workflows documented | +| Conciseness | No redundancy, efficient density, appropriate length | + +### Required Sections Check + +1. Project Overview - present? +2. Quick Start - present with commands? +3. Critical Rules - present? +4. **Pre-Change Protocol** - present? (HIGH PRIORITY if missing) + +## Plugin Integration Analysis + +### Detection Method + +1. Read `.claude/settings.local.json` for enabled MCP servers +2. Map MCP servers to plugins: + - `gitea` -> projman + - `netbox` -> cmdb-assistant +3. Check for hook-based plugins (project-hygiene) +4. Scan CLAUDE.md for plugin references + +### Coverage Scoring + +For each detected plugin, verify CLAUDE.md contains: +- Plugin section header or mention +- Available commands documentation +- MCP tools reference (if applicable) +- Usage guidelines + +Coverage = (plugins referenced / plugins detected) * 100% + +## Report Format + +``` +CLAUDE.md Analysis Report +========================= + +File: /path/to/project/CLAUDE.md +Lines: N +Last Modified: YYYY-MM-DD + +Overall Score: NN/100 + +Category Scores: +- Structure: NN/25 (Rating) +- Clarity: NN/25 (Rating) +- Completeness: NN/25 (Rating) +- Conciseness: NN/25 (Rating) + +Strengths: ++ [Positive finding] + +Issues Found: + +N. [SEVERITY] Issue description (location) + Context explaining the problem. + Impact: What happens if not fixed. + +Recommendations: +N. Action to take (priority: high/medium/low) + +--- + +Plugin Integration Analysis +=========================== + +Detected Active Plugins: + [check] plugin-name (via detection method) + +Plugin Coverage: NN% (N/N plugins referenced) + +Missing Integration Content: +N. plugin-name + What to add. +``` + +## Issue Severity + +| Level | When to Use | +|-------|-------------| +| HIGH | Missing mandatory sections, security issues | +| MEDIUM | Missing recommended content, duplicate content | +| LOW | Formatting issues, minor improvements | + +## Follow-Up Actions + +After analysis, offer: +1. Implement all content recommendations +2. Add missing plugin integrations +3. Do both (recommended) +4. Show preview of changes first diff --git a/plugins/claude-config-maintainer/skills/claude-md-structure.md b/plugins/claude-config-maintainer/skills/claude-md-structure.md new file mode 100644 index 0000000..4eb1c8e --- /dev/null +++ b/plugins/claude-config-maintainer/skills/claude-md-structure.md @@ -0,0 +1,113 @@ +# CLAUDE.md Structure Reference + +This skill defines the standard structure, required sections, and templates for CLAUDE.md files. + +## Required Sections + +Every CLAUDE.md MUST have these sections: + +| Section | Purpose | Priority | +|---------|---------|----------| +| Project Overview | What the project does | Required | +| Quick Start | Build/test/run commands | Required | +| Critical Rules | Must-follow constraints | Required | +| Pre-Change Protocol | Dependency check before edits | **MANDATORY** | + +## Recommended Sections + +| Section | When to Include | +|---------|-----------------| +| Architecture | Complex projects with multiple components | +| Common Operations | Projects with repetitive tasks | +| File Structure | Large codebases | +| Troubleshooting | Projects with known gotchas | +| Integration Points | Projects with external dependencies | + +## Header Hierarchy + +``` +# CLAUDE.md (H1 - only one) +## Section (H2 - main sections) +### Subsection (H3 - within sections) +#### Detail (H4 - rarely needed) +``` + +**Rules:** +- Never skip levels (no H3 before H2) +- Maximum depth: 4 levels +- No orphaned content before first header + +## Templates + +### Minimal Template +For small projects: +```markdown +# CLAUDE.md + +## Project Overview +[Description] + +## Quick Start +[Commands] + +## Critical Rules +[Constraints] + +## Pre-Change Protocol +[Mandatory section - see pre-change-protocol.md] +``` + +### Standard Template (Default) +```markdown +# CLAUDE.md + +## Project Overview +## Quick Start +## Architecture +## Critical Rules +## Pre-Change Protocol +## Common Operations +## File Structure +``` + +### Comprehensive Template +For large projects - adds: +- Detailed Architecture +- Troubleshooting +- Integration Points +- Development Workflow +- Deployment Notes + +## Auto-Detection Signals + +| Technology | Detection Method | +|------------|------------------| +| Language | File extensions, config files | +| Framework | package.json, requirements.txt, Cargo.toml | +| Build system | Makefile, scripts in package.json | +| Testing | pytest.ini, jest.config.js, go.mod | +| Docker | Dockerfile, docker-compose.yml | +| Database | ORM configs, connection strings | + +## Section Content Guidelines + +### Project Overview +- 1-3 sentences describing purpose +- Target audience if relevant +- Key technologies used + +### Quick Start +- Install command +- Test command +- Run command +- Each with brief inline comment + +### Critical Rules +- Numbered or bulleted list +- Specific, actionable constraints +- Include rationale for non-obvious rules + +### Architecture +- High-level component diagram (ASCII or description) +- Data flow explanation +- Key file/directory purposes diff --git a/plugins/claude-config-maintainer/skills/diff-analysis.md b/plugins/claude-config-maintainer/skills/diff-analysis.md new file mode 100644 index 0000000..1896af7 --- /dev/null +++ b/plugins/claude-config-maintainer/skills/diff-analysis.md @@ -0,0 +1,97 @@ +# CLAUDE.md Diff Analysis + +This skill defines how to analyze and present CLAUDE.md differences. + +## Comparison Modes + +| Mode | Command | Description | +|------|---------|-------------| +| Working vs HEAD | `/config-diff` | Uncommitted changes | +| Working vs Commit | `--commit=REF` | Changes since specific point | +| Commit to Commit | `--from=X --to=Y` | Historical comparison | +| Branch Comparison | `--branch=NAME` | Cross-branch differences | + +## Change Indicators + +| Symbol | Meaning | +|--------|---------| +| `+` | Line added | +| `-` | Line removed | +| `@@` | Location marker (line numbers) | +| `[MODIFIED]` | Section has changes | +| `[ADDED]` | New section created | +| `[REMOVED]` | Section deleted | +| `[UNCHANGED]` | No changes to section | + +## Impact Categories + +| Category | Meaning | +|----------|---------| +| NEW REQUIREMENT | Claude will need to do something new | +| REMOVED REQUIREMENT | Claude no longer needs to do something | +| MODIFIED | Existing behavior changed | +| NEW RULE | New constraint added | +| RELAXED RULE | Constraint removed or softened | + +## Report Format + +``` +CLAUDE.md Diff Report +===================== + +File: /path/to/project/CLAUDE.md +Comparing: [mode description] +Commit: [ref] "[message]" (time ago) + +Summary: +- Lines added: N +- Lines removed: N +- Net change: +/-N lines +- Sections affected: N + +Section Changes: +---------------- + +## Section Name [STATUS] + +/- Change description + +Detailed Diff: +-------------- + +--- CLAUDE.md (before) ++++ CLAUDE.md (after) + +@@ -N,M +N,M @@ + context +-removed ++added + context + +Behavioral Impact: +------------------ + +These changes will affect Claude's behavior: + +N. [CATEGORY] Description of impact +``` + +## Section-Focused View + +When using `--section=NAME`: +- Filter diff to only that section +- Show section-specific statistics +- Highlight behavioral impact for that area + +## Troubleshooting + +### No changes detected +- File matches comparison target +- Verify comparing correct commits + +### File not found in commit +- CLAUDE.md didn't exist at that point +- Use `git log -- CLAUDE.md` to find creation + +### Not a git repository +- Command requires git history +- Initialize git or use file backup comparison diff --git a/plugins/claude-config-maintainer/skills/lint-rules.md b/plugins/claude-config-maintainer/skills/lint-rules.md new file mode 100644 index 0000000..e9c32f5 --- /dev/null +++ b/plugins/claude-config-maintainer/skills/lint-rules.md @@ -0,0 +1,136 @@ +# CLAUDE.md Lint Rules + +This skill defines all linting rules for validating CLAUDE.md files. + +## Rule Categories + +### Security Rules (SEC) + +| Rule | Description | Severity | Auto-fix | +|------|-------------|----------|----------| +| SEC001 | Hardcoded absolute paths | Warning | Yes | +| SEC002 | Potential secrets/API keys | Error | No | +| SEC003 | Hardcoded IP addresses | Warning | No | +| SEC004 | Exposed credentials patterns | Error | No | +| SEC005 | Hardcoded URLs with tokens | Error | No | +| SEC006 | Environment variable values (not names) | Warning | No | + +### Structure Rules (STR) + +| Rule | Description | Severity | Auto-fix | +|------|-------------|----------|----------| +| STR001 | Missing required sections | Error | Yes | +| STR002 | Invalid header hierarchy (h3 before h2) | Warning | Yes | +| STR003 | Orphaned content before first header | Info | No | +| STR004 | Excessive nesting depth (>4 levels) | Warning | No | +| STR005 | Empty sections | Warning | Yes | +| STR006 | Missing section content | Warning | No | + +### Content Rules (CNT) + +| Rule | Description | Severity | Auto-fix | +|------|-------------|----------|----------| +| CNT001 | Contradictory instructions | Error | No | +| CNT002 | Vague or ambiguous rules | Warning | No | +| CNT003 | Overly long sections (>100 lines) | Info | No | +| CNT004 | Duplicate content | Warning | No | +| CNT005 | TODO/FIXME in production config | Warning | No | +| CNT006 | Outdated version references | Info | No | +| CNT007 | Broken internal links | Warning | No | + +### Format Rules (FMT) + +| Rule | Description | Severity | Auto-fix | +|------|-------------|----------|----------| +| FMT001 | Inconsistent header styles | Info | Yes | +| FMT002 | Inconsistent list markers | Info | Yes | +| FMT003 | Missing code block language | Info | Yes | +| FMT004 | Trailing whitespace | Info | Yes | +| FMT005 | Missing blank lines around headers | Info | Yes | +| FMT006 | Inconsistent indentation | Info | Yes | + +### Best Practice Rules (BPR) + +| Rule | Description | Severity | Auto-fix | +|------|-------------|----------|----------| +| BPR001 | No Quick Start section | Warning | No | +| BPR002 | No Critical Rules section | Warning | No | +| BPR003 | Instructions without examples | Info | No | +| BPR004 | Commands without explanation | Info | No | +| BPR005 | Rules without rationale | Info | No | +| BPR006 | Missing plugin integration docs | Info | No | + +## Anti-Pattern Examples + +### SEC002: Hardcoded Secrets +```markdown +# BAD +API_KEY=sk-1234567890abcdef + +# GOOD +API_KEY=$OPENAI_API_KEY # Set via environment +``` + +### SEC001: Hardcoded Paths +```markdown +# BAD +Config file: /home/john/projects/myapp/config.yml + +# GOOD +Config file: ./config.yml +Config file: $PROJECT_ROOT/config.yml +``` + +### CNT001: Contradictory Rules +```markdown +# BAD +- Always use TypeScript +- JavaScript files are acceptable for scripts + +# GOOD +- Always use TypeScript for source code +- JavaScript (.js) is acceptable only for config files and scripts +``` + +### CNT002: Vague Instructions +```markdown +# BAD +- Be careful with the database + +# GOOD +- Never run DELETE without WHERE clause +- Always backup before migrations +``` + +### STR002: Invalid Hierarchy +```markdown +# BAD +# Main Title +### Skipped Level + +# GOOD +# Main Title +## Section +### Subsection +``` + +## Output Format + +``` +[SEVERITY] RULE_ID: Description (line N) + | Context line showing issue + | ^^^^^^ indicator + +-- Explanation of problem + + Suggested fix: + - old line + + new line +``` + +## Severity Levels + +| Level | Meaning | Action | +|-------|---------|--------| +| Error | Must fix | Blocks commit | +| Warning | Should fix | Review recommended | +| Info | Consider fixing | Optional improvement | diff --git a/plugins/claude-config-maintainer/skills/optimization-patterns.md b/plugins/claude-config-maintainer/skills/optimization-patterns.md new file mode 100644 index 0000000..b833844 --- /dev/null +++ b/plugins/claude-config-maintainer/skills/optimization-patterns.md @@ -0,0 +1,136 @@ +# CLAUDE.md Optimization Patterns + +This skill defines patterns for optimizing CLAUDE.md files. + +## Optimization Categories + +### Restructure +- Reorder sections by importance (Quick Start near top) +- Group related content together +- Improve header hierarchy +- Add navigation aids (TOC for long files) + +### Condense +- Remove redundant explanations +- Convert verbose text to bullet points +- Eliminate duplicate content +- Shorten overly detailed sections + +### Enhance +- Add missing essential sections +- **Add Pre-Change Protocol if missing (HIGH PRIORITY)** +- Improve unclear instructions +- Add helpful examples +- Highlight critical rules + +### Format +- Standardize header styles (no trailing colons) +- Fix code block formatting (add language tags) +- Align list formatting (consistent markers) +- Improve table layouts + +## Scoring Criteria + +### Structure (25 points) +- Logical section ordering +- Clear header hierarchy +- Easy navigation +- Appropriate grouping + +### Clarity (25 points) +- Clear instructions +- Good examples +- Unambiguous language +- Appropriate detail level + +### Completeness (25 points) +- Project overview present +- Quick start commands documented +- Critical rules highlighted +- Key workflows covered +- Pre-Change Protocol present (MANDATORY) + +### Conciseness (25 points) +- No unnecessary repetition +- Efficient information density +- Appropriate length for project size +- No generic filler content + +## Score Interpretation + +| Score | Rating | Action | +|-------|--------|--------| +| 90-100 | Excellent | Maintenance only | +| 70-89 | Good | Minor improvements | +| 50-69 | Needs Work | Optimization recommended | +| Below 50 | Poor | Major restructuring needed | + +## Common Optimizations + +### Verbose to Concise +```markdown +# Before (34 lines) +## Running Tests +To run the tests, you first need to make sure you have all the +dependencies installed. The dependencies are listed in requirements.txt. +Once you have installed the dependencies, you can run the tests using +pytest. Pytest will automatically discover all test files... + +# After (8 lines) +## Running Tests +```bash +pip install -r requirements.txt # Install dependencies +pytest # Run all tests +pytest -v # Verbose output +pytest tests/unit/ # Run specific directory +``` +``` + +### Duplicate Removal +- Keep first occurrence +- Add cross-reference if needed: "See [Section Name] above" + +### Header Standardization +```markdown +# Before +## Quick Start: +## Architecture +## Testing: + +# After +## Quick Start +## Architecture +## Testing +``` + +### Code Block Enhancement +```markdown +# Before +``` +npm install +npm test +``` + +# After +```bash +npm install # Install dependencies +npm test # Run test suite +``` +``` + +## Safety Features + +### Backup Creation +- Always backup before changes +- Store in `.claude/backups/CLAUDE.md.TIMESTAMP` +- Easy restoration if needed + +### Preview Mode +- Show all changes before applying +- Use diff format for easy review +- Allow approve/reject per change + +### Selective Application +- Can apply individual changes +- Skip specific optimizations +- Iterative refinement supported diff --git a/plugins/claude-config-maintainer/skills/pre-change-protocol.md b/plugins/claude-config-maintainer/skills/pre-change-protocol.md new file mode 100644 index 0000000..4ce1f21 --- /dev/null +++ b/plugins/claude-config-maintainer/skills/pre-change-protocol.md @@ -0,0 +1,83 @@ +# Pre-Change Protocol + +This skill defines the mandatory Pre-Change Protocol section that MUST be included in every CLAUDE.md file. + +## Why This Is Mandatory + +The Pre-Change Protocol prevents the #1 cause of bugs from AI-assisted coding: **incomplete changes where Claude modifies some files but misses others that reference the same code**. + +Without this protocol: +- Claude may rename a function but miss callers +- Claude may modify a config but miss documentation +- Claude may update a schema but miss dependent code + +## Detection + +Search CLAUDE.md for these indicators: +- Header containing "Pre-Change" or "Before Any Code Change" +- References to `grep -rn` or impact search +- Checklist with "Files That Will Be Affected" +- User verification checkpoint + +## Required Section Content + +```markdown +## MANDATORY: Before Any Code Change + +**Claude MUST show this checklist BEFORE editing any file:** + +### 1. Impact Search Results +Run and show output of: +```bash +grep -rn "PATTERN" --include="*.sh" --include="*.md" --include="*.json" --include="*.py" | grep -v ".git" +``` + +### 2. Files That Will Be Affected +Numbered list of every file to be modified, with the specific change for each. + +### 3. Files Searched But Not Changed (and why) +Proof that related files were checked and determined unchanged. + +### 4. Documentation That References This +List of docs that mention this feature/script/function. + +**User verifies this list before Claude proceeds. If Claude skips this, stop immediately.** + +### After Changes +Run the same grep and show results proving no references remain unaddressed. +``` + +## Placement + +Insert Pre-Change Protocol section: +- **After:** Critical Rules section +- **Before:** Common Operations section + +## If Missing During Analysis + +Flag as **HIGH PRIORITY** issue: + +``` +1. [HIGH] Missing Pre-Change Protocol section + CLAUDE.md lacks mandatory dependency-check protocol. + Impact: Claude may miss file references when making changes, + leading to broken dependencies and incomplete updates. + + Recommendation: Add Pre-Change Protocol section immediately. + This is the #1 cause of cascading bugs from incomplete changes. +``` + +## If Missing During Optimization + +**Automatically add the section** at the correct position. This is the highest priority enhancement. + +## Variations + +The exact wording can vary, but these elements are required: + +1. **Search requirement** - Must run grep/search before changes +2. **Affected files list** - Must enumerate all files to modify +3. **Non-affected files proof** - Must show what was checked but unchanged +4. **Documentation check** - Must list referencing docs +5. **User checkpoint** - Must pause for user verification +6. **Post-change verification** - Must verify after changes diff --git a/plugins/claude-config-maintainer/skills/visual-header.md b/plugins/claude-config-maintainer/skills/visual-header.md new file mode 100644 index 0000000..5c4e21a --- /dev/null +++ b/plugins/claude-config-maintainer/skills/visual-header.md @@ -0,0 +1,52 @@ +# Visual Header Display + +This skill defines the standard visual header for claude-config-maintainer commands. + +## Header Format + +``` ++-----------------------------------------------------------------+ +| CONFIG-MAINTAINER - [Command Name] | ++-----------------------------------------------------------------+ +``` + +## Command-Specific Headers + +### /config-analyze +``` ++-----------------------------------------------------------------+ +| CONFIG-MAINTAINER - CLAUDE.md Analysis | ++-----------------------------------------------------------------+ +``` + +### /config-optimize +``` ++-----------------------------------------------------------------+ +| CONFIG-MAINTAINER - CLAUDE.md Optimization | ++-----------------------------------------------------------------+ +``` + +### /config-lint +``` ++-----------------------------------------------------------------+ +| CONFIG-MAINTAINER - CLAUDE.md Lint | ++-----------------------------------------------------------------+ +``` + +### /config-diff +``` ++-----------------------------------------------------------------+ +| CONFIG-MAINTAINER - CLAUDE.md Diff | ++-----------------------------------------------------------------+ +``` + +### /config-init +``` ++-----------------------------------------------------------------+ +| CONFIG-MAINTAINER - CLAUDE.md Initialization | ++-----------------------------------------------------------------+ +``` + +## Usage + +Display the header at the start of command execution, before any analysis or output. diff --git a/plugins/code-sentinel/commands/refactor-dry.md b/plugins/code-sentinel/commands/refactor-dry.md index 91dcc94..4ae5bab 100644 --- a/plugins/code-sentinel/commands/refactor-dry.md +++ b/plugins/code-sentinel/commands/refactor-dry.md @@ -8,16 +8,12 @@ Analyze and preview refactoring opportunities without making changes. ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔒 CODE-SENTINEL · Refactor Preview │ -└──────────────────────────────────────────────────────────────────┘ ++----------------------------------------------------------------------+ +| CODE-SENTINEL - Refactor Preview | ++----------------------------------------------------------------------+ ``` -Then proceed with the analysis. - ## Usage ``` /refactor-dry [--all] @@ -26,44 +22,31 @@ Then proceed with the analysis. **Target:** File path, function name, or "." for current file **--all:** Show all opportunities, not just recommended +## Skills to Load + +- skills/refactoring-patterns.md +- skills/dry-run-workflow.md + ## Process -1. **Scan Target** - Analyze code for refactoring opportunities. +1. **Scan Target** - Analyze code using patterns from skill +2. **Score Opportunities** - Rate by Impact/Risk/Effort (see dry-run-workflow skill) +3. **Output** - Group by recommended vs optional -2. **Score Opportunities** - Each opportunity rated by: - - Impact (how much it improves code) - - Risk (likelihood of breaking something) - - Effort (complexity of the refactoring) +## Output Format -3. **Output** ``` -## Refactoring Opportunities: src/handlers.py +## Refactoring Opportunities: ### Recommended (High Impact, Low Risk) +1. **pattern** at lines X-Y + - Impact: High | Risk: Low + - Run: `/refactor --pattern=` -1. **extract-method** at lines 45-67 - - Extract order validation logic - - Impact: High (reduces complexity from 12 to 4) - - Risk: Low (pure function, no side effects) - - Run: `/refactor src/handlers.py:45 --pattern=extract-method` - -2. **use-dataclass** for OrderInput class - - Convert to dataclass with validation - - Impact: Medium (reduces boilerplate) - - Risk: Low - - Run: `/refactor src/models.py:OrderInput --pattern=use-dataclass` - -### Optional (Consider Later) - -3. **use-fstring** at 12 locations - - Modernize string formatting - - Impact: Low (readability only) - - Risk: None +### Optional +- Lower priority items ### Summary -- 2 recommended refactorings -- 1 optional improvement -- Estimated complexity reduction: 35% +- X recommended, Y optional +- Estimated complexity reduction: Z% ``` diff --git a/plugins/code-sentinel/commands/refactor.md b/plugins/code-sentinel/commands/refactor.md index 319767e..1c8d5e8 100644 --- a/plugins/code-sentinel/commands/refactor.md +++ b/plugins/code-sentinel/commands/refactor.md @@ -8,16 +8,12 @@ Apply refactoring transformations to specified code. ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔒 CODE-SENTINEL · Refactor │ -└──────────────────────────────────────────────────────────────────┘ ++----------------------------------------------------------------------+ +| CODE-SENTINEL - Refactor | ++----------------------------------------------------------------------+ ``` -Then proceed with the refactoring workflow. - ## Usage ``` /refactor [--pattern=] @@ -26,68 +22,31 @@ Then proceed with the refactoring workflow. **Target:** File path, function name, or "." for current context **Pattern:** Specific refactoring pattern (optional) -## Available Patterns +## Skills to Load -### Structure -| Pattern | Description | -|---------|-------------| -| `extract-method` | Extract code block into named function | -| `extract-class` | Move related methods to new class | -| `inline` | Inline trivial function/variable | -| `rename` | Rename with all references updated | -| `move` | Move function/class to different module | - -### Simplification -| Pattern | Description | -|---------|-------------| -| `simplify-conditional` | Flatten nested if/else | -| `remove-dead-code` | Delete unreachable code | -| `consolidate-duplicate` | Merge duplicate code blocks | -| `decompose-conditional` | Break complex conditions into named parts | - -### Modernization -| Pattern | Description | -|---------|-------------| -| `use-comprehension` | Convert loops to list/dict comprehensions | -| `use-pathlib` | Replace os.path with pathlib | -| `use-fstring` | Convert .format() to f-strings | -| `use-typing` | Add type hints | -| `use-dataclass` | Convert class to dataclass | +- skills/refactoring-patterns.md ## Process -1. **Analyze Target** - - Parse code structure - - Identify refactoring opportunities - - Check for side effects and dependencies +1. **Analyze Target** - Parse code, identify opportunities from skill, check dependencies +2. **Propose Changes** - Show before/after diff, explain improvement, list affected files +3. **Apply (with confirmation)** - Make changes, update references, run tests -2. **Propose Changes** - - Show before/after diff - - Explain the improvement - - List affected files/references +## Output Format -3. **Apply (with confirmation)** - - Make changes - - Update all references - - Run existing tests if available - -4. **Output** ``` -## Refactoring: extract-method +## Refactoring: ### Target -src/handlers.py:create_order (lines 45-89) +: (lines X-Y) ### Changes -- Extracted validation logic → validate_order_input() -- Extracted pricing logic → calculate_order_total() -- Original function now 15 lines (was 44) +- Change description ### Files Modified -- src/handlers.py -- tests/test_handlers.py (updated calls) +- file1.py ### Metrics -- Cyclomatic complexity: 12 → 4 -- Function length: 44 → 15 lines +- Cyclomatic complexity: X -> Y +- Function length: X -> Y lines ``` diff --git a/plugins/code-sentinel/commands/security-scan.md b/plugins/code-sentinel/commands/security-scan.md index a92ef9b..6f9348c 100644 --- a/plugins/code-sentinel/commands/security-scan.md +++ b/plugins/code-sentinel/commands/security-scan.md @@ -8,61 +8,34 @@ Comprehensive security audit of the project. ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔒 CODE-SENTINEL · Security Scan │ -└──────────────────────────────────────────────────────────────────┘ ++----------------------------------------------------------------------+ +| CODE-SENTINEL - Security Scan | ++----------------------------------------------------------------------+ ``` -Then proceed with the scan workflow. +## Skills to Load + +- skills/security-patterns/SKILL.md ## Process -1. **File Discovery** - Scan all code files: .py, .js, .ts, .jsx, .tsx, .go, .rs, .java, .rb, .php, .sh +1. **File Discovery** - Scan: .py, .js, .ts, .jsx, .tsx, .go, .rs, .java, .rb, .php, .sh +2. **Pattern Detection** - Apply patterns from skill (Critical/High/Medium severity) +3. **Report** - Group by severity, include code snippets and fixes -2. **Pattern Detection** +## Output Format - ### Critical Vulnerabilities - | Pattern | Risk | Detection | - |---------|------|-----------| - | SQL Injection | High | String concat in SQL queries | - | Command Injection | High | shell=True, os.system with vars | - | XSS | High | innerHTML with user input | - | Code Injection | Critical | eval/exec with external input | - | Deserialization | Critical | pickle.loads, yaml.load unsafe | - | Path Traversal | High | File ops without sanitization | - | Hardcoded Secrets | High | API keys, passwords in code | - | SSRF | Medium | URL from user input in requests | - - ### Code Quality Issues - | Pattern | Risk | Detection | - |---------|------|-----------| - | Broad Exceptions | Low | `except:` or `except Exception:` | - | Debug Statements | Low | print/console.log with data | - | TODO/FIXME Security | Medium | Comments mentioning security | - | Deprecated Functions | Medium | Known insecure functions | - -3. **Output Format** ``` ## Security Scan Report ### Critical (Immediate Action Required) -🔴 src/db.py:45 - SQL Injection - Code: `f"SELECT * FROM users WHERE id = {user_id}"` - Fix: Use parameterized query: `cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))` +[red] file:line - Vulnerability Type + Code: `problematic code` + Fix: Recommended solution -### High -🟠 config.py:12 - Hardcoded Secret - Code: `API_KEY = "sk-1234..."` - Fix: Use environment variable: `API_KEY = os.environ.get("API_KEY")` - -### Medium -🟡 utils.py:78 - Broad Exception - Code: `except:` - Fix: Catch specific exceptions +### High / Medium / Low +[Similar format] ### Summary - Critical: X (must fix before deploy) @@ -70,7 +43,8 @@ Then proceed with the scan workflow. - Medium: X (improve when possible) ``` -4. **Exit Code Guidance** - - Critical findings: Recommend blocking merge/deploy - - High findings: Recommend fixing before release - - Medium/Low: Informational +## Exit Guidance + +- Critical findings: Block merge/deploy +- High findings: Fix before release +- Medium/Low: Informational diff --git a/plugins/code-sentinel/skills/dry-run-workflow.md b/plugins/code-sentinel/skills/dry-run-workflow.md new file mode 100644 index 0000000..4f0c27d --- /dev/null +++ b/plugins/code-sentinel/skills/dry-run-workflow.md @@ -0,0 +1,99 @@ +--- +description: Workflow for previewing changes safely before applying them +--- + +# Dry Run Workflow Skill + +## Overview + +Dry run mode analyzes code and shows proposed changes without modifying files. Essential for reviewing impact before committing to changes. + +## Opportunity Scoring + +Rate each refactoring opportunity on three dimensions: + +### Impact Score (1-5) +| Score | Meaning | Example | +|-------|---------|---------| +| 5 | Major improvement | Cyclomatic complexity 15 -> 3 | +| 4 | Significant improvement | Function 50 lines -> 15 lines | +| 3 | Moderate improvement | Better naming, clearer structure | +| 2 | Minor improvement | Code style modernization | +| 1 | Cosmetic only | Formatting changes | + +### Risk Score (1-5) +| Score | Meaning | Example | +|-------|---------|---------| +| 5 | Very high risk | Changes to core business logic | +| 4 | High risk | Modifies shared utilities | +| 3 | Moderate risk | Changes function signatures | +| 2 | Low risk | Internal implementation only | +| 1 | Minimal risk | Pure functions, no side effects | + +### Effort Score (1-5) +| Score | Meaning | Example | +|-------|---------|---------| +| 5 | Major effort | Requires architecture changes | +| 4 | Significant effort | Many files affected | +| 3 | Moderate effort | Multiple related changes | +| 2 | Low effort | Single file, clear scope | +| 1 | Trivial | Automated transformation | + +## Priority Calculation + +``` +Priority = (Impact * 2) - Risk - (Effort * 0.5) +``` + +| Priority Range | Recommendation | +|---------------|----------------| +| > 5 | Recommended - do it | +| 3-5 | Optional - consider it | +| < 3 | Skip - not worth it | + +## Output Format + +### Recommended Section +High impact, low risk opportunities: +``` +1. **pattern-name** at file:lines + - Description of the change + - Impact: High/Medium/Low (specific metric improvement) + - Risk: Low/Medium/High (why) + - Run: `/refactor --pattern=` +``` + +### Optional Section +Lower priority opportunities grouped by type. + +### Summary +- Count of recommended vs optional +- Estimated overall improvement percentage +- Any blockers or dependencies + +## Dependency Detection + +Before recommending changes, check for: + +1. **Test Coverage** - Does this code have tests? +2. **Usage Scope** - Is it used elsewhere? +3. **Side Effects** - Does it modify external state? +4. **Breaking Changes** - Will it change public API? + +Flag dependencies in output: +``` +Note: This refactoring requires updating 3 callers: + - src/api/handlers.py:45 + - src/cli/commands.py:78 + - tests/test_handlers.py:23 +``` + +## Safety Checklist + +Before recommending any change: + +- [ ] All affected code locations identified +- [ ] No breaking API changes without flag +- [ ] Test coverage assessed +- [ ] Side effects documented +- [ ] Rollback path clear (git) diff --git a/plugins/code-sentinel/skills/refactoring-patterns.md b/plugins/code-sentinel/skills/refactoring-patterns.md new file mode 100644 index 0000000..cb15bf8 --- /dev/null +++ b/plugins/code-sentinel/skills/refactoring-patterns.md @@ -0,0 +1,119 @@ +--- +description: Code refactoring patterns and techniques for improving structure and maintainability +--- + +# Refactoring Patterns Skill + +## Structure Patterns + +| Pattern | Description | When to Use | +|---------|-------------|-------------| +| `extract-method` | Extract code block into named function | Long functions, repeated logic | +| `extract-class` | Move related methods to new class | Class doing too much | +| `inline` | Inline trivial function/variable | Over-abstracted code | +| `rename` | Rename with all references updated | Unclear naming | +| `move` | Move function/class to different module | Misplaced code | + +### extract-method Example +```python +# BEFORE +def process_order(order): + # Validate (extract this) + if not order.items: + raise ValueError("Empty order") + if order.total < 0: + raise ValueError("Invalid total") + # Process + for item in order.items: + inventory.reserve(item) + return create_invoice(order) + +# AFTER +def validate_order(order): + if not order.items: + raise ValueError("Empty order") + if order.total < 0: + raise ValueError("Invalid total") + +def process_order(order): + validate_order(order) + for item in order.items: + inventory.reserve(item) + return create_invoice(order) +``` + +## Simplification Patterns + +| Pattern | Description | When to Use | +|---------|-------------|-------------| +| `simplify-conditional` | Flatten nested if/else | Deep nesting (>3 levels) | +| `remove-dead-code` | Delete unreachable code | After refactoring | +| `consolidate-duplicate` | Merge duplicate code blocks | DRY violations | +| `decompose-conditional` | Break complex conditions into named parts | Long boolean expressions | + +### simplify-conditional Example +```python +# BEFORE +if user: + if user.active: + if user.has_permission: + do_action() + +# AFTER (guard clauses) +if not user: + return +if not user.active: + return +if not user.has_permission: + return +do_action() +``` + +## Modernization Patterns + +| Pattern | Description | When to Use | +|---------|-------------|-------------| +| `use-comprehension` | Convert loops to list/dict comprehensions | Simple transformations | +| `use-pathlib` | Replace os.path with pathlib | File path operations | +| `use-fstring` | Convert .format() to f-strings | String formatting | +| `use-typing` | Add type hints | Public APIs, complex functions | +| `use-dataclass` | Convert class to dataclass | Data-holding classes | + +### use-dataclass Example +```python +# BEFORE +class User: + def __init__(self, name, email, age): + self.name = name + self.email = email + self.age = age + +# AFTER +@dataclass +class User: + name: str + email: str + age: int +``` + +## Code Smell Detection + +| Smell | Indicators | Suggested Pattern | +|-------|------------|-------------------| +| Long Method | >20 lines, multiple responsibilities | extract-method | +| Large Class | >10 methods, low cohesion | extract-class | +| Primitive Obsession | Many related primitives | use-dataclass | +| Nested Conditionals | >3 nesting levels | simplify-conditional | +| Duplicate Code | Copy-pasted blocks | consolidate-duplicate | +| Dead Code | Unreachable branches | remove-dead-code | + +## Metrics + +After refactoring, measure improvement: + +| Metric | Good Target | Tool | +|--------|-------------|------| +| Cyclomatic Complexity | <10 per function | radon, lizard | +| Function Length | <25 lines | manual count | +| Class Cohesion | LCOM <0.5 | pylint | +| Duplication | <3% | jscpd, radon | diff --git a/plugins/contract-validator/commands/check-agent.md b/plugins/contract-validator/commands/check-agent.md index 15ca4b6..54f57b6 100644 --- a/plugins/contract-validator/commands/check-agent.md +++ b/plugins/contract-validator/commands/check-agent.md @@ -1,18 +1,10 @@ # /check-agent - Validate Agent Definition -## Visual Output - -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ ✅ CONTRACT-VALIDATOR · Agent Check │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the validation. - -Validate a single agent's tool references and data flow. +## Skills to Load +- skills/visual-output.md +- skills/interface-parsing.md +- skills/validation-rules.md +- skills/mcp-tools-reference.md ## Usage @@ -22,30 +14,26 @@ Validate a single agent's tool references and data flow. ## Parameters -- `agent_name` (required): Name of the agent to validate (e.g., "Planner", "Orchestrator") -- `claude_md_path` (optional): Path to CLAUDE.md file. Defaults to `./CLAUDE.md` +- `agent_name` (required): Agent to validate (e.g., "Planner", "Orchestrator") +- `claude_md_path` (optional): Path to CLAUDE.md. Defaults to `./CLAUDE.md` ## Workflow -1. **Parse agent definition**: - - Locate agent in CLAUDE.md (Four-Agent Model table or Agents section) - - Extract responsibilities, tool references, workflow steps +1. **Display header** per `skills/visual-output.md` -2. **Validate tool references**: - - Check each referenced tool exists in available plugins - - Report missing or misspelled tool names - - Suggest corrections for common mistakes +2. **Parse agent** per `skills/interface-parsing.md` + - Use `parse_claude_md_agents` to extract agent definition + - Get responsibilities, tool references, workflow steps -3. **Validate data flow**: - - Analyze sequence of tools in agent workflow - - Verify data producers precede data consumers - - Check for orphaned data references +3. **Validate** per `skills/validation-rules.md` + - Use `validate_agent_refs` - check all tools exist + - Use `validate_data_flow` - verify producer/consumer order 4. **Report findings**: - - List all tool references found - - List any missing tools - - Data flow validation results - - Suggestions for improvement + - Tool references found + - Missing tools (with suggestions) + - Data flow issues + - Recommendations ## Examples @@ -54,10 +42,3 @@ Validate a single agent's tool references and data flow. /check-agent Orchestrator ./CLAUDE.md /check-agent data-analysis ~/project/CLAUDE.md ``` - -## Available Tools - -Use these MCP tools: -- `validate_agent_refs` - Check agent tool references exist -- `validate_data_flow` - Verify data flow through agent sequence -- `parse_claude_md_agents` - Parse all agents from CLAUDE.md diff --git a/plugins/contract-validator/commands/dependency-graph.md b/plugins/contract-validator/commands/dependency-graph.md index b7520ac..8fe3f3c 100644 --- a/plugins/contract-validator/commands/dependency-graph.md +++ b/plugins/contract-validator/commands/dependency-graph.md @@ -1,18 +1,11 @@ # /dependency-graph - Generate Dependency Visualization -## Visual Output - -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ ✅ CONTRACT-VALIDATOR · Dependency Graph │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the visualization. - -Generate a Mermaid flowchart showing plugin dependencies, data flows, and tool relationships. +## Skills to Load +- skills/visual-output.md +- skills/plugin-discovery.md +- skills/interface-parsing.md +- skills/dependency-analysis.md +- skills/mcp-tools-reference.md ## Usage @@ -28,236 +21,35 @@ Generate a Mermaid flowchart showing plugin dependencies, data flows, and tool r ## Workflow -1. **Discover plugins**: - - Scan plugins directory for all plugins with `.claude-plugin/` marker - - Parse each plugin's README.md to extract interface - - Parse CLAUDE.md for agent definitions and tool sequences +1. **Display header** per `skills/visual-output.md` -2. **Analyze dependencies**: - - Identify shared MCP servers (plugins using same server) - - Detect tool dependencies (which plugins produce vs consume data) - - Find agent tool references across plugins - - Categorize as required (ERROR if missing) or optional (WARNING if missing) +2. **Discover plugins** per `skills/plugin-discovery.md` -3. **Build dependency graph**: - - Create nodes for each plugin - - Create edges for: - - Shared MCP servers (bidirectional) - - Data producers -> consumers (directional) - - Agent tool dependencies (directional) - - Mark edges as optional or required +3. **Parse interfaces** per `skills/interface-parsing.md` + - Use `parse_plugin_interface` for each plugin + - Use `parse_claude_md_agents` for CLAUDE.md -4. **Generate Mermaid output**: - - Create flowchart diagram syntax - - Style required dependencies with solid lines - - Style optional dependencies with dashed lines - - Group by MCP server or data flow +4. **Analyze dependencies** per `skills/dependency-analysis.md` + - Identify shared MCP servers + - Detect data producers/consumers + - Categorize as required or optional -## Output Format - -### Mermaid (default) - -```mermaid -flowchart TD - subgraph mcp_gitea["MCP: gitea"] - projman["projman"] - pr-review["pr-review"] - end - - subgraph mcp_data["MCP: data-platform"] - data-platform["data-platform"] - end - - subgraph mcp_viz["MCP: viz-platform"] - viz-platform["viz-platform"] - end - - %% Data flow dependencies - data-platform -->|"data_ref (required)"| viz-platform - - %% Optional dependencies - projman -.->|"lessons (optional)"| pr-review - - %% Styling - classDef required stroke:#e74c3c,stroke-width:2px - classDef optional stroke:#f39c12,stroke-dasharray:5 5 -``` - -### Text Format - -``` -DEPENDENCY GRAPH -================ - -Plugins: 12 -MCP Servers: 4 -Dependencies: 8 (5 required, 3 optional) - -MCP Server Groups: - gitea: projman, pr-review - data-platform: data-platform - viz-platform: viz-platform - netbox: cmdb-assistant - -Data Flow Dependencies: - data-platform -> viz-platform (data_ref) [REQUIRED] - data-platform -> data-platform (data_ref) [INTERNAL] - -Cross-Plugin Tool Usage: - projman.Planner uses: create_issue, search_lessons - pr-review.reviewer uses: get_pr_diff, create_pr_review -``` - -## Dependency Types - -| Type | Line Style | Meaning | -|------|------------|---------| -| Required | Solid (`-->`) | Plugin cannot function without this dependency | -| Optional | Dashed (`-.->`) | Plugin works but with reduced functionality | -| Internal | Dotted (`...>`) | Self-dependency within same plugin | -| Shared MCP | Double (`==>`) | Plugins share same MCP server instance | - -## Known Data Flow Patterns - -The command recognizes these producer/consumer relationships: - -### Data Producers -- `read_csv`, `read_parquet`, `read_json` - File loaders -- `pg_query`, `pg_execute` - Database queries -- `filter`, `select`, `groupby`, `join` - Transformations - -### Data Consumers -- `describe`, `head`, `tail` - Data inspection -- `to_csv`, `to_parquet` - File writers -- `chart_create` - Visualization - -### Cross-Plugin Flows -- `data-platform` produces `data_ref` -> `viz-platform` consumes for charts -- `projman` produces issues -> `pr-review` references in reviews -- `gitea` wiki -> `projman` lessons learned +5. **Generate output**: + - Mermaid: Create flowchart TD diagram with styled edges + - Text: Create text summary with counts and lists ## Examples -### Basic Usage - ``` /dependency-graph -``` - -Generates Mermaid diagram for current marketplace. - -### With Tool Details - -``` /dependency-graph --show-tools -``` - -Includes individual tool nodes showing which tools each plugin provides. - -### Text Summary - -``` /dependency-graph --format text -``` - -Outputs text-based summary suitable for CLAUDE.md inclusion. - -### Specific Path - -``` /dependency-graph ~/claude-plugins-work ``` -Analyze marketplace at specified path. +## Integration -## Integration with Other Commands - -Use with `/validate-contracts` to: -1. Run `/dependency-graph` to visualize relationships -2. Run `/validate-contracts` to find issues in those relationships -3. Fix issues and regenerate graph to verify - -## Available Tools - -Use these MCP tools: -- `parse_plugin_interface` - Extract interface from plugin README.md -- `parse_claude_md_agents` - Extract agents and their tool sequences -- `generate_compatibility_report` - Get full interface data (JSON format for analysis) -- `validate_data_flow` - Verify data producer/consumer relationships - -## Implementation Notes - -### Detecting Shared MCP Servers - -Check each plugin's `.mcp.json` file for server definitions: - -```bash -# List all .mcp.json files in plugins -find plugins/ -name ".mcp.json" -exec cat {} \; -``` - -Plugins with identical MCP server names share that server. - -### Identifying Data Flows - -1. Parse tool categories from README.md -2. Map known producer tools to their output types -3. Map known consumer tools to their input requirements -4. Create edges where outputs match inputs - -### Optional vs Required - -- **Required**: Consumer tool has no default/fallback behavior -- **Optional**: Consumer works without producer (e.g., lessons search returns empty) - -Determination is based on: -- Issue severity from `validate_data_flow` (ERROR = required, WARNING = optional) -- Tool documentation stating "requires" vs "uses if available" - -## Sample Output - -For the leo-claude-mktplace: - -```mermaid -flowchart TD - subgraph gitea_mcp["Shared MCP: gitea"] - projman["projman
14 commands"] - pr-review["pr-review
6 commands"] - end - - subgraph netbox_mcp["Shared MCP: netbox"] - cmdb-assistant["cmdb-assistant
3 commands"] - end - - subgraph data_mcp["Shared MCP: data-platform"] - data-platform["data-platform
7 commands"] - end - - subgraph viz_mcp["Shared MCP: viz-platform"] - viz-platform["viz-platform
7 commands"] - end - - subgraph standalone["Standalone Plugins"] - doc-guardian["doc-guardian"] - code-sentinel["code-sentinel"] - clarity-assist["clarity-assist"] - git-flow["git-flow"] - claude-config-maintainer["claude-config-maintainer"] - contract-validator["contract-validator"] - end - - %% Data flow: data-platform -> viz-platform - data-platform -->|"data_ref"| viz-platform - - %% Cross-plugin: projman lessons -> pr-review context - projman -.->|"lessons"| pr-review - - %% Styling - classDef mcpGroup fill:#e8f4fd,stroke:#2196f3 - classDef standalone fill:#f5f5f5,stroke:#9e9e9e - classDef required stroke:#e74c3c,stroke-width:2px - classDef optional stroke:#f39c12,stroke-dasharray:5 5 - - class gitea_mcp,netbox_mcp,data_mcp,viz_mcp mcpGroup - class standalone standalone -``` +Use with `/validate-contracts`: +1. Run `/dependency-graph` to visualize +2. Run `/validate-contracts` to find issues +3. Fix and regenerate diff --git a/plugins/contract-validator/commands/initial-setup.md b/plugins/contract-validator/commands/initial-setup.md index 9b77f46..687e6fa 100644 --- a/plugins/contract-validator/commands/initial-setup.md +++ b/plugins/contract-validator/commands/initial-setup.md @@ -1,164 +1,49 @@ --- -description: Interactive setup wizard for contract-validator plugin - verifies MCP server and shows capabilities +description: Interactive setup wizard for contract-validator plugin --- -# Contract-Validator Setup Wizard +# /initial-setup - Contract-Validator Setup Wizard -## Visual Output +## Skills to Load +- skills/visual-output.md +- skills/mcp-tools-reference.md -When executing this command, display the plugin header: +**Important:** This command uses Bash, Read, Write tools - NOT MCP tools (they work only after setup + restart). -``` -┌──────────────────────────────────────────────────────────────────┐ -│ ✅ CONTRACT-VALIDATOR · Setup Wizard │ -└──────────────────────────────────────────────────────────────────┘ -``` +## Workflow -Then proceed with the setup. +1. **Display header** per `skills/visual-output.md` -This command sets up the contract-validator plugin for cross-plugin compatibility validation. +2. **Check Python version**: + ```bash + python3 --version + ``` + Requires 3.10+. Stop if below. -## Important Context +3. **Locate MCP server**: + - Installed: `~/.claude/plugins/marketplaces/leo-claude-mktplace/mcp-servers/contract-validator/` + - Source: `~/claude-plugins-work/mcp-servers/contract-validator/` -- **This command uses Bash, Read, Write, and AskUserQuestion tools** - NOT MCP tools -- **MCP tools won't work until after setup + session restart** -- **No external credentials required** - this plugin validates local files only +4. **Check/create venv**: + ```bash + ls .venv/bin/python || (python3 -m venv .venv && .venv/bin/pip install -r requirements.txt) + ``` ---- +5. **Verify MCP server**: + ```bash + .venv/bin/python -c "from mcp_server.server import ContractValidatorMCPServer; print('OK')" + ``` -## Phase 1: Environment Validation +6. **Display success** per `skills/visual-output.md` -### Step 1.1: Check Python Version +7. **Inform user**: Session restart required for MCP tools. -```bash -python3 --version -``` +## Post-Setup Commands -Requires Python 3.10+. If below, stop setup and inform user: -``` -Python 3.10 or higher is required. Please install it and run /initial-setup again. -``` - ---- - -## Phase 2: MCP Server Setup - -### Step 2.1: Locate Contract-Validator MCP Server - -```bash -# If running from installed marketplace -ls -la ~/.claude/plugins/marketplaces/leo-claude-mktplace/mcp-servers/contract-validator/ 2>/dev/null || echo "NOT_FOUND_INSTALLED" - -# If running from source -ls -la ~/claude-plugins-work/mcp-servers/contract-validator/ 2>/dev/null || echo "NOT_FOUND_SOURCE" -``` - -Determine which path exists and use that as the MCP server path. - -### Step 2.2: Check Virtual Environment - -```bash -ls -la /path/to/mcp-servers/contract-validator/.venv/bin/python 2>/dev/null && echo "VENV_EXISTS" || echo "VENV_MISSING" -``` - -### Step 2.3: Create Virtual Environment (if missing) - -```bash -cd /path/to/mcp-servers/contract-validator && python3 -m venv .venv && source .venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt && deactivate -``` - -**If pip install fails:** -- Show the error to the user -- Suggest: "Check your internet connection and try again." - ---- - -## Phase 3: Validation - -### Step 3.1: Verify MCP Server - -```bash -cd /path/to/mcp-servers/contract-validator && .venv/bin/python -c "from mcp_server.server import ContractValidatorMCPServer; print('MCP Server OK')" -``` - -If this fails, check the error and report it to the user. - -### Step 3.2: Summary - -Display: - -``` -╔════════════════════════════════════════════════════════════════╗ -║ CONTRACT-VALIDATOR SETUP COMPLETE ║ -╠════════════════════════════════════════════════════════════════╣ -║ MCP Server: ✓ Ready ║ -║ Parse Tools: ✓ Available (2 tools) ║ -║ Validation Tools: ✓ Available (3 tools) ║ -║ Report Tools: ✓ Available (2 tools) ║ -╚════════════════════════════════════════════════════════════════╝ -``` - -### Step 3.3: Session Restart Notice - ---- - -**Session Restart Required** - -Restart your Claude Code session for MCP tools to become available. - -**After restart, you can:** -- Run `/validate-contracts` to check all plugins for compatibility issues -- Run `/check-agent` to validate a single agent definition -- Run `/list-interfaces` to see all plugin commands and tools - ---- - -## Available Tools - -| Category | Tools | Description | -|----------|-------|-------------| -| Parse | `parse_plugin_interface`, `parse_claude_md_agents` | Extract interfaces from README.md and agents from CLAUDE.md | -| Validation | `validate_compatibility`, `validate_agent_refs`, `validate_data_flow` | Check conflicts, tool references, and data flows | -| Report | `generate_compatibility_report`, `list_issues` | Generate reports and filter issues | - ---- - -## Available Commands - -| Command | Description | -|---------|-------------| -| `/validate-contracts` | Full marketplace compatibility validation | -| `/check-agent` | Validate single agent definition | -| `/list-interfaces` | Show all plugin interfaces | - ---- - -## Use Cases - -### 1. Pre-Release Validation -Run `/validate-contracts` before releasing a new marketplace version to catch: -- Command name conflicts between plugins -- Missing tool references in agents -- Broken data flows - -### 2. Agent Development -Run `/check-agent` when creating or modifying agents to verify: -- All referenced tools exist -- Data flows are valid -- No undeclared dependencies - -### 3. Plugin Audit -Run `/list-interfaces` to get a complete view of: -- All commands across plugins -- All tools available -- Potential overlap areas - ---- +- `/validate-contracts` - Full marketplace validation +- `/check-agent` - Validate single agent +- `/list-interfaces` - Show all plugin interfaces ## No Configuration Required -This plugin doesn't require any configuration files. It reads plugin manifests and README files directly from the filesystem. - -**Paths it scans:** -- Marketplace: `~/.claude/plugins/marketplaces/leo-claude-mktplace/plugins/` -- Source (if available): `~/claude-plugins-work/plugins/` +This plugin reads plugin manifests and README files directly - no credentials needed. diff --git a/plugins/contract-validator/commands/list-interfaces.md b/plugins/contract-validator/commands/list-interfaces.md index b2dd4cc..dce1ed7 100644 --- a/plugins/contract-validator/commands/list-interfaces.md +++ b/plugins/contract-validator/commands/list-interfaces.md @@ -1,18 +1,10 @@ # /list-interfaces - Show Plugin Interfaces -## Visual Output - -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ ✅ CONTRACT-VALIDATOR · List Interfaces │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the interface listing. - -Display what each plugin in the marketplace produces and accepts. +## Skills to Load +- skills/visual-output.md +- skills/plugin-discovery.md +- skills/interface-parsing.md +- skills/mcp-tools-reference.md ## Usage @@ -26,35 +18,25 @@ Display what each plugin in the marketplace produces and accepts. ## Workflow -1. **Discover plugins**: - - Scan plugins directory for all plugins with `.claude-plugin/` marker - - Read each plugin's README.md +1. **Display header** per `skills/visual-output.md` -2. **Parse interfaces**: - - Extract commands (slash commands offered by plugin) - - Extract agents (autonomous agents defined) - - Extract tools (MCP tools provided) - - Identify tool categories and features +2. **Discover plugins** per `skills/plugin-discovery.md` -3. **Display summary**: - - Table of plugins with command/agent/tool counts - - Detailed breakdown per plugin - - Tool categories and their contents +3. **Parse interfaces** per `skills/interface-parsing.md` + - Use `parse_plugin_interface` for each plugin README.md + - Extract commands, agents, tools -## Output Format +4. **Display summary table**: + ``` + | Plugin | Commands | Agents | Tools | + |-------------|----------|--------|-------| + | projman | 12 | 4 | 26 | + ``` -``` -| Plugin | Commands | Agents | Tools | -|-------------|----------|--------|-------| -| projman | 12 | 4 | 26 | -| data-platform| 7 | 2 | 32 | -| ... | ... | ... | ... | - -## projman -- Commands: /sprint-plan, /sprint-start, ... -- Agents: Planner, Orchestrator, Executor, Code Reviewer -- Tools: list_issues, create_issue, ... -``` +5. **Display per-plugin details**: + - List of commands + - List of agents + - Tool categories ## Examples @@ -62,9 +44,3 @@ Display what each plugin in the marketplace produces and accepts. /list-interfaces /list-interfaces ~/claude-plugins-work ``` - -## Available Tools - -Use these MCP tools: -- `parse_plugin_interface` - Parse individual plugin README -- `generate_compatibility_report` - Get full interface data (JSON format) diff --git a/plugins/contract-validator/commands/validate-contracts.md b/plugins/contract-validator/commands/validate-contracts.md index 5d5067a..e38d20c 100644 --- a/plugins/contract-validator/commands/validate-contracts.md +++ b/plugins/contract-validator/commands/validate-contracts.md @@ -1,18 +1,11 @@ # /validate-contracts - Full Contract Validation -## Visual Output - -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ ✅ CONTRACT-VALIDATOR · Full Validation │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the validation. - -Run comprehensive cross-plugin compatibility validation for the entire marketplace. +## Skills to Load +- skills/visual-output.md +- skills/plugin-discovery.md +- skills/interface-parsing.md +- skills/validation-rules.md +- skills/mcp-tools-reference.md ## Usage @@ -26,25 +19,22 @@ Run comprehensive cross-plugin compatibility validation for the entire marketpla ## Workflow -1. **Discover plugins**: - - Scan plugins directory for all plugins with `.claude-plugin/` marker - - Parse each plugin's README.md to extract interface +1. **Display header** per `skills/visual-output.md` -2. **Run compatibility checks**: - - Perform pairwise compatibility validation between all plugins - - Check for command name conflicts - - Check for tool name overlaps - - Identify interface mismatches +2. **Discover plugins** per `skills/plugin-discovery.md` -3. **Validate CLAUDE.md agents**: - - Parse agent definitions from CLAUDE.md - - Validate all tool references exist - - Check data flow through agent sequences +3. **Parse interfaces** per `skills/interface-parsing.md` + - Use `parse_plugin_interface` for each plugin -4. **Generate report**: - - Summary statistics (plugins, commands, tools, issues) - - Detailed findings by severity (error, warning, info) - - Actionable suggestions for each issue +4. **Run validations** per `skills/validation-rules.md` + - Use `validate_compatibility` for pairwise checks + - Use `validate_agent_refs` for CLAUDE.md agents + - Use `validate_data_flow` for data sequences + +5. **Generate report**: + - Use `generate_compatibility_report` for full report + - Use `list_issues` to filter by severity + - Display summary and actionable suggestions ## Examples @@ -52,11 +42,3 @@ Run comprehensive cross-plugin compatibility validation for the entire marketpla /validate-contracts /validate-contracts ~/claude-plugins-work ``` - -## Available Tools - -Use these MCP tools: -- `generate_compatibility_report` - Generate full marketplace report -- `list_issues` - Filter issues by severity or type -- `parse_plugin_interface` - Parse individual plugin interface -- `validate_compatibility` - Check two plugins for conflicts diff --git a/plugins/contract-validator/skills/dependency-analysis.md b/plugins/contract-validator/skills/dependency-analysis.md new file mode 100644 index 0000000..ab0afed --- /dev/null +++ b/plugins/contract-validator/skills/dependency-analysis.md @@ -0,0 +1,57 @@ +# Skill: Dependency Analysis + +Analyze dependencies between plugins including shared MCP servers and data flows. + +## Dependency Types + +| Type | Line Style | Meaning | +|------|------------|---------| +| Required | Solid (`-->`) | Plugin cannot function without this | +| Optional | Dashed (`-.->`) | Plugin works with reduced functionality | +| Internal | Dotted (`...>`) | Self-dependency within same plugin | +| Shared MCP | Double (`==>`) | Plugins share same MCP server instance | + +## Shared MCP Server Detection + +Check each plugin's `.mcp.json` for server definitions. Plugins with identical MCP server names share that server. + +**Common shared servers:** +- `gitea` - Used by projman, pr-review +- `netbox` - Used by cmdb-assistant +- `data-platform` - Used by data-platform +- `viz-platform` - Used by viz-platform + +## Data Flow Patterns + +### Data Producers +- `read_csv`, `read_parquet`, `read_json` - File loaders +- `pg_query`, `pg_execute` - Database queries +- `filter`, `select`, `groupby`, `join` - Transformations + +### Data Consumers +- `describe`, `head`, `tail` - Data inspection +- `to_csv`, `to_parquet` - File writers +- `chart_create` - Visualization + +### Cross-Plugin Flows +| Producer | Consumer | Data Type | +|----------|----------|-----------| +| data-platform | viz-platform | `data_ref` | +| projman | pr-review | issues/lessons | +| gitea wiki | projman | lessons learned | + +## Required vs Optional + +- **Required**: Consumer has no default/fallback (ERROR if missing) +- **Optional**: Consumer works without producer (WARNING if missing) + +Determined by: +- Issue severity from `validate_data_flow` +- Tool docs stating "requires" vs "uses if available" + +## MCP Tools + +| Tool | Purpose | +|------|---------| +| `validate_data_flow` | Verify producer/consumer relationships | +| `generate_compatibility_report` | Get full dependency data | diff --git a/plugins/contract-validator/skills/interface-parsing.md b/plugins/contract-validator/skills/interface-parsing.md new file mode 100644 index 0000000..d2aab35 --- /dev/null +++ b/plugins/contract-validator/skills/interface-parsing.md @@ -0,0 +1,52 @@ +# Skill: Interface Parsing + +Parse plugin interfaces from README.md and agent definitions from CLAUDE.md. + +## Interface Components + +| Component | Source | Description | +|-----------|--------|-------------| +| Commands | README.md | Slash commands offered by plugin | +| Agents | README.md, CLAUDE.md | Autonomous agents defined | +| Tools | README.md | MCP tools provided | +| Categories | README.md | Tool groupings and features | + +## Parsing README.md + +Extract from these sections: + +1. **Commands section**: Look for tables with `| Command |` or lists of `/command-name` +2. **Tools section**: Look for tables with `| Tool |` or code blocks with tool names +3. **Agents section**: Look for "Four-Agent Model" or "Agents" headings + +## Parsing CLAUDE.md + +Extract agent definitions from: + +1. **Four-Agent Model table**: `| Agent | Personality | Responsibilities |` +2. **Agent sections**: Headings like `### Planner Agent` or `## Agents` +3. **Tool sequences**: Lists of tools in workflow steps + +## Agent Definition Structure + +```yaml +agent: + name: "Planner" + personality: "Thoughtful, methodical" + responsibilities: + - "Sprint planning" + - "Architecture analysis" + tools: + - "create_issue" + - "search_lessons" + workflow: + - step: "Analyze requirements" + tools: ["list_issues", "get_issue"] +``` + +## MCP Tools + +| Tool | Purpose | +|------|---------| +| `parse_plugin_interface` | Extract interface from README.md | +| `parse_claude_md_agents` | Extract agents and tool sequences from CLAUDE.md | diff --git a/plugins/contract-validator/skills/mcp-tools-reference.md b/plugins/contract-validator/skills/mcp-tools-reference.md new file mode 100644 index 0000000..f621c35 --- /dev/null +++ b/plugins/contract-validator/skills/mcp-tools-reference.md @@ -0,0 +1,61 @@ +# Skill: MCP Tools Reference + +Available MCP tools for contract-validator operations. + +## Tool Categories + +### Parse Tools +| Tool | Description | +|------|-------------| +| `parse_plugin_interface` | Extract interface from plugin README.md | +| `parse_claude_md_agents` | Extract agents and tool sequences from CLAUDE.md | + +### Validation Tools +| Tool | Description | +|------|-------------| +| `validate_compatibility` | Check two plugins for conflicts | +| `validate_agent_refs` | Check agent tool references exist | +| `validate_data_flow` | Verify data flow through agent sequence | + +### Report Tools +| Tool | Description | +|------|-------------| +| `generate_compatibility_report` | Generate full marketplace report (JSON) | +| `list_issues` | Filter issues by severity or type | + +## Tool Usage Patterns + +### Full Marketplace Validation +``` +1. generate_compatibility_report(marketplace_path) +2. list_issues(severity="ERROR") # Get critical issues +3. list_issues(severity="WARNING") # Get warnings +``` + +### Single Agent Check +``` +1. parse_claude_md_agents(claude_md_path) +2. validate_agent_refs(agent_name, agents_data) +3. validate_data_flow(agent_workflow) +``` + +### Interface Listing +``` +1. For each plugin: + parse_plugin_interface(readme_path) +2. Aggregate results into summary table +``` + +### Dependency Graph +``` +1. generate_compatibility_report(marketplace_path) +2. validate_data_flow(cross_plugin_flows) +3. Build Mermaid diagram from results +``` + +## Error Handling + +If MCP tools fail: +1. Check if `/initial-setup` has been run +2. Verify session was restarted after setup +3. Check MCP server venv exists and is valid diff --git a/plugins/contract-validator/skills/plugin-discovery.md b/plugins/contract-validator/skills/plugin-discovery.md new file mode 100644 index 0000000..45bee46 --- /dev/null +++ b/plugins/contract-validator/skills/plugin-discovery.md @@ -0,0 +1,42 @@ +# Skill: Plugin Discovery + +Discover plugins in a marketplace by scanning for `.claude-plugin/` markers. + +## Discovery Process + +1. **Identify marketplace root**: + - Use provided path or default to current project root + - Look for `plugins/` subdirectory + +2. **Scan for plugins**: + - Find all directories containing `.claude-plugin/plugin.json` + - Each is a valid plugin + +3. **Build plugin list**: + - Extract plugin name from directory name + - Record path to plugin root + +## Standard Paths + +| Context | Path | +|---------|------| +| Installed | `~/.claude/plugins/marketplaces/leo-claude-mktplace/plugins/` | +| Source | `~/claude-plugins-work/plugins/` | + +## Expected Structure + +``` +plugins/ + plugin-name/ + .claude-plugin/ + plugin.json # Required marker + commands/ # Command definitions + agents/ # Agent definitions (optional) + hooks/ # Hook definitions (optional) + skills/ # Skill files (optional) + README.md # Interface documentation +``` + +## MCP Tool + +Use `parse_plugin_interface` with each discovered plugin's README.md path. diff --git a/plugins/contract-validator/skills/validation-rules.md b/plugins/contract-validator/skills/validation-rules.md new file mode 100644 index 0000000..e11bdb1 --- /dev/null +++ b/plugins/contract-validator/skills/validation-rules.md @@ -0,0 +1,57 @@ +# Skill: Validation Rules + +Rules for validating plugin compatibility and agent definitions. + +## Compatibility Checks + +### 1. Command Name Conflicts +- No two plugins should have identical command names +- Severity: ERROR + +### 2. Tool Name Overlaps +- Tools with same name must have same signature +- Severity: WARNING (may be intentional aliasing) + +### 3. Interface Mismatches +- Producer output types must match consumer input types +- Severity: ERROR + +## Agent Validation + +### Tool Reference Check +1. Parse agent's tool references from workflow steps +2. Verify each tool exists in available plugins +3. Report missing or misspelled tool names +4. Suggest corrections for common mistakes + +### Data Flow Validation +1. Analyze sequence of tools in agent workflow +2. Verify data producers precede data consumers +3. Check for orphaned data references +4. Ensure required data is available at each step + +## Severity Levels + +| Level | Meaning | Action | +|-------|---------|--------| +| ERROR | Will cause runtime failures | Must fix | +| WARNING | May cause issues | Review needed | +| INFO | Informational only | No action required | + +## Common Issues + +| Issue | Cause | Fix | +|-------|-------|-----| +| Missing tool | Typo or plugin not installed | Check spelling, install plugin | +| Data flow gap | Producer not called before consumer | Reorder workflow steps | +| Name conflict | Two plugins use same command | Rename one command | +| Orphan reference | Data produced but never consumed | Remove or use the data | + +## MCP Tools + +| Tool | Purpose | +|------|---------| +| `validate_compatibility` | Check two plugins for conflicts | +| `validate_agent_refs` | Check agent tool references | +| `validate_data_flow` | Verify data flow sequences | +| `list_issues` | Filter issues by severity or type | diff --git a/plugins/contract-validator/skills/visual-output.md b/plugins/contract-validator/skills/visual-output.md new file mode 100644 index 0000000..a5a65bd --- /dev/null +++ b/plugins/contract-validator/skills/visual-output.md @@ -0,0 +1,88 @@ +# Skill: Visual Output + +Standard visual formatting for contract-validator commands. + +## Command Header + +Display at the start of every command: + +``` ++----------------------------------------------------------------------+ +| CONTRACT-VALIDATOR - [Command Name] | ++----------------------------------------------------------------------+ +``` + +## Result Boxes + +### Success Box +``` ++====================================================================+ +| CONTRACT-VALIDATOR [ACTION] COMPLETE | ++====================================================================+ +| Item 1: [checkmark] Status | +| Item 2: [checkmark] Status | ++====================================================================+ +``` + +### Error Box +``` ++====================================================================+ +| CONTRACT-VALIDATOR [ACTION] FAILED | ++====================================================================+ +| Error: [description] | +| Suggestion: [fix] | ++====================================================================+ +``` + +## Summary Tables + +### Plugin Summary +``` +| Plugin | Commands | Agents | Tools | +|-------------|----------|--------|-------| +| projman | 12 | 4 | 26 | +| data-platform| 7 | 2 | 32 | +``` + +### Issue Summary +``` +| Severity | Count | +|----------|-------| +| ERROR | 2 | +| WARNING | 5 | +| INFO | 8 | +``` + +## Mermaid Diagrams + +For dependency graphs, use flowchart TD format: + +```mermaid +flowchart TD + subgraph group_name["Group Label"] + node1["Plugin Name"] + end + + node1 -->|"label"| node2 + node1 -.->|"optional"| node3 + + classDef required stroke:#e74c3c,stroke-width:2px + classDef optional stroke:#f39c12,stroke-dasharray:5 5 +``` + +## Text Format Alternative + +For non-graphical output: + +``` +DEPENDENCY GRAPH +================ + +Plugins: 12 +MCP Servers: 4 +Dependencies: 8 (5 required, 3 optional) + +MCP Server Groups: + gitea: projman, pr-review + data-platform: data-platform +``` diff --git a/plugins/data-platform/commands/data-quality.md b/plugins/data-platform/commands/data-quality.md index cfc8d3c..fb2c211 100644 --- a/plugins/data-platform/commands/data-quality.md +++ b/plugins/data-platform/commands/data-quality.md @@ -1,18 +1,13 @@ # /data-quality - Data Quality Assessment +## Skills to Load +- skills/data-profiling.md +- skills/mcp-tools-reference.md +- skills/visual-header.md + ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📊 DATA-PLATFORM · Data Quality │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the assessment. - -Comprehensive data quality check for DataFrames with pass/warn/fail scoring. +Display header: `DATA-PLATFORM - Data Quality` ## Usage @@ -22,72 +17,18 @@ Comprehensive data quality check for DataFrames with pass/warn/fail scoring. ## Workflow -1. **Get data reference**: - - If no data_ref provided, use `list_data` to show available options - - Validate the data_ref exists +Execute `skills/data-profiling.md` quality assessment: -2. **Null analysis**: - - Calculate null percentage per column - - **PASS**: < 5% nulls - - **WARN**: 5-20% nulls - - **FAIL**: > 20% nulls - -3. **Duplicate detection**: - - Check for fully duplicated rows - - **PASS**: 0% duplicates - - **WARN**: < 1% duplicates - - **FAIL**: >= 1% duplicates - -4. **Type consistency**: - - Identify mixed-type columns (object columns with mixed content) - - Flag columns that could be numeric but contain strings - - **PASS**: All columns have consistent types - - **FAIL**: Mixed types detected - -5. **Outlier detection** (numeric columns): - - Use IQR method (values beyond 1.5 * IQR) - - Report percentage of outliers per column - - **PASS**: < 1% outliers - - **WARN**: 1-5% outliers - - **FAIL**: > 5% outliers - -6. **Generate quality report**: - - Overall quality score (0-100) - - Per-column breakdown - - Recommendations for remediation - -## Report Format - -``` -=== Data Quality Report === -Dataset: sales_data -Rows: 10,000 | Columns: 15 -Overall Score: 82/100 [PASS] - ---- Column Analysis --- -| Column | Nulls | Dups | Type | Outliers | Status | -|--------------|-------|------|----------|----------|--------| -| customer_id | 0.0% | - | int64 | 0.2% | PASS | -| email | 2.3% | - | object | - | PASS | -| amount | 15.2% | - | float64 | 3.1% | WARN | -| created_at | 0.0% | - | datetime | - | PASS | - ---- Issues Found --- -[WARN] Column 'amount': 15.2% null values (threshold: 5%) -[WARN] Column 'amount': 3.1% outliers detected -[FAIL] 1.2% duplicate rows detected (12 rows) - ---- Recommendations --- -1. Investigate null values in 'amount' column -2. Review outliers in 'amount' - may be data entry errors -3. Remove or deduplicate 12 duplicate rows -``` +1. **Get data reference**: Use `list_data` if none provided +2. **Run quality checks**: Nulls, duplicates, types, outliers +3. **Calculate score**: Apply weighted scoring formula +4. **Generate report**: Issues and recommendations ## Options | Flag | Description | |------|-------------| -| `--strict` | Use stricter thresholds (WARN at 1% nulls, FAIL at 5%) | +| `--strict` | Stricter thresholds (WARN at 1%, FAIL at 5% nulls) | ## Examples @@ -96,20 +37,12 @@ Overall Score: 82/100 [PASS] /data-quality df_customers --strict ``` -## Scoring +## Quality Thresholds -| Component | Weight | Scoring | -|-----------|--------|---------| -| Nulls | 30% | 100 - (avg_null_pct * 2) | -| Duplicates | 20% | 100 - (dup_pct * 50) | -| Type consistency | 25% | 100 if clean, 0 if mixed | -| Outliers | 25% | 100 - (avg_outlier_pct * 10) | +See `skills/data-profiling.md` for detailed thresholds and scoring. -Final score: Weighted average, capped at 0-100 +## Required MCP Tools -## Available Tools - -Use these MCP tools: -- `describe` - Get statistical summary (for outlier detection) +- `describe` - Get statistical summary - `head` - Preview data - `list_data` - List available DataFrames diff --git a/plugins/data-platform/commands/dbt-test.md b/plugins/data-platform/commands/dbt-test.md index a1b8f38..e32fc50 100644 --- a/plugins/data-platform/commands/dbt-test.md +++ b/plugins/data-platform/commands/dbt-test.md @@ -1,18 +1,13 @@ # /dbt-test - Run dbt Tests +## Skills to Load +- skills/dbt-workflow.md +- skills/mcp-tools-reference.md +- skills/visual-header.md + ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📊 DATA-PLATFORM · dbt Tests │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the tests. - -Execute dbt tests with formatted pass/fail results. +Display header: `DATA-PLATFORM - dbt Tests` ## Usage @@ -22,75 +17,17 @@ Execute dbt tests with formatted pass/fail results. ## Workflow -1. **Pre-validation** (MANDATORY): - - Use `dbt_parse` to validate project first - - If validation fails, show errors and STOP +Execute `skills/dbt-workflow.md` test workflow: -2. **Execute tests**: - - Use `dbt_test` with provided selection - - Capture all test results - -3. **Format results**: - - Group by test type (schema vs. data) - - Show pass/fail status with counts - - Display failure details - -## Report Format - -``` -=== dbt Test Results === -Project: my_project -Selection: tag:critical - ---- Summary --- -Total: 24 tests -PASS: 22 (92%) -FAIL: 1 (4%) -WARN: 1 (4%) -SKIP: 0 (0%) - ---- Schema Tests (18) --- -[PASS] unique_dim_customers_customer_id -[PASS] not_null_dim_customers_customer_id -[PASS] not_null_dim_customers_email -[PASS] accepted_values_dim_customers_status -[FAIL] relationships_fct_orders_customer_id - ---- Data Tests (6) --- -[PASS] assert_positive_order_amounts -[PASS] assert_valid_dates -[WARN] assert_recent_orders (threshold: 7 days) - ---- Failure Details --- -Test: relationships_fct_orders_customer_id -Type: schema (relationships) -Model: fct_orders -Message: 15 records failed referential integrity check -Query: SELECT * FROM fct_orders WHERE customer_id NOT IN (SELECT customer_id FROM dim_customers) - ---- Warning Details --- -Test: assert_recent_orders -Type: data -Message: No orders in last 7 days (expected for dev environment) -Severity: warn -``` - -## Selection Syntax - -| Pattern | Meaning | -|---------|---------| -| (none) | Run all tests | -| `model_name` | Tests for specific model | -| `+model_name` | Tests for model and upstream | -| `tag:critical` | Tests with tag | -| `test_type:schema` | Only schema tests | -| `test_type:data` | Only data tests | +1. **Pre-validation** (MANDATORY): Run `dbt_parse` first +2. **Execute tests**: Use `dbt_test` with selection +3. **Format results**: Group by test type, show pass/fail/warn counts ## Options | Flag | Description | |------|-------------| -| `--warn-only` | Treat failures as warnings (don't fail CI) | +| `--warn-only` | Treat failures as warnings | ## Examples @@ -98,34 +35,9 @@ Severity: warn /dbt-test # Run all tests /dbt-test dim_customers # Tests for specific model /dbt-test tag:critical # Run critical tests only -/dbt-test +fct_orders # Test model and its upstream ``` -## Test Types +## Required MCP Tools -### Schema Tests -Built-in tests defined in `schema.yml`: -- `unique` - No duplicate values -- `not_null` - No null values -- `accepted_values` - Value in allowed list -- `relationships` - Foreign key integrity - -### Data Tests -Custom SQL tests in `tests/` directory: -- Return rows that fail the assertion -- Zero rows = pass, any rows = fail - -## Exit Codes - -| Code | Meaning | -|------|---------| -| 0 | All tests passed | -| 1 | One or more tests failed | -| 2 | dbt error (parse failure, etc.) | - -## Available Tools - -Use these MCP tools: - `dbt_parse` - Pre-validation (ALWAYS RUN FIRST) - `dbt_test` - Execute tests (REQUIRED) -- `dbt_build` - Alternative: run + test together diff --git a/plugins/data-platform/commands/explain.md b/plugins/data-platform/commands/explain.md index 2f149ae..0d34273 100644 --- a/plugins/data-platform/commands/explain.md +++ b/plugins/data-platform/commands/explain.md @@ -1,18 +1,14 @@ # /explain - dbt Model Explanation +## Skills to Load +- skills/dbt-workflow.md +- skills/lineage-analysis.md +- skills/mcp-tools-reference.md +- skills/visual-header.md + ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📊 DATA-PLATFORM · Model Explanation │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the explanation. - -Explain a dbt model's purpose, dependencies, and SQL logic. +Display header: `DATA-PLATFORM - Model Explanation` ## Usage @@ -22,24 +18,10 @@ Explain a dbt model's purpose, dependencies, and SQL logic. ## Workflow -1. **Get model info**: - - Use `dbt_lineage` to get model metadata - - Extract description, tags, materialization - -2. **Analyze dependencies**: - - Show upstream models (what this depends on) - - Show downstream models (what depends on this) - - Visualize as dependency tree - -3. **Compile SQL**: - - Use `dbt_compile` to get rendered SQL - - Explain key transformations - -4. **Report**: - - Model purpose (from description) - - Materialization strategy - - Dependency graph - - Key SQL logic explained +1. **Get model info**: Use `dbt_lineage` for metadata (description, tags, materialization) +2. **Analyze dependencies**: Show upstream/downstream as tree +3. **Compile SQL**: Use `dbt_compile` to get rendered SQL +4. **Report**: Purpose, materialization, dependencies, key SQL logic ## Examples @@ -48,9 +30,8 @@ Explain a dbt model's purpose, dependencies, and SQL logic. /explain fct_orders ``` -## Available Tools +## Required MCP Tools -Use these MCP tools: - `dbt_lineage` - Get model dependencies - `dbt_compile` - Get compiled SQL - `dbt_ls` - List related resources diff --git a/plugins/data-platform/commands/ingest.md b/plugins/data-platform/commands/ingest.md index c7b2067..9089dea 100644 --- a/plugins/data-platform/commands/ingest.md +++ b/plugins/data-platform/commands/ingest.md @@ -1,18 +1,12 @@ # /ingest - Data Ingestion +## Skills to Load +- skills/mcp-tools-reference.md +- skills/visual-header.md + ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📊 DATA-PLATFORM · Ingest │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the ingestion. - -Load data from files or database into the data platform. +Display header: `DATA-PLATFORM - Ingest` ## Usage @@ -22,21 +16,17 @@ Load data from files or database into the data platform. ## Workflow -1. **Identify data source**: - - If source is a file path, determine format (CSV, Parquet, JSON) - - If source is "db" or a table name, query PostgreSQL +1. **Identify source**: + - File path: determine format (CSV, Parquet, JSON) + - SQL query or table name: query PostgreSQL 2. **Load data**: - - For files: Use `read_csv`, `read_parquet`, or `read_json` - - For database: Use `pg_query` with appropriate SELECT + - Files: `read_csv`, `read_parquet`, `read_json` + - Database: `pg_query` -3. **Validate**: - - Check row count against limits - - If exceeds 100k rows, suggest chunking or filtering +3. **Validate**: Check row count against 100k limit -4. **Report**: - - Show data_ref, row count, columns, and memory usage - - Preview first few rows +4. **Report**: data_ref, row count, columns, memory usage, preview ## Examples @@ -46,9 +36,8 @@ Load data from files or database into the data platform. /ingest "SELECT * FROM orders WHERE created_at > '2024-01-01'" ``` -## Available Tools +## Required MCP Tools -Use these MCP tools: - `read_csv` - Load CSV files - `read_parquet` - Load Parquet files - `read_json` - Load JSON/JSONL files diff --git a/plugins/data-platform/commands/initial-setup.md b/plugins/data-platform/commands/initial-setup.md index 9f9b623..a8d82b6 100644 --- a/plugins/data-platform/commands/initial-setup.md +++ b/plugins/data-platform/commands/initial-setup.md @@ -1,243 +1,49 @@ ---- -description: Interactive setup wizard for data-platform plugin - configures MCP server and optional PostgreSQL/dbt ---- +# /initial-setup - Data Platform Setup Wizard -# Data Platform Setup Wizard +## Skills to Load +- skills/setup-workflow.md +- skills/visual-header.md ## Visual Output -When executing this command, display the plugin header: +Display header: `DATA-PLATFORM - Setup Wizard` + +## Usage ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📊 DATA-PLATFORM · Setup Wizard │ -└──────────────────────────────────────────────────────────────────┘ +/initial-setup ``` -Then proceed with the setup. +## Workflow -This command sets up the data-platform plugin with pandas, PostgreSQL, and dbt integration. +Execute `skills/setup-workflow.md` phases in order: -## Important Context +### Phase 1: Environment Validation +- Check Python 3.10+ installed +- Stop if version too old -- **This command uses Bash, Read, Write, and AskUserQuestion tools** - NOT MCP tools -- **MCP tools won't work until after setup + session restart** -- **PostgreSQL and dbt are optional** - pandas tools work without them +### Phase 2: MCP Server Setup +- Locate MCP server (installed or source path) +- Check/create virtual environment +- Install dependencies if needed ---- +### Phase 3: PostgreSQL Configuration (Optional) +- Ask user if they want PostgreSQL access +- If yes: create `~/.config/claude/postgres.env` +- Test connection and report status -## Phase 1: Environment Validation +### Phase 4: dbt Configuration (Optional) +- Ask user if they use dbt +- If yes: explain auto-detection via `dbt_project.yml` +- Check dbt CLI installation -### Step 1.1: Check Python Version +### Phase 5: Validation +- Verify MCP server can be imported +- Display summary with component status +- Inform user to restart session -```bash -python3 --version -``` +## Important Notes -Requires Python 3.10+. If below, stop setup and inform user. - -### Step 1.2: Check for Required Libraries - -```bash -python3 -c "import sys; print(f'Python {sys.version_info.major}.{sys.version_info.minor}')" -``` - ---- - -## Phase 2: MCP Server Setup - -### Step 2.1: Locate Data Platform MCP Server - -The MCP server should be at the marketplace root: - -```bash -# If running from installed marketplace -ls -la ~/.claude/plugins/marketplaces/leo-claude-mktplace/mcp-servers/data-platform/ 2>/dev/null || echo "NOT_FOUND_INSTALLED" - -# If running from source -ls -la ~/claude-plugins-work/mcp-servers/data-platform/ 2>/dev/null || echo "NOT_FOUND_SOURCE" -``` - -Determine the correct path based on which exists. - -### Step 2.2: Check Virtual Environment - -```bash -ls -la /path/to/mcp-servers/data-platform/.venv/bin/python 2>/dev/null && echo "VENV_EXISTS" || echo "VENV_MISSING" -``` - -### Step 2.3: Create Virtual Environment (if missing) - -```bash -cd /path/to/mcp-servers/data-platform && python3 -m venv .venv && source .venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt && deactivate -``` - -**Note:** This may take a few minutes due to pandas, pyarrow, and dbt dependencies. - ---- - -## Phase 3: PostgreSQL Configuration (Optional) - -### Step 3.1: Ask About PostgreSQL - -Use AskUserQuestion: -- Question: "Do you want to configure PostgreSQL database access?" -- Header: "PostgreSQL" -- Options: - - "Yes, I have a PostgreSQL database" - - "No, I'll only use pandas/dbt tools" - -**If user chooses "No":** Skip to Phase 4. - -### Step 3.2: Create Config Directory - -```bash -mkdir -p ~/.config/claude -``` - -### Step 3.3: Check PostgreSQL Configuration - -```bash -cat ~/.config/claude/postgres.env 2>/dev/null || echo "FILE_NOT_FOUND" -``` - -**If file exists with valid URL:** Skip to Step 3.6. -**If missing or has placeholders:** Continue. - -### Step 3.4: Gather PostgreSQL Information - -Use AskUserQuestion: -- Question: "What is your PostgreSQL connection URL format?" -- Header: "DB Format" -- Options: - - "Standard: postgresql://user:pass@host:5432/db" - - "PostGIS: postgresql://user:pass@host:5432/db (with PostGIS extension)" - - "Other (I'll provide the full URL)" - -Ask user to provide the connection URL. - -### Step 3.5: Create Configuration File - -```bash -cat > ~/.config/claude/postgres.env << 'EOF' -# PostgreSQL Configuration -# Generated by data-platform /initial-setup - -POSTGRES_URL= -EOF -chmod 600 ~/.config/claude/postgres.env -``` - -### Step 3.6: Test PostgreSQL Connection (if configured) - -```bash -source ~/.config/claude/postgres.env && python3 -c " -import asyncio -import asyncpg -async def test(): - try: - conn = await asyncpg.connect('$POSTGRES_URL', timeout=5) - ver = await conn.fetchval('SELECT version()') - await conn.close() - print(f'SUCCESS: {ver.split(\",\")[0]}') - except Exception as e: - print(f'FAILED: {e}') -asyncio.run(test()) -" -``` - -Report result: -- SUCCESS: Connection works -- FAILED: Show error and suggest fixes - ---- - -## Phase 4: dbt Configuration (Optional) - -### Step 4.1: Ask About dbt - -Use AskUserQuestion: -- Question: "Do you use dbt for data transformations in your projects?" -- Header: "dbt" -- Options: - - "Yes, I have dbt projects" - - "No, I don't use dbt" - -**If user chooses "No":** Skip to Phase 5. - -### Step 4.2: dbt Discovery - -dbt configuration is **project-level** (not system-level). The plugin auto-detects dbt projects by looking for `dbt_project.yml`. - -Inform user: -``` -dbt projects are detected automatically when you work in a directory -containing dbt_project.yml. - -If your dbt project is in a subdirectory, you can set DBT_PROJECT_DIR -in your project's .env file: - - DBT_PROJECT_DIR=./transform - DBT_PROFILES_DIR=~/.dbt -``` - -### Step 4.3: Check dbt Installation - -```bash -dbt --version 2>/dev/null || echo "DBT_NOT_FOUND" -``` - -**If not found:** Inform user that dbt CLI tools require dbt-core to be installed globally or in the project. - ---- - -## Phase 5: Validation - -### Step 5.1: Verify MCP Server - -```bash -cd /path/to/mcp-servers/data-platform && .venv/bin/python -c "from mcp_server.server import DataPlatformMCPServer; print('MCP Server OK')" -``` - -### Step 5.2: Summary - -``` -╔════════════════════════════════════════════════════════════╗ -║ DATA-PLATFORM SETUP COMPLETE ║ -╠════════════════════════════════════════════════════════════╣ -║ MCP Server: ✓ Ready ║ -║ pandas Tools: ✓ Available (14 tools) ║ -║ PostgreSQL Tools: [✓/✗] [Status based on config] ║ -║ PostGIS Tools: [✓/✗] [Status based on PostGIS] ║ -║ dbt Tools: [✓/✗] [Status based on discovery] ║ -╚════════════════════════════════════════════════════════════╝ -``` - -### Step 5.3: Session Restart Notice - ---- - -**⚠️ Session Restart Required** - -Restart your Claude Code session for MCP tools to become available. - -**After restart, you can:** -- Run `/ingest` to load data from files or database -- Run `/profile` to analyze DataFrame statistics -- Run `/schema` to explore database/DataFrame schema -- Run `/run` to execute dbt models (if configured) -- Run `/lineage` to view dbt model dependencies - ---- - -## Memory Limits - -The data-platform plugin has a default row limit of 100,000 rows per DataFrame. For larger datasets: -- Use chunked processing (`chunk_size` parameter) -- Filter data before loading -- Store to Parquet for efficient re-loading - -You can override the limit by setting in your project `.env`: -``` -DATA_PLATFORM_MAX_ROWS=500000 -``` +- Uses Bash, Read, Write, AskUserQuestion tools (NOT MCP tools) +- MCP tools unavailable until session restart +- PostgreSQL and dbt are optional - pandas works without them diff --git a/plugins/data-platform/commands/lineage-viz.md b/plugins/data-platform/commands/lineage-viz.md index 50bad3a..2879021 100644 --- a/plugins/data-platform/commands/lineage-viz.md +++ b/plugins/data-platform/commands/lineage-viz.md @@ -1,18 +1,13 @@ # /lineage-viz - Mermaid Lineage Visualization +## Skills to Load +- skills/lineage-analysis.md +- skills/mcp-tools-reference.md +- skills/visual-header.md + ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📊 DATA-PLATFORM · Lineage Visualization │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the visualization. - -Generate Mermaid flowchart syntax for dbt model lineage. +Display header: `DATA-PLATFORM - Lineage Visualization` ## Usage @@ -22,61 +17,16 @@ Generate Mermaid flowchart syntax for dbt model lineage. ## Workflow -1. **Get lineage data**: - - Use `dbt_lineage` to fetch model dependencies - - Capture upstream sources and downstream consumers - -2. **Build Mermaid graph**: - - Create nodes for each model/source - - Style nodes by materialization type - - Add directional arrows for dependencies - -3. **Output**: - - Render Mermaid flowchart syntax - - Include copy-paste ready code block - -## Output Format - -```mermaid -flowchart LR - subgraph Sources - raw_customers[(raw_customers)] - raw_orders[(raw_orders)] - end - - subgraph Staging - stg_customers[stg_customers] - stg_orders[stg_orders] - end - - subgraph Marts - dim_customers{{dim_customers}} - fct_orders{{fct_orders}} - end - - raw_customers --> stg_customers - raw_orders --> stg_orders - stg_customers --> dim_customers - stg_orders --> fct_orders - dim_customers --> fct_orders -``` - -## Node Styles - -| Materialization | Mermaid Shape | Example | -|-----------------|---------------|---------| -| source | Cylinder `[( )]` | `raw_data[(raw_data)]` | -| view | Rectangle `[ ]` | `stg_model[stg_model]` | -| table | Double braces `{{ }}` | `dim_model{{dim_model}}` | -| incremental | Hexagon `{{ }}` | `fct_model{{fct_model}}` | -| ephemeral | Dashed `[/ /]` | `tmp_model[/tmp_model/]` | +1. **Get lineage data**: Use `dbt_lineage` to fetch model dependencies +2. **Build Mermaid graph**: Apply node shapes from `skills/lineage-analysis.md` +3. **Output**: Render copy-paste ready Mermaid flowchart ## Options | Flag | Description | |------|-------------| -| `--direction TB` | Top-to-bottom layout (default: LR = left-to-right) | -| `--depth N` | Limit lineage depth (default: unlimited) | +| `--direction TB` | Top-to-bottom layout (default: LR) | +| `--depth N` | Limit lineage depth | ## Examples @@ -86,52 +36,8 @@ flowchart LR /lineage-viz rpt_revenue --depth 2 ``` -## Usage Tips +## Required MCP Tools -1. **Paste in documentation**: Copy the output directly into README.md or docs -2. **GitHub/GitLab rendering**: Both platforms render Mermaid natively -3. **Mermaid Live Editor**: Paste at https://mermaid.live for interactive editing - -## Example Output - -For `/lineage-viz fct_orders`: - -~~~markdown -```mermaid -flowchart LR - %% Sources - raw_customers[(raw_customers)] - raw_orders[(raw_orders)] - raw_products[(raw_products)] - - %% Staging - stg_customers[stg_customers] - stg_orders[stg_orders] - stg_products[stg_products] - - %% Marts - dim_customers{{dim_customers}} - dim_products{{dim_products}} - fct_orders{{fct_orders}} - - %% Dependencies - raw_customers --> stg_customers - raw_orders --> stg_orders - raw_products --> stg_products - stg_customers --> dim_customers - stg_products --> dim_products - stg_orders --> fct_orders - dim_customers --> fct_orders - dim_products --> fct_orders - - %% Highlight target model - style fct_orders fill:#f96,stroke:#333,stroke-width:2px -``` -~~~ - -## Available Tools - -Use these MCP tools: - `dbt_lineage` - Get model dependencies (REQUIRED) - `dbt_ls` - List dbt resources - `dbt_docs_generate` - Generate full manifest if needed diff --git a/plugins/data-platform/commands/lineage.md b/plugins/data-platform/commands/lineage.md index 496937d..19eaf3a 100644 --- a/plugins/data-platform/commands/lineage.md +++ b/plugins/data-platform/commands/lineage.md @@ -1,18 +1,13 @@ # /lineage - Data Lineage Visualization +## Skills to Load +- skills/lineage-analysis.md +- skills/mcp-tools-reference.md +- skills/visual-header.md + ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📊 DATA-PLATFORM · Lineage │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the visualization. - -Show data lineage for dbt models or database tables. +Display header: `DATA-PLATFORM - Lineage` ## Usage @@ -22,24 +17,10 @@ Show data lineage for dbt models or database tables. ## Workflow -1. **Get lineage data**: - - Use `dbt_lineage` for dbt models - - For database tables, trace through dbt manifest - -2. **Build lineage graph**: - - Identify all upstream sources - - Identify all downstream consumers - - Note materialization at each node - -3. **Visualize**: - - ASCII art dependency tree - - List format with indentation - - Show depth levels - -4. **Report**: - - Full dependency chain - - Critical path identification - - Refresh implications +1. **Get lineage data**: Use `dbt_lineage` for dbt models +2. **Build lineage graph**: Identify upstream sources and downstream consumers +3. **Visualize**: ASCII tree with depth levels (see `skills/lineage-analysis.md`) +4. **Report**: Full dependency chain and refresh implications ## Examples @@ -48,25 +29,8 @@ Show data lineage for dbt models or database tables. /lineage fct_orders --depth 3 ``` -## Output Format +## Required MCP Tools -``` -Sources: - └── raw_customers (source) - └── raw_orders (source) - -dim_customers (table) - ├── upstream: - │ └── stg_customers (view) - │ └── raw_customers (source) - └── downstream: - └── fct_orders (incremental) - └── rpt_customer_lifetime (table) -``` - -## Available Tools - -Use these MCP tools: - `dbt_lineage` - Get model dependencies - `dbt_ls` - List dbt resources - `dbt_docs_generate` - Generate full manifest diff --git a/plugins/data-platform/commands/profile.md b/plugins/data-platform/commands/profile.md index c8f85cd..965c949 100644 --- a/plugins/data-platform/commands/profile.md +++ b/plugins/data-platform/commands/profile.md @@ -1,18 +1,13 @@ # /profile - Data Profiling +## Skills to Load +- skills/data-profiling.md +- skills/mcp-tools-reference.md +- skills/visual-header.md + ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📊 DATA-PLATFORM · Data Profile │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the profiling. - -Generate statistical profile and quality report for a DataFrame. +Display header: `DATA-PLATFORM - Data Profile` ## Usage @@ -22,24 +17,12 @@ Generate statistical profile and quality report for a DataFrame. ## Workflow -1. **Get data reference**: - - If no data_ref provided, use `list_data` to show available options - - Validate the data_ref exists +Execute `skills/data-profiling.md` profiling workflow: -2. **Generate profile**: - - Use `describe` for statistical summary - - Analyze null counts, unique values, data types - -3. **Quality assessment**: - - Identify columns with high null percentage - - Flag potential data quality issues - - Suggest cleaning operations if needed - -4. **Report**: - - Summary statistics per column - - Data type distribution - - Memory usage - - Quality score +1. **Get data reference**: Use `list_data` if none provided +2. **Generate profile**: Use `describe` for statistics +3. **Quality assessment**: Identify null columns, potential issues +4. **Report**: Statistics, types, memory usage, quality score ## Examples @@ -48,9 +31,8 @@ Generate statistical profile and quality report for a DataFrame. /profile df_a1b2c3d4 ``` -## Available Tools +## Required MCP Tools -Use these MCP tools: - `describe` - Get statistical summary - `head` - Preview first rows - `list_data` - List available DataFrames diff --git a/plugins/data-platform/commands/run.md b/plugins/data-platform/commands/run.md index 0698a1f..d7a3141 100644 --- a/plugins/data-platform/commands/run.md +++ b/plugins/data-platform/commands/run.md @@ -1,18 +1,13 @@ # /run - Execute dbt Models +## Skills to Load +- skills/dbt-workflow.md +- skills/mcp-tools-reference.md +- skills/visual-header.md + ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📊 DATA-PLATFORM · dbt Run │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the execution. - -Run dbt models with automatic pre-validation. +Display header: `DATA-PLATFORM - dbt Run` ## Usage @@ -22,46 +17,28 @@ Run dbt models with automatic pre-validation. ## Workflow -1. **Pre-validation** (MANDATORY): - - Use `dbt_parse` to validate project - - Check for deprecated syntax (dbt 1.9+) - - If validation fails, show errors and STOP +Execute `skills/dbt-workflow.md` run workflow: -2. **Execute models**: - - Use `dbt_run` with provided selection - - Monitor progress and capture output +1. **Pre-validation** (MANDATORY): Run `dbt_parse` first +2. **Execute models**: Use `dbt_run` with selection +3. **Report results**: Status, execution time, row counts -3. **Report results**: - - Success/failure status per model - - Execution time - - Row counts where available - - Any warnings or errors +## Selection Syntax + +See `skills/dbt-workflow.md` for full selection patterns. ## Examples ``` /run # Run all models /run dim_customers # Run specific model -/run +fct_orders # Run model and its upstream +/run +fct_orders # Run model and upstream /run tag:daily # Run models with tag /run --full-refresh # Rebuild incremental models ``` -## Selection Syntax +## Required MCP Tools -| Pattern | Meaning | -|---------|---------| -| `model_name` | Run single model | -| `+model_name` | Run model and upstream | -| `model_name+` | Run model and downstream | -| `+model_name+` | Run model with all deps | -| `tag:name` | Run by tag | -| `path:models/staging` | Run by path | - -## Available Tools - -Use these MCP tools: - `dbt_parse` - Pre-validation (ALWAYS RUN FIRST) - `dbt_run` - Execute models - `dbt_build` - Run + test -- `dbt_test` - Run tests only diff --git a/plugins/data-platform/commands/schema.md b/plugins/data-platform/commands/schema.md index 75c23ce..969921f 100644 --- a/plugins/data-platform/commands/schema.md +++ b/plugins/data-platform/commands/schema.md @@ -1,18 +1,12 @@ # /schema - Schema Exploration +## Skills to Load +- skills/mcp-tools-reference.md +- skills/visual-header.md + ## Visual Output -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📊 DATA-PLATFORM · Schema Explorer │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the exploration. - -Display schema information for database tables or DataFrames. +Display header: `DATA-PLATFORM - Schema Explorer` ## Usage @@ -23,23 +17,15 @@ Display schema information for database tables or DataFrames. ## Workflow 1. **Determine target**: - - If argument is a loaded data_ref, show DataFrame schema - - If argument is a table name, query database schema - - If no argument, list all available tables and DataFrames + - DataFrame: show pandas schema via `describe` + - Database table: query via `pg_columns` + - No argument: list all tables and DataFrames -2. **For DataFrames**: - - Use `describe` to get column info - - Show dtypes, null counts, sample values +2. **For DataFrames**: Show dtypes, null counts, sample values -3. **For database tables**: - - Use `pg_columns` for column details - - Use `st_tables` to check for PostGIS columns - - Show constraints and indexes if available +3. **For database tables**: Show columns, types, constraints, indexes -4. **Report**: - - Column name, type, nullable, default - - For PostGIS: geometry type, SRID - - For DataFrames: pandas dtype, null percentage +4. **For PostGIS**: Include geometry type and SRID via `st_tables` ## Examples @@ -49,9 +35,8 @@ Display schema information for database tables or DataFrames. /schema sales_data # Show DataFrame schema ``` -## Available Tools +## Required MCP Tools -Use these MCP tools: - `pg_tables` - List database tables - `pg_columns` - Get column info - `pg_schemas` - List schemas diff --git a/plugins/data-platform/skills/data-profiling.md b/plugins/data-platform/skills/data-profiling.md new file mode 100644 index 0000000..4ccd489 --- /dev/null +++ b/plugins/data-platform/skills/data-profiling.md @@ -0,0 +1,72 @@ +# Data Profiling + +## Profiling Workflow + +1. **Get data reference** via `list_data` +2. **Generate statistics** via `describe` +3. **Analyze quality** (nulls, duplicates, types, outliers) +4. **Calculate score** and generate report + +## Quality Checks + +### Null Analysis +- Calculate null percentage per column +- **PASS**: < 5% nulls +- **WARN**: 5-20% nulls +- **FAIL**: > 20% nulls + +### Duplicate Detection +- Check for fully duplicated rows +- **PASS**: 0% duplicates +- **WARN**: < 1% duplicates +- **FAIL**: >= 1% duplicates + +### Type Consistency +- Identify mixed-type columns +- Flag numeric columns with string values +- **PASS**: Consistent types +- **FAIL**: Mixed types detected + +### Outlier Detection (IQR Method) +- Calculate Q1, Q3, IQR = Q3 - Q1 +- Outliers: values < Q1 - 1.5*IQR or > Q3 + 1.5*IQR +- **PASS**: < 1% outliers +- **WARN**: 1-5% outliers +- **FAIL**: > 5% outliers + +## Quality Scoring + +| Component | Weight | Formula | +|-----------|--------|---------| +| Nulls | 30% | 100 - (avg_null_pct * 2) | +| Duplicates | 20% | 100 - (dup_pct * 50) | +| Type consistency | 25% | 100 if clean, 0 if mixed | +| Outliers | 25% | 100 - (avg_outlier_pct * 10) | + +Final score: Weighted average, capped at 0-100 + +## Report Format + +``` +=== Data Quality Report === +Dataset: [data_ref] +Rows: X | Columns: Y +Overall Score: XX/100 [PASS/WARN/FAIL] + +--- Column Analysis --- +| Column | Nulls | Dups | Type | Outliers | Status | +|--------|-------|------|------|----------|--------| +| col1 | X.X% | - | type | X.X% | PASS | + +--- Issues Found --- +[WARN/FAIL] Column 'X': Issue description + +--- Recommendations --- +1. Suggested remediation steps +``` + +## Strict Mode + +With `--strict` flag: +- **WARN** at 1% nulls (vs 5%) +- **FAIL** at 5% nulls (vs 20%) diff --git a/plugins/data-platform/skills/dbt-workflow.md b/plugins/data-platform/skills/dbt-workflow.md new file mode 100644 index 0000000..4604086 --- /dev/null +++ b/plugins/data-platform/skills/dbt-workflow.md @@ -0,0 +1,85 @@ +# dbt Workflow + +## Pre-Validation (MANDATORY) + +**Always run `dbt_parse` before any dbt operation.** + +This validates: +- dbt_project.yml syntax +- Model SQL syntax +- schema.yml definitions +- Deprecated syntax (dbt 1.9+) + +If validation fails, show errors and STOP. + +## Model Selection Syntax + +| Pattern | Meaning | +|---------|---------| +| `model_name` | Single model | +| `+model_name` | Model and upstream dependencies | +| `model_name+` | Model and downstream dependents | +| `+model_name+` | Model with all dependencies | +| `tag:name` | Models with specific tag | +| `path:models/staging` | Models in path | +| `test_type:schema` | Schema tests only | +| `test_type:data` | Data tests only | + +## Execution Workflow + +1. **Parse**: `dbt_parse` - Validate project +2. **Run**: `dbt_run` - Execute models +3. **Test**: `dbt_test` - Run tests +4. **Build**: `dbt_build` - Run + test together + +## Test Types + +### Schema Tests +Defined in `schema.yml`: +- `unique` - No duplicate values +- `not_null` - No null values +- `accepted_values` - Value in allowed list +- `relationships` - Foreign key integrity + +### Data Tests +Custom SQL in `tests/` directory: +- Return rows that fail assertion +- Zero rows = pass, any rows = fail + +## Materialization Types + +| Type | Description | +|------|-------------| +| `view` | Virtual table, always fresh | +| `table` | Physical table, full rebuild | +| `incremental` | Append/merge new rows only | +| `ephemeral` | CTE, no physical object | + +## Exit Codes + +| Code | Meaning | +|------|---------| +| 0 | Success | +| 1 | Test/run failure | +| 2 | dbt error (parse failure) | + +## Result Formatting + +``` +=== dbt [Operation] Results === +Project: [project_name] +Selection: [selection_pattern] + +--- Summary --- +Total: X models/tests +PASS: X (%) +FAIL: X (%) +WARN: X (%) +SKIP: X (%) + +--- Details --- +[Model/Test details with status] + +--- Failure Details --- +[Error messages and remediation] +``` diff --git a/plugins/data-platform/skills/lineage-analysis.md b/plugins/data-platform/skills/lineage-analysis.md new file mode 100644 index 0000000..8c871ec --- /dev/null +++ b/plugins/data-platform/skills/lineage-analysis.md @@ -0,0 +1,73 @@ +# Lineage Analysis + +## Lineage Workflow + +1. **Get lineage data** via `dbt_lineage` +2. **Build dependency graph** (upstream + downstream) +3. **Visualize** (ASCII tree or Mermaid) +4. **Report** critical path and refresh implications + +## ASCII Tree Format + +``` +Sources: + |-- raw_customers (source) + |-- raw_orders (source) + +model_name (materialization) + |-- upstream: + | |-- stg_model (view) + | |-- raw_source (source) + |-- downstream: + |-- fct_model (incremental) + |-- rpt_model (table) +``` + +## Mermaid Diagram Format + +```mermaid +flowchart LR + subgraph Sources + raw_data[(raw_data)] + end + + subgraph Staging + stg_model[stg_model] + end + + subgraph Marts + dim_model{{dim_model}} + end + + raw_data --> stg_model + stg_model --> dim_model +``` + +## Mermaid Node Shapes + +| Materialization | Shape | Syntax | +|-----------------|-------|--------| +| source | Cylinder | `[(name)]` | +| view | Rectangle | `[name]` | +| table | Double braces | `{{name}}` | +| incremental | Hexagon | `{{name}}` | +| ephemeral | Dashed | `[/name/]` | + +## Mermaid Options + +| Flag | Description | +|------|-------------| +| `--direction TB` | Top-to-bottom (default: LR) | +| `--depth N` | Limit lineage depth | + +## Styling Target Model + +```mermaid +style target_model fill:#f96,stroke:#333,stroke-width:2px +``` + +## Usage Tips + +1. **Documentation**: Copy Mermaid to README.md +2. **GitHub/GitLab**: Both render Mermaid natively +3. **Live Editor**: https://mermaid.live for interactive editing diff --git a/plugins/data-platform/skills/mcp-tools-reference.md b/plugins/data-platform/skills/mcp-tools-reference.md new file mode 100644 index 0000000..3b784d7 --- /dev/null +++ b/plugins/data-platform/skills/mcp-tools-reference.md @@ -0,0 +1,69 @@ +# MCP Tools Reference + +## pandas Tools + +| Tool | Description | +|------|-------------| +| `read_csv` | Load CSV file into DataFrame | +| `read_parquet` | Load Parquet file into DataFrame | +| `read_json` | Load JSON/JSONL file into DataFrame | +| `to_csv` | Export DataFrame to CSV | +| `to_parquet` | Export DataFrame to Parquet | +| `describe` | Get statistical summary (count, mean, std, min, max) | +| `head` | Preview first N rows | +| `tail` | Preview last N rows | +| `filter` | Filter rows by condition | +| `select` | Select specific columns | +| `groupby` | Aggregate data by columns | +| `join` | Join two DataFrames | +| `list_data` | List all loaded DataFrames | +| `drop_data` | Remove DataFrame from memory | + +## PostgreSQL Tools + +| Tool | Description | +|------|-------------| +| `pg_connect` | Establish database connection | +| `pg_query` | Execute SELECT query, return DataFrame | +| `pg_execute` | Execute INSERT/UPDATE/DELETE | +| `pg_tables` | List tables in schema | +| `pg_columns` | Get column info for table | +| `pg_schemas` | List available schemas | + +## PostGIS Tools + +| Tool | Description | +|------|-------------| +| `st_tables` | List tables with geometry columns | +| `st_geometry_type` | Get geometry type for column | +| `st_srid` | Get SRID for geometry column | +| `st_extent` | Get bounding box for geometry | + +## dbt Tools + +| Tool | Description | +|------|-------------| +| `dbt_parse` | Validate project (ALWAYS RUN FIRST) | +| `dbt_run` | Execute models | +| `dbt_test` | Run tests | +| `dbt_build` | Run + test together | +| `dbt_compile` | Compile SQL without execution | +| `dbt_ls` | List dbt resources | +| `dbt_docs_generate` | Generate documentation manifest | +| `dbt_lineage` | Get model dependencies | + +## Tool Selection Guidelines + +**For data loading:** +- Files: `read_csv`, `read_parquet`, `read_json` +- Database: `pg_query` + +**For data exploration:** +- Schema: `describe`, `pg_columns`, `st_tables` +- Preview: `head`, `tail` +- Available data: `list_data`, `pg_tables` + +**For dbt operations:** +- Always start with `dbt_parse` for validation +- Use `dbt_lineage` for dependency analysis +- Use `dbt_compile` to see rendered SQL diff --git a/plugins/data-platform/skills/setup-workflow.md b/plugins/data-platform/skills/setup-workflow.md new file mode 100644 index 0000000..991a1d7 --- /dev/null +++ b/plugins/data-platform/skills/setup-workflow.md @@ -0,0 +1,108 @@ +# Setup Workflow + +## Important Context + +- **This workflow uses Bash, Read, Write, AskUserQuestion tools** - NOT MCP tools +- **MCP tools won't work until after setup + session restart** +- **PostgreSQL and dbt are optional** - pandas tools work without them + +## Phase 1: Environment Validation + +### Check Python Version +```bash +python3 --version +``` +Requires Python 3.10+. If below, stop and inform user. + +## Phase 2: MCP Server Setup + +### Locate MCP Server +Check both paths: +```bash +# Installed marketplace +ls -la ~/.claude/plugins/marketplaces/leo-claude-mktplace/mcp-servers/data-platform/ + +# Source +ls -la ~/claude-plugins-work/mcp-servers/data-platform/ +``` + +### Check/Create Virtual Environment +```bash +# Check +ls -la /path/to/mcp-servers/data-platform/.venv/bin/python + +# Create if missing +cd /path/to/mcp-servers/data-platform +python3 -m venv .venv +source .venv/bin/activate +pip install --upgrade pip +pip install -r requirements.txt +deactivate +``` + +## Phase 3: PostgreSQL Configuration (Optional) + +### Config Location +`~/.config/claude/postgres.env` + +### Config Format +```bash +# PostgreSQL Configuration +POSTGRES_URL=postgresql://user:pass@host:5432/db +``` + +Set permissions: `chmod 600 ~/.config/claude/postgres.env` + +### Test Connection +```bash +source ~/.config/claude/postgres.env && python3 -c " +import asyncio, asyncpg +async def test(): + conn = await asyncpg.connect('$POSTGRES_URL', timeout=5) + ver = await conn.fetchval('SELECT version()') + await conn.close() + print(f'SUCCESS: {ver.split(\",\")[0]}') +asyncio.run(test()) +" +``` + +## Phase 4: dbt Configuration (Optional) + +dbt is **project-level** (auto-detected via `dbt_project.yml`). + +For subdirectory projects, set in `.env`: +``` +DBT_PROJECT_DIR=./transform +DBT_PROFILES_DIR=~/.dbt +``` + +### Check dbt Installation +```bash +dbt --version +``` + +## Phase 5: Validation + +### Verify MCP Server +```bash +cd /path/to/mcp-servers/data-platform +.venv/bin/python -c "from mcp_server.server import DataPlatformMCPServer; print('OK')" +``` + +## Memory Limits + +Default: 100,000 rows per DataFrame + +Override in project `.env`: +``` +DATA_PLATFORM_MAX_ROWS=500000 +``` + +For larger datasets: +- Use chunked processing (`chunk_size` parameter) +- Filter data before loading +- Store to Parquet for efficient re-loading + +## Session Restart + +After setup, restart Claude Code session for MCP tools to become available. diff --git a/plugins/data-platform/skills/visual-header.md b/plugins/data-platform/skills/visual-header.md new file mode 100644 index 0000000..98df1ac --- /dev/null +++ b/plugins/data-platform/skills/visual-header.md @@ -0,0 +1,45 @@ +# Visual Header + +## Standard Format + +Display at the start of every command execution: + +``` ++----------------------------------------------------------------------+ +| DATA-PLATFORM - [Command Name] | ++----------------------------------------------------------------------+ +``` + +## Command Headers + +| Command | Header Text | +|---------|-------------| +| initial-setup | Setup Wizard | +| ingest | Ingest | +| profile | Data Profile | +| schema | Schema Explorer | +| data-quality | Data Quality | +| run | dbt Run | +| dbt-test | dbt Tests | +| lineage | Lineage | +| lineage-viz | Lineage Visualization | +| explain | Model Explanation | + +## Summary Box Format + +For completion summaries: + +``` ++============================================================+ +| DATA-PLATFORM [OPERATION] COMPLETE | ++============================================================+ +| Component: [Status] | +| Component: [Status] | ++============================================================+ +``` + +## Status Indicators + +- Success: `[check]` or `Ready` +- Warning: `[!]` or `Partial` +- Failure: `[X]` or `Failed` diff --git a/plugins/doc-guardian/commands/changelog-gen.md b/plugins/doc-guardian/commands/changelog-gen.md index 381f058..3a89f4b 100644 --- a/plugins/doc-guardian/commands/changelog-gen.md +++ b/plugins/doc-guardian/commands/changelog-gen.md @@ -6,116 +6,49 @@ description: Generate changelog from conventional commits in Keep-a-Changelog fo Generate a changelog entry from conventional commits. +## Skills to Load + +- skills/changelog-format.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📝 DOC-GUARDIAN · Changelog Generation │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| DOC-GUARDIAN - Changelog Generation | ++------------------------------------------------------------------+ ``` -Then proceed with the generation. - ## Process 1. **Identify Commit Range** - - Default: commits since last tag - - Optional: specify range (e.g., `v1.0.0..HEAD`) - - Detect if this is first release (no previous tags) + Execute `skills/changelog-format.md` - detect range from tags 2. **Parse Conventional Commits** - Extract from commit messages following the pattern: - ``` - (): - - [optional body] - - [optional footer(s)] - ``` - - **Recognized Types:** - | Type | Changelog Section | - |------|------------------| - | `feat` | Added | - | `fix` | Fixed | - | `docs` | Documentation | - | `perf` | Performance | - | `refactor` | Changed | - | `style` | Changed | - | `test` | Testing | - | `build` | Build | - | `ci` | CI/CD | - | `chore` | Maintenance | - | `BREAKING CHANGE` | Breaking Changes | + Use pattern from skill: `(): ` 3. **Group by Type** - Organize commits into Keep-a-Changelog sections: - - Breaking Changes (if any `!` suffix or `BREAKING CHANGE` footer) - - Added (feat) - - Changed (refactor, style, perf) - - Deprecated - - Removed - - Fixed (fix) - - Security + Map to Keep-a-Changelog sections per skill 4. **Format Entries** - For each commit: - - Extract scope (if present) as prefix + - Extract scope as bold prefix - Use description as entry text - - Link to commit hash if repository URL available - - Include PR/issue references from footer + - Link commit hashes if repo URL available -5. **Output Format** -```markdown -## [Unreleased] - -### Breaking Changes -- **scope**: Description of breaking change - -### Added -- **scope**: New feature description -- Another feature without scope - -### Changed -- **scope**: Refactoring description - -### Fixed -- **scope**: Bug fix description - -### Documentation -- Updated README with new examples -``` +5. **Output** + Use format from `skills/changelog-format.md` ## Options | Flag | Description | Default | |------|-------------|---------| -| `--from ` | Start from specific tag | Latest tag | -| `--to ` | End at specific ref | HEAD | -| `--version ` | Set version header | [Unreleased] | -| `--include-merge` | Include merge commits | false | -| `--group-by-scope` | Group by scope within sections | false | +| `--from ` | Start from tag | Latest tag | +| `--to ` | End at ref | HEAD | +| `--version ` | Version header | [Unreleased] | +| `--include-merge` | Include merges | false | +| `--group-by-scope` | Group by scope | false | ## Integration -The generated output is designed to be copied directly into CHANGELOG.md: +Output designed for direct copy to CHANGELOG.md: - Follows [Keep a Changelog](https://keepachangelog.com) format - Compatible with semantic versioning -- Excludes non-user-facing commits (chore, ci, test by default) - -## Example Usage - -``` -/changelog-gen -/changelog-gen --from v1.0.0 --version 1.1.0 -/changelog-gen --include-merge --group-by-scope -``` - -## Non-Conventional Commits - -Commits not following conventional format are: -- Listed under "Other" section -- Flagged for manual categorization -- Skipped if `--strict` flag is used diff --git a/plugins/doc-guardian/commands/doc-audit.md b/plugins/doc-guardian/commands/doc-audit.md index c87d1fd..4ab8441 100644 --- a/plugins/doc-guardian/commands/doc-audit.md +++ b/plugins/doc-guardian/commands/doc-audit.md @@ -6,33 +6,26 @@ description: Full documentation audit - scans entire project for doc drift witho Perform a comprehensive documentation drift analysis. +## Skills to Load + +- skills/drift-detection.md +- skills/doc-patterns.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📝 DOC-GUARDIAN · Documentation Audit │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| DOC-GUARDIAN - Documentation Audit | ++------------------------------------------------------------------+ ``` -Then proceed with the audit. - ## Process 1. **Inventory Documentation Files** - - README.md (root and subdirectories) - - CLAUDE.md - - API documentation - - Docstrings in code files - - Configuration references + Execute `skills/doc-patterns.md` - identify all doc files 2. **Cross-Reference Analysis** - For each documentation file: - - Extract referenced functions, classes, endpoints, configs - - Verify each reference exists in codebase - - Check signatures/types match documentation - - Flag deprecated or renamed items still in docs + Execute `skills/drift-detection.md` - verify all references 3. **Completeness Check** - Public functions without docstrings @@ -40,23 +33,7 @@ Then proceed with the audit. - Environment variables used but not documented - CLI commands not in help text -4. **Output Format** -``` -## Documentation Drift Report - -### Critical (Broken References) -- [ ] README.md:45 references `calculate_total()` - function renamed to `compute_total()` - -### Stale (Outdated Info) -- [ ] CLAUDE.md:23 lists Python 3.9 - project uses 3.11 - -### Missing (Undocumented) -- [ ] api/handlers.py:`create_order()` - no docstring - -### Summary -- Critical: X items -- Stale: X items -- Missing: X items -``` +4. **Output** + Use format from `skills/drift-detection.md` 5. **Do NOT make changes** - audit only, report findings diff --git a/plugins/doc-guardian/commands/doc-coverage.md b/plugins/doc-guardian/commands/doc-coverage.md index 286959c..040147a 100644 --- a/plugins/doc-guardian/commands/doc-coverage.md +++ b/plugins/doc-guardian/commands/doc-coverage.md @@ -6,135 +6,43 @@ description: Calculate documentation coverage percentage for functions and class Analyze codebase to calculate documentation coverage metrics. +## Skills to Load + +- skills/coverage-calculation.md +- skills/doc-patterns.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📝 DOC-GUARDIAN · Documentation Coverage │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| DOC-GUARDIAN - Documentation Coverage | ++------------------------------------------------------------------+ ``` -Then proceed with the analysis. - ## Process 1. **Scan Source Files** - Identify all documentable items: - - **Python:** - - Functions (def) - - Classes - - Methods - - Module-level docstrings - - **JavaScript/TypeScript:** - - Functions (function, arrow functions) - - Classes - - Methods - - JSDoc comments - - **Other Languages:** - - Adapt patterns for Go, Rust, etc. + Execute `skills/coverage-calculation.md` - identify documentable items 2. **Determine Documentation Status** - For each item, check: - - Has docstring/JSDoc comment - - Docstring is non-empty and meaningful (not just `pass` or `TODO`) - - Parameters are documented (for detailed mode) - - Return type is documented (for detailed mode) + Check each item has meaningful docstring/JSDoc 3. **Calculate Metrics** - ``` - Coverage = (Documented Items / Total Items) * 100 - ``` + Use formula from skill: `Coverage = (Documented / Total) * 100` - **Levels:** - - Basic: Item has any docstring - - Standard: Docstring describes purpose - - Complete: All parameters and return documented - -4. **Output Format** -``` -## Documentation Coverage Report - -### Summary -- Total documentable items: 156 -- Documented: 142 -- Coverage: 91.0% - -### By Type -| Type | Total | Documented | Coverage | -|------|-------|------------|----------| -| Functions | 89 | 85 | 95.5% | -| Classes | 23 | 21 | 91.3% | -| Methods | 44 | 36 | 81.8% | - -### By Directory -| Path | Total | Documented | Coverage | -|------|-------|------------|----------| -| src/api/ | 34 | 32 | 94.1% | -| src/utils/ | 28 | 28 | 100.0% | -| src/models/ | 45 | 38 | 84.4% | -| tests/ | 49 | 44 | 89.8% | - -### Undocumented Items -- [ ] src/api/handlers.py:45 `create_order()` -- [ ] src/api/handlers.py:78 `update_order()` -- [ ] src/models/user.py:23 `UserModel.validate()` -``` +4. **Output** + Use format from `skills/coverage-calculation.md` ## Options | Flag | Description | Default | |------|-------------|---------| | `--path ` | Scan specific directory | Project root | -| `--exclude ` | Exclude files matching pattern | `**/test_*,**/*_test.*` | -| `--include-private` | Include private members (_prefixed) | false | -| `--include-tests` | Include test files | false | -| `--min-coverage ` | Fail if below threshold | none | -| `--format ` | Output format (table, json, markdown) | table | -| `--detailed` | Check parameter/return docs | false | +| `--exclude ` | Exclude pattern | `**/test_*` | +| `--min-coverage ` | Fail if below | none | +| `--detailed` | Check params/returns | false | -## Thresholds +## Exit Codes -Common coverage targets: -| Level | Coverage | Description | -|-------|----------|-------------| -| Minimal | 60% | Basic documentation exists | -| Good | 80% | Most public APIs documented | -| Excellent | 95% | Comprehensive documentation | - -## CI Integration - -Use `--min-coverage` to enforce standards: -```bash -# Fail if coverage drops below 80% -claude /doc-coverage --min-coverage 80 -``` - -Exit codes: -- 0: Coverage meets threshold (or no threshold set) +- 0: Coverage meets threshold - 1: Coverage below threshold - -## Example Usage - -``` -/doc-coverage -/doc-coverage --path src/ -/doc-coverage --min-coverage 85 --exclude "**/generated/**" -/doc-coverage --detailed --include-private -``` - -## Language Detection - -File extensions mapped to documentation patterns: -| Extension | Language | Doc Format | -|-----------|----------|------------| -| .py | Python | Docstrings (""") | -| .js, .ts | JavaScript/TypeScript | JSDoc (/** */) | -| .go | Go | // comments above | -| .rs | Rust | /// doc comments | -| .rb | Ruby | # comments, YARD | -| .java | Java | Javadoc (/** */) | diff --git a/plugins/doc-guardian/commands/doc-sync.md b/plugins/doc-guardian/commands/doc-sync.md index 5cae98d..7d47623 100644 --- a/plugins/doc-guardian/commands/doc-sync.md +++ b/plugins/doc-guardian/commands/doc-sync.md @@ -6,22 +6,23 @@ description: Synchronize all pending documentation updates in a single commit Apply all pending documentation updates detected by doc-guardian hooks. +## Skills to Load + +- skills/sync-workflow.md +- skills/drift-detection.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📝 DOC-GUARDIAN · Documentation Sync │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| DOC-GUARDIAN - Documentation Sync | ++------------------------------------------------------------------+ ``` -Then proceed with the sync. - ## Process 1. **Review Pending Queue** - List all documentation drift detected during this session. + Execute `skills/sync-workflow.md` - read `.doc-guardian-queue` 2. **Batch Updates** For each pending item: @@ -29,48 +30,13 @@ Then proceed with the sync. - Apply the update - Track in change list -3. **Update Types** - - **Reference Fixes:** - - Renamed function/class → update all doc references - - Changed signature → update parameter documentation - - Removed item → remove or mark deprecated in docs - - **Content Sync:** - - Version numbers (Python, Node, dependencies) - - Configuration keys/values - - File paths and directory structures - - Command examples and outputs - - **Structural:** - - Add missing sections for new features - - Remove sections for deleted features - - Reorder to match current code organization - -4. **Commit Strategy** +3. **Commit Strategy** - Stage all doc changes together - Single commit: `docs: sync documentation with code changes` - - Include summary of what was updated in commit body + - Include summary in commit body -5. **Clear Queue** - After successful sync, clear the queue file: - ```bash - echo "# Doc Guardian Queue - cleared after sync on $(date +%Y-%m-%d)" > .doc-guardian-queue - ``` +4. **Clear Queue** + After successful sync, clear the queue file -6. **Output** -``` -## Documentation Sync Complete - -### Files Updated -- README.md (3 changes) -- CLAUDE.md (1 change) -- src/api/README.md (2 changes) - -### Changes Applied -- Updated function reference: calculate_total → compute_total -- Updated Python version: 3.9 → 3.11 -- Added docstring to create_order() - -Committed: abc123f -``` +5. **Output** + Use format from `skills/sync-workflow.md` diff --git a/plugins/doc-guardian/commands/stale-docs.md b/plugins/doc-guardian/commands/stale-docs.md index 95dd004..bd3c857 100644 --- a/plugins/doc-guardian/commands/stale-docs.md +++ b/plugins/doc-guardian/commands/stale-docs.md @@ -6,30 +6,23 @@ description: Detect documentation files that are stale relative to their associa Identify documentation files that may be outdated based on commit history. +## Skills to Load + +- skills/staleness-metrics.md +- skills/drift-detection.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 📝 DOC-GUARDIAN · Stale Documentation Check │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| DOC-GUARDIAN - Stale Documentation Check | ++------------------------------------------------------------------+ ``` -Then proceed with the check. - ## Process 1. **Map Documentation to Code** - Build relationships between docs and code: - - | Doc File | Related Code | - |----------|--------------| - | README.md | All files in same directory | - | API.md | src/api/**/* | - | CLAUDE.md | Configuration files, scripts | - | docs/module.md | src/module/**/* | - | Component.md | Component.tsx, Component.css | + Execute `skills/staleness-metrics.md` - build relationships 2. **Analyze Commit History** For each doc file: @@ -38,118 +31,22 @@ Then proceed with the check. - Count commits to code since doc was updated 3. **Calculate Staleness** - ``` - Commits Behind = Code Commits Since Doc Update - Days Behind = Days Since Doc Update - Days Since Code Update - ``` + Use levels from skill (Fresh/Aging/Stale/Critical) -4. **Apply Threshold** - Default: Flag if documentation is 10+ commits behind related code - - **Staleness Levels:** - | Commits Behind | Level | Action | - |----------------|-------|--------| - | 0-5 | Fresh | No action needed | - | 6-10 | Aging | Review recommended | - | 11-20 | Stale | Update needed | - | 20+ | Critical | Immediate attention | - -5. **Output Format** -``` -## Stale Documentation Report - -### Critical (20+ commits behind) -| File | Last Updated | Commits Behind | Related Code | -|------|--------------|----------------|--------------| -| docs/api.md | 2024-01-15 | 34 | src/api/**/* | - -### Stale (11-20 commits behind) -| File | Last Updated | Commits Behind | Related Code | -|------|--------------|----------------|--------------| -| README.md | 2024-02-20 | 15 | package.json, src/index.ts | - -### Aging (6-10 commits behind) -| File | Last Updated | Commits Behind | Related Code | -|------|--------------|----------------|--------------| -| CONTRIBUTING.md | 2024-03-01 | 8 | .github/*, scripts/* | - -### Summary -- Critical: 1 file -- Stale: 1 file -- Aging: 1 file -- Fresh: 12 files -- Total documentation files: 15 -``` +4. **Output** + Use format from `skills/staleness-metrics.md` ## Options | Flag | Description | Default | |------|-------------|---------| -| `--threshold ` | Commits behind to flag as stale | 10 | -| `--days` | Use days instead of commits | false | -| `--path ` | Scan specific directory | Project root | -| `--doc-pattern ` | Pattern for doc files | `**/*.md,**/README*` | -| `--ignore ` | Ignore specific docs | `CHANGELOG.md,LICENSE` | -| `--show-fresh` | Include fresh docs in output | false | -| `--format ` | Output format (table, json) | table | - -## Relationship Detection - -How docs are mapped to code: - -1. **Same Directory** - - `src/api/README.md` relates to `src/api/**/*` - -2. **Name Matching** - - `docs/auth.md` relates to `**/auth.*`, `**/auth/**` - -3. **Explicit Links** - - Parse `[link](path)` in docs to find related files - -4. **Import Analysis** - - Track which modules are referenced in code examples - -## Configuration - -Create `.doc-guardian.yml` to customize mappings: -```yaml -stale-docs: - threshold: 10 - mappings: - - doc: docs/deployment.md - code: - - Dockerfile - - docker-compose.yml - - .github/workflows/deploy.yml - - doc: ARCHITECTURE.md - code: - - src/**/* - ignore: - - CHANGELOG.md - - LICENSE - - vendor/** -``` - -## Example Usage - -``` -/stale-docs -/stale-docs --threshold 5 -/stale-docs --days --threshold 30 -/stale-docs --path docs/ --show-fresh -``` - -## Integration with doc-audit - -`/stale-docs` focuses specifically on commit-based staleness, while `/doc-audit` checks content accuracy. Use both for comprehensive documentation health: - -``` -/doc-audit # Check for broken references and content drift -/stale-docs # Check for files that may need review -``` +| `--threshold ` | Commits behind to flag | 10 | +| `--days` | Use days instead | false | +| `--path ` | Scan directory | Project root | +| `--show-fresh` | Include fresh docs | false | ## Exit Codes -- 0: No critical or stale documentation -- 1: Stale documentation found (useful for CI) -- 2: Critical documentation found +- 0: No critical or stale docs +- 1: Stale docs found +- 2: Critical docs found diff --git a/plugins/doc-guardian/skills/changelog-format.md b/plugins/doc-guardian/skills/changelog-format.md new file mode 100644 index 0000000..1da053e --- /dev/null +++ b/plugins/doc-guardian/skills/changelog-format.md @@ -0,0 +1,121 @@ +--- +name: changelog-format +description: Keep a Changelog format and Conventional Commits parsing +--- + +# Changelog Format + +## Purpose + +Defines Keep a Changelog format and how to parse Conventional Commits. + +## When to Use + +- **changelog-gen**: Generating changelog entries from commits +- **git-flow integration**: Validating commit message format + +--- + +## Conventional Commits Pattern + +``` +(): + +[optional body] + +[optional footer(s)] +``` + +--- + +## Type to Section Mapping + +| Commit Type | Changelog Section | +|-------------|------------------| +| `feat` | Added | +| `fix` | Fixed | +| `docs` | Documentation | +| `perf` | Performance | +| `refactor` | Changed | +| `style` | Changed | +| `test` | Testing | +| `build` | Build | +| `ci` | CI/CD | +| `chore` | Maintenance | +| `BREAKING CHANGE` | Breaking Changes | + +--- + +## Keep a Changelog Sections + +Standard order (only include non-empty): +1. Breaking Changes +2. Added +3. Changed +4. Deprecated +5. Removed +6. Fixed +7. Security + +--- + +## Breaking Changes Detection + +Detected by: +- `!` suffix on type: `feat!: new auth system` +- `BREAKING CHANGE` in footer +- `BREAKING-CHANGE` in footer + +--- + +## Entry Formatting + +For each commit: +1. Extract scope (if present) as bold prefix: `**scope**: ` +2. Use description as entry text +3. Link to commit hash if repository URL available +4. Include PR/issue references from footer + +### Example Output + +```markdown +## [Unreleased] + +### Breaking Changes +- **auth**: Remove deprecated OAuth1 support + +### Added +- **api**: New batch processing endpoint +- User preference saving feature + +### Changed +- **core**: Improve error message clarity + +### Fixed +- **api**: Handle null values in response +``` + +--- + +## Non-Conventional Handling + +Commits not following format: +- List under "Other" section +- Flag for manual categorization +- Skip if `--strict` flag used + +--- + +## Commit Range Detection + +1. Default: commits since last tag +2. First release: all commits from initial +3. Explicit: `--from --to ` + +```bash +# Find last tag +git describe --tags --abbrev=0 + +# Commits since tag +git log v1.0.0..HEAD --oneline +``` diff --git a/plugins/doc-guardian/skills/coverage-calculation.md b/plugins/doc-guardian/skills/coverage-calculation.md new file mode 100644 index 0000000..5b389fb --- /dev/null +++ b/plugins/doc-guardian/skills/coverage-calculation.md @@ -0,0 +1,131 @@ +--- +name: coverage-calculation +description: Documentation coverage metrics, language patterns, and thresholds +--- + +# Coverage Calculation + +## Purpose + +Defines how to calculate documentation coverage and thresholds. + +## When to Use + +- **doc-coverage**: Full coverage analysis +- **doc-audit**: Completeness checks + +--- + +## Coverage Formula + +``` +Coverage = (Documented Items / Total Items) * 100 +``` + +--- + +## Documentable Items by Language + +### Python +- Functions (`def`) +- Classes +- Methods +- Module-level docstrings + +### JavaScript/TypeScript +- Functions (`function`, arrow functions) +- Classes +- Methods +- JSDoc comments (`/** */`) + +### Go +- Functions +- Types +- Methods +- Package comments (`//` above declaration) + +### Rust +- Functions +- Structs/Enums +- Impl blocks +- Doc comments (`///`) + +--- + +## Language Detection + +| Extension | Language | Doc Format | +|-----------|----------|------------| +| .py | Python | Docstrings (`"""`) | +| .js, .ts | JavaScript/TypeScript | JSDoc (`/** */`) | +| .go | Go | `//` comments above | +| .rs | Rust | `///` doc comments | +| .rb | Ruby | `#` comments, YARD | +| .java | Java | Javadoc (`/** */`) | + +--- + +## Coverage Levels + +### Basic +- Item has any docstring/comment +- Not empty or placeholder + +### Standard +- Docstring describes purpose +- Non-trivial content (not just `pass` or `TODO`) + +### Complete +- All parameters documented +- Return type documented +- Raises/throws documented + +--- + +## Coverage Thresholds + +| Level | Coverage | Description | +|-------|----------|-------------| +| Minimal | 60% | Basic documentation exists | +| Good | 80% | Most public APIs documented | +| Excellent | 95% | Comprehensive documentation | + +--- + +## Output Format + +``` +## Documentation Coverage Report + +### Summary +- Total documentable items: 156 +- Documented: 142 +- Coverage: 91.0% + +### By Type +| Type | Total | Documented | Coverage | +|------|-------|------------|----------| +| Functions | 89 | 85 | 95.5% | +| Classes | 23 | 21 | 91.3% | +| Methods | 44 | 36 | 81.8% | + +### By Directory +| Path | Total | Documented | Coverage | +|------|-------|------------|----------| +| src/api/ | 34 | 32 | 94.1% | +| src/utils/ | 28 | 28 | 100.0% | + +### Undocumented Items +- [ ] src/api/handlers.py:45 `create_order()` +- [ ] src/models/user.py:23 `UserModel.validate()` +``` + +--- + +## Exclusion Patterns + +Default exclusions: +- `**/test_*` - Test files +- `**/*_test.*` - Test files +- Private members (`_prefixed`) unless `--include-private` +- Generated code (`**/generated/**`) diff --git a/plugins/doc-guardian/skills/doc-patterns.md b/plugins/doc-guardian/skills/doc-patterns.md new file mode 100644 index 0000000..f8dac18 --- /dev/null +++ b/plugins/doc-guardian/skills/doc-patterns.md @@ -0,0 +1,67 @@ +--- +name: doc-patterns +description: Common documentation structures and patterns +--- + +# Documentation Patterns + +## Purpose + +Defines common documentation file structures and their contents. + +## When to Use + +- **doc-audit**: Understanding what to check in each doc type +- **doc-coverage**: Identifying documentation locations + +--- + +## README.md Patterns + +Typical sections: +- **Installation**: Version requirements, dependencies +- **Usage**: Function calls, CLI commands +- **Configuration**: Environment vars, config files +- **API**: Endpoint references + +--- + +## CLAUDE.md Patterns + +Typical sections: +- **Project Context**: Tech stack versions +- **File Structure**: Directory layout +- **Commands**: Available operations +- **Workflows**: Process descriptions + +--- + +## Code Documentation + +### Docstrings +- Function signatures +- Parameters and types +- Return values +- Raised exceptions + +### Type Hints +- Should match docstring types +- Verify consistency + +### Inline Comments +- References to other code +- TODO markers +- Warning notes + +--- + +## File Inventory + +Standard documentation files to check: +- `README.md` (root and subdirectories) +- `CLAUDE.md` +- `CONTRIBUTING.md` +- `CHANGELOG.md` +- `docs/**/*.md` +- API documentation +- Configuration references diff --git a/plugins/doc-guardian/skills/doc-patterns/SKILL.md b/plugins/doc-guardian/skills/doc-patterns/SKILL.md deleted file mode 100644 index ac585c2..0000000 --- a/plugins/doc-guardian/skills/doc-patterns/SKILL.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -description: Knowledge of documentation patterns and structures for drift detection ---- - -# Documentation Patterns Skill - -## Common Documentation Structures - -### README.md Patterns -- Installation section: version requirements, dependencies -- Usage section: function calls, CLI commands -- Configuration section: env vars, config files -- API section: endpoint references - -### CLAUDE.md Patterns -- Project context: tech stack versions -- File structure: directory layout -- Commands: available operations -- Workflows: process descriptions - -### Code Documentation -- Docstrings: function signatures, parameters, returns -- Type hints: should match docstring types -- Comments: inline references to other code - -## Drift Detection Rules - -1. **Version Mismatch**: Any hardcoded version in docs must match package.json, pyproject.toml, requirements.txt -2. **Function References**: Function names in docs must exist in codebase with matching signatures -3. **Path References**: File paths in docs must exist in current directory structure -4. **Config Keys**: Environment variables and config keys in docs must be used in code -5. **Command Examples**: CLI examples in docs should be valid commands - -## Priority Levels - -- **P0 (Critical)**: Broken references that would cause user errors -- **P1 (High)**: Outdated information that misleads users -- **P2 (Medium)**: Missing documentation for public interfaces -- **P3 (Low)**: Style inconsistencies, minor wording issues diff --git a/plugins/doc-guardian/skills/drift-detection.md b/plugins/doc-guardian/skills/drift-detection.md new file mode 100644 index 0000000..8baecaa --- /dev/null +++ b/plugins/doc-guardian/skills/drift-detection.md @@ -0,0 +1,102 @@ +--- +name: drift-detection +description: Core drift detection rules, cross-reference analysis, and priority levels +--- + +# Drift Detection + +## Purpose + +Defines how to detect documentation drift through cross-reference analysis. + +## When to Use + +- **doc-audit**: Full cross-reference analysis +- **stale-docs**: Commit-based staleness detection +- **SessionStart hook**: Real-time drift detection + +--- + +## Cross-Reference Analysis + +For each documentation file: +1. Extract referenced functions, classes, endpoints, configs +2. Verify each reference exists in codebase +3. Check signatures/types match documentation +4. Flag deprecated or renamed items still in docs + +--- + +## Drift Detection Rules + +| Rule | Check | Priority | +|------|-------|----------| +| Version Mismatch | Hardcoded versions must match package.json, pyproject.toml, requirements.txt | P0 | +| Function References | Function names must exist with matching signatures | P0 | +| Path References | File paths must exist in directory structure | P0 | +| Config Keys | Env vars and config keys must be used in code | P1 | +| Command Examples | CLI examples must be valid commands | P1 | + +--- + +## Priority Levels + +| Level | Description | Action | +|-------|-------------|--------| +| **P0 (Critical)** | Broken references causing user errors | Immediate fix | +| **P1 (High)** | Outdated information misleading users | Fix in current session | +| **P2 (Medium)** | Missing documentation for public interfaces | Add to backlog | +| **P3 (Low)** | Style inconsistencies, minor wording | Optional | + +--- + +## Drift Categories + +### Critical (Broken References) +- Function/class renamed but docs not updated +- File moved/deleted but docs still reference old path +- API endpoint changed but docs show old URL + +### Stale (Outdated Info) +- Version numbers not matching actual +- Configuration examples using deprecated keys +- Screenshots of old UI + +### Missing (Undocumented) +- Public functions without docstrings +- New features not in README +- Environment variables used but not documented + +--- + +## Documentation File Mapping + +| Doc File | Related Code | +|----------|--------------| +| README.md | All files in same directory | +| API.md | src/api/**/* | +| CLAUDE.md | Configuration files, scripts | +| docs/module.md | src/module/**/* | +| Component.md | Component.tsx, Component.css | + +--- + +## Output Format + +``` +## Documentation Drift Report + +### Critical (Broken References) +- [ ] README.md:45 references `calculate_total()` - function renamed to `compute_total()` + +### Stale (Outdated Info) +- [ ] CLAUDE.md:23 lists Python 3.9 - project uses 3.11 + +### Missing (Undocumented) +- [ ] api/handlers.py:`create_order()` - no docstring + +### Summary +- Critical: X items +- Stale: X items +- Missing: X items +``` diff --git a/plugins/doc-guardian/skills/staleness-metrics.md b/plugins/doc-guardian/skills/staleness-metrics.md new file mode 100644 index 0000000..a72da61 --- /dev/null +++ b/plugins/doc-guardian/skills/staleness-metrics.md @@ -0,0 +1,127 @@ +--- +name: staleness-metrics +description: Documentation staleness levels, thresholds, and relationship detection +--- + +# Staleness Metrics + +## Purpose + +Defines how to measure documentation staleness relative to code changes. + +## When to Use + +- **stale-docs**: Commit-based staleness detection +- **doc-audit**: Age-based analysis + +--- + +## Staleness Calculation + +``` +Commits Behind = Code Commits Since Doc Update +Days Behind = Days Since Doc Update - Days Since Code Update +``` + +--- + +## Staleness Levels + +| Commits Behind | Level | Action | +|----------------|-------|--------| +| 0-5 | Fresh | No action needed | +| 6-10 | Aging | Review recommended | +| 11-20 | Stale | Update needed | +| 20+ | Critical | Immediate attention | + +--- + +## Relationship Detection + +### 1. Same Directory +`src/api/README.md` relates to `src/api/**/*` + +### 2. Name Matching +`docs/auth.md` relates to `**/auth.*`, `**/auth/**` + +### 3. Explicit Links +Parse `[link](path)` in docs to find related files + +### 4. Import Analysis +Track which modules are referenced in code examples + +--- + +## Git Commands + +```bash +# Last doc commit +git log -1 --format="%H %ai" -- docs/api.md + +# Last code commit for related files +git log -1 --format="%H %ai" -- src/api/ + +# Commits to code since doc update +git rev-list ..HEAD -- src/api/ | wc -l +``` + +--- + +## Configuration + +`.doc-guardian.yml`: +```yaml +stale-docs: + threshold: 10 + mappings: + - doc: docs/deployment.md + code: + - Dockerfile + - docker-compose.yml + - .github/workflows/deploy.yml + - doc: ARCHITECTURE.md + code: + - src/**/* + ignore: + - CHANGELOG.md + - LICENSE + - vendor/** +``` + +--- + +## Output Format + +``` +## Stale Documentation Report + +### Critical (20+ commits behind) +| File | Last Updated | Commits Behind | Related Code | +|------|--------------|----------------|--------------| +| docs/api.md | 2024-01-15 | 34 | src/api/**/* | + +### Stale (11-20 commits behind) +| File | Last Updated | Commits Behind | Related Code | +|------|--------------|----------------|--------------| +| README.md | 2024-02-20 | 15 | package.json, src/index.ts | + +### Aging (6-10 commits behind) +| File | Last Updated | Commits Behind | Related Code | +|------|--------------|----------------|--------------| +| CONTRIBUTING.md | 2024-03-01 | 8 | .github/*, scripts/* | + +### Summary +- Critical: 1 file +- Stale: 1 file +- Aging: 1 file +- Fresh: 12 files +- Total documentation files: 15 +``` + +--- + +## Exit Codes + +- 0: No critical or stale documentation +- 1: Stale documentation found (for CI) +- 2: Critical documentation found diff --git a/plugins/doc-guardian/skills/sync-workflow.md b/plugins/doc-guardian/skills/sync-workflow.md new file mode 100644 index 0000000..4aff5d8 --- /dev/null +++ b/plugins/doc-guardian/skills/sync-workflow.md @@ -0,0 +1,109 @@ +--- +name: sync-workflow +description: Documentation synchronization process and queue management +--- + +# Sync Workflow + +## Purpose + +Defines how to synchronize documentation with code changes. + +## When to Use + +- **doc-sync**: Apply pending documentation updates +- **PostToolUse hook**: Queue drift for later sync + +--- + +## Queue File + +Location: `.doc-guardian-queue` in project root + +Format: +``` +# Doc Guardian Queue +# Generated: YYYY-MM-DD HH:MM:SS + +## Pending Updates +- README.md:45 | reference | calculate_total -> compute_total +- CLAUDE.md:23 | version | Python 3.9 -> 3.11 +- src/api/README.md:12 | path | old/path.py -> new/path.py +``` + +--- + +## Update Types + +### Reference Fixes +- Renamed function/class: update all doc references +- Changed signature: update parameter documentation +- Removed item: remove or mark deprecated in docs + +### Content Sync +- Version numbers (Python, Node, dependencies) +- Configuration keys/values +- File paths and directory structures +- Command examples and outputs + +### Structural +- Add missing sections for new features +- Remove sections for deleted features +- Reorder to match current code organization + +--- + +## Sync Process + +1. **Review Queue** + - Read `.doc-guardian-queue` + - List all pending items + +2. **Batch Updates** + - Apply each update + - Track in change list + +3. **Commit Strategy** + - Stage all doc changes together + - Single commit: `docs: sync documentation with code changes` + - Include summary in commit body + +4. **Clear Queue** + ```bash + echo "# Doc Guardian Queue - cleared after sync on $(date +%Y-%m-%d)" > .doc-guardian-queue + ``` + +--- + +## Output Format + +``` +## Documentation Sync Complete + +### Files Updated +- README.md (3 changes) +- CLAUDE.md (1 change) +- src/api/README.md (2 changes) + +### Changes Applied +- Updated function reference: calculate_total -> compute_total +- Updated Python version: 3.9 -> 3.11 +- Added docstring to create_order() + +Committed: abc123f +``` + +--- + +## Queue Entry Format + +``` +: | | -> +``` + +Types: +- `reference` - Function/class name change +- `version` - Version number update +- `path` - File path change +- `config` - Configuration key/value +- `missing` - New documentation needed diff --git a/plugins/git-flow/commands/branch-cleanup.md b/plugins/git-flow/commands/branch-cleanup.md index fc4c19a..d21ef4a 100644 --- a/plugins/git-flow/commands/branch-cleanup.md +++ b/plugins/git-flow/commands/branch-cleanup.md @@ -1,124 +1,44 @@ +--- +name: branch-cleanup +description: Remove merged and stale branches locally and optionally on remote +agent: git-assistant +--- + # /branch-cleanup - Clean Merged and Stale Branches -## Visual Output +## Skills -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔀 GIT-FLOW · Branch Cleanup │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the workflow. +- skills/visual-header.md +- skills/git-safety.md +- skills/sync-workflow.md +- skills/environment-variables.md ## Purpose -Remove branches that have been merged OR whose remote tracking branch no longer exists, both locally and optionally on remote. +Remove branches that have been merged OR whose remote tracking branch no longer exists. -## Behavior +## Parameters -### Step 1: Prune Remote Refs +| Parameter | Description | +|-----------|-------------| +| `--dry-run` | Preview without deleting | +| `--remote` | Also delete remote branches | +| `--stale-only` | Only delete stale branches (upstream gone) | -```bash -# Remove stale remote-tracking references -git fetch --prune -``` +## Workflow -### Step 2: Identify Branches for Cleanup - -```bash -# Find merged local branches -git branch --merged - -# Find merged remote branches -git branch -r --merged - -# Find local branches with deleted upstreams (stale) -git branch -vv | grep ': gone]' -``` - -### Step 3: Present Findings - -``` -Found branches for cleanup: - -Merged (safe to delete): - - feat/login-page (merged 3 days ago) - - fix/typo-header (merged 1 week ago) - - chore/deps-update (merged 2 weeks ago) - -Stale (remote deleted): - - feat/old-feature (upstream gone) - - fix/already-merged (upstream gone) - -Remote (merged into base): - - origin/feat/login-page - - origin/fix/typo-header - -Protected (won't delete): - - main - - development - - staging - -Delete these branches? -1. Delete all (local merged + stale + remote) -2. Delete merged only (skip stale) -3. Delete stale only (upstream gone) -4. Let me pick which ones -5. Cancel -``` - -### Step 4: Execute Cleanup - -```bash -# Delete merged local branches -git branch -d - -# Delete stale local branches (force needed since no upstream) -git branch -D - -# Delete remote branches -git push origin --delete -``` - -### Step 5: Report - -``` -Cleanup complete: - -Deleted local (merged): 3 branches -Deleted local (stale): 2 branches -Deleted remote: 2 branches -Skipped: 0 branches - -Remaining local branches: - - main - - development - - feat/current-work (not merged, has upstream) -``` - -## Environment Variables - -| Variable | Default | Description | -|----------|---------|-------------| -| `GIT_DEFAULT_BASE` | `development` | Base branch for merge detection | -| `GIT_PROTECTED_BRANCHES` | `main,master,development,staging,production` | Never delete these | -| `GIT_AUTO_DELETE_REMOTE` | `false` | Auto-delete remote branches | -| `GIT_CLEANUP_STALE` | `true` | Include stale branches (upstream gone) in cleanup | - -## Safety - -- Never deletes protected branches -- Warns about unmerged branches that still have upstreams -- Confirms before deleting remote branches -- Uses `-d` (safe delete) for merged branches -- Uses `-D` (force delete) only for stale branches with confirmation -- Stale branches are highlighted separately for review +1. **Display header** - Show GIT-FLOW Branch Cleanup header +2. **Prune remote refs** - `git fetch --prune` +3. **Find merged branches** - `git branch --merged ` +4. **Find stale branches** - `git branch -vv | grep ': gone]'` +5. **Exclude protected** - Never delete protected branches (per git-safety.md) +6. **Present findings** - Show merged, stale, and protected lists +7. **Confirm deletion** - Options: all, merged only, stale only, pick, cancel +8. **Execute cleanup** - Delete selected branches +9. **Report** - Show deletion summary ## Output -On success: ``` Cleaned up: Local (merged): 3 branches deleted diff --git a/plugins/git-flow/commands/branch-start.md b/plugins/git-flow/commands/branch-start.md index d5d198c..fae307c 100644 --- a/plugins/git-flow/commands/branch-start.md +++ b/plugins/git-flow/commands/branch-start.md @@ -1,106 +1,43 @@ +--- +name: branch-start +description: Create a new feature/fix/chore branch with consistent naming +agent: git-assistant +--- + # /branch-start - Start New Branch -## Visual Output +## Skills -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔀 GIT-FLOW · Branch Start │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the workflow. +- skills/visual-header.md +- skills/branch-naming.md +- skills/git-safety.md +- skills/environment-variables.md ## Purpose -Create a new feature/fix/chore branch with consistent naming conventions. +Create a new branch with consistent naming conventions, based on the configured base branch. -## Usage +## Parameters -``` -/branch-start [description] -``` +| Parameter | Description | +|-----------|-------------| +| `` | Brief description for branch name | +| `--type` | Branch type: feat, fix, chore, docs, refactor | +| `--issue` | Issue number to include in branch name | -## Behavior +## Workflow -### Step 1: Determine Branch Type - -``` -What type of change is this? -1. feat - New feature -2. fix - Bug fix -3. chore - Maintenance task -4. docs - Documentation -5. refactor - Code refactoring -``` - -### Step 2: Get Description - -If not provided, ask: - -``` -Brief description (2-4 words): -> add user authentication -``` - -### Step 3: Generate Branch Name - -Convert to kebab-case: -- `feat/add-user-authentication` -- `fix/login-timeout-error` -- `chore/update-dependencies` - -### Step 4: Create Branch - -```bash -# Ensure base branch is up-to-date -git checkout -git pull origin - -# Create and switch to new branch -git checkout -b -``` - -### Step 5: Confirm - -``` -Created branch: feat/add-user-authentication -Based on: development (abc1234) - -Ready to start coding! -``` - -## Environment Variables - -| Variable | Default | Description | -|----------|---------|-------------| -| `GIT_DEFAULT_BASE` | `development` | Branch to create from | -| `GIT_BRANCH_PREFIX` | `true` | Use type/ prefix | - -## Naming Rules - -- Lowercase only -- Hyphens for spaces -- No special characters -- Max 50 characters - -## Validation - -``` -Branch name validation: -✓ Lowercase -✓ Valid prefix (feat/) -✓ Descriptive (3+ words recommended) -✗ Too long (52 chars, max 50) - -Suggested: feat/add-user-auth -Use this instead? (y/n) -``` +1. **Display header** - Show GIT-FLOW Branch Start header +2. **Determine type** - Prompt for branch type if not provided +3. **Get description** - Prompt for description if not provided +4. **Generate name** - Convert to kebab-case (per branch-naming.md) +5. **Validate** - Check naming rules, truncate if needed +6. **Update base** - Checkout and pull base branch +7. **Create branch** - `git checkout -b ` +8. **Confirm** - Display created branch info ## Output -On success: ``` Branch: feat/add-user-authentication Base: development @ abc1234 diff --git a/plugins/git-flow/commands/commit-merge.md b/plugins/git-flow/commands/commit-merge.md index 91ba960..5f923b6 100644 --- a/plugins/git-flow/commands/commit-merge.md +++ b/plugins/git-flow/commands/commit-merge.md @@ -1,94 +1,49 @@ +--- +name: commit-merge +description: Commit current changes and merge branch into target +agent: git-assistant +--- + # /commit-merge - Commit and Merge -## Visual Output +## Skills -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔀 GIT-FLOW · Commit & Merge │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the workflow. +- skills/visual-header.md +- skills/commit-conventions.md +- skills/merge-workflow.md +- skills/git-safety.md +- skills/environment-variables.md ## Purpose Commit current changes, then merge the current branch into a target branch. -## Behavior +## Parameters -### Step 1: Run /commit +| Parameter | Description | +|-----------|-------------| +| `--target` | Target branch (default: GIT_DEFAULT_BASE) | +| `--squash` | Squash commits on merge | +| `--no-delete` | Keep branch after merge | -Execute the standard commit workflow. +## Workflow -### Step 2: Identify Target Branch - -Check environment or ask: - -``` -Merge into which branch? -1. development (Recommended - GIT_DEFAULT_BASE) -2. main -3. Other: ____ -``` - -### Step 3: Merge Strategy - -``` -How should I merge? -1. Merge commit (preserves history) -2. Squash and merge (single commit) -3. Rebase (linear history) -``` - -### Step 4: Execute Merge - -```bash -# Switch to target -git checkout - -# Pull latest -git pull origin - -# Merge feature branch -git merge [--squash] [--no-ff] - -# Push -git push origin -``` - -### Step 5: Cleanup (Optional) - -``` -Merge complete. Delete the feature branch? -1. Yes, delete local and remote (Recommended) -2. Delete local only -3. Keep the branch -``` - -## Environment Variables - -| Variable | Default | Description | -|----------|---------|-------------| -| `GIT_DEFAULT_BASE` | `development` | Default branch to merge into | -| `GIT_MERGE_STRATEGY` | `merge` | Default merge strategy | -| `GIT_AUTO_DELETE_MERGED` | `true` | Auto-delete merged branches | - -## Safety Checks - -- Verify target branch exists -- Check for uncommitted changes before switching -- Ensure merge doesn't conflict (preview first) +1. **Display header** - Show GIT-FLOW Commit & Merge header +2. **Run /commit** - Execute standard commit workflow +3. **Identify target** - Prompt for target branch if not specified +4. **Select strategy** - Merge commit, squash, or rebase (per merge-workflow.md) +5. **Execute merge** - Switch to target, pull, merge, push +6. **Handle conflicts** - Guide resolution if needed +7. **Cleanup** - Offer to delete merged branch (per git-safety.md) +8. **Report** - Show merge summary ## Output -On success: ``` Committed: abc1234 feat(auth): add password reset functionality -Merged feat/password-reset → development +Merged feat/password-reset -> development Deleted branch: feat/password-reset development is now at: def5678 diff --git a/plugins/git-flow/commands/commit-push.md b/plugins/git-flow/commands/commit-push.md index de552e8..29814ad 100644 --- a/plugins/git-flow/commands/commit-push.md +++ b/plugins/git-flow/commands/commit-push.md @@ -1,65 +1,42 @@ +--- +name: commit-push +description: Create a commit and push to remote in one operation +agent: git-assistant +--- + # /commit-push - Commit and Push -## Visual Output +## Skills -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔀 GIT-FLOW · Commit & Push │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the workflow. +- skills/visual-header.md +- skills/commit-conventions.md +- skills/sync-workflow.md +- skills/git-safety.md +- skills/environment-variables.md ## Purpose Create a commit and push to the remote repository in one operation. -## Behavior +## Parameters -### Step 1: Run /commit +| Parameter | Description | +|-----------|-------------| +| `--message`, `-m` | Override auto-generated message | +| `--force` | Force push (requires confirmation) | -Execute the standard commit workflow (see commit.md). +## Workflow -### Step 2: Push to Remote - -After successful commit: - -1. Check if branch has upstream tracking -2. If no upstream, set it: `git push -u origin ` -3. If upstream exists: `git push` - -### Step 3: Handle Conflicts - -If push fails due to diverged history: - -``` -Remote has changes not in your local branch. - -Options: -1. Pull and rebase, then push (Recommended) -2. Pull and merge, then push -3. Force push (⚠️ destructive) -4. Cancel and review manually -``` - -## Environment Variables - -| Variable | Default | Description | -|----------|---------|-------------| -| `GIT_AUTO_PUSH` | `true` | Auto-push after commit | -| `GIT_PUSH_STRATEGY` | `rebase` | How to handle diverged branches | - -## Safety Checks - -- **Protected branches**: Warn before pushing to main/master/production -- **Force push**: Require explicit confirmation -- **No tracking**: Ask before creating new remote branch +1. **Display header** - Show GIT-FLOW Commit & Push header +2. **Run /commit** - Execute standard commit workflow +3. **Check upstream** - Set up tracking if needed (`git push -u`) +4. **Push** - Push to remote +5. **Handle conflicts** - Offer rebase/merge/force if push fails (per sync-workflow.md) +6. **Verify safety** - Warn before push to protected branches (per git-safety.md) +7. **Report** - Show push result ## Output -On success: ``` Committed: abc1234 feat(auth): add password reset functionality diff --git a/plugins/git-flow/commands/commit-sync.md b/plugins/git-flow/commands/commit-sync.md index d8ad0f1..cf12e54 100644 --- a/plugins/git-flow/commands/commit-sync.md +++ b/plugins/git-flow/commands/commit-sync.md @@ -1,116 +1,49 @@ +--- +name: commit-sync +description: Commit, push, and sync with base branch +agent: git-assistant +--- + # /commit-sync - Commit, Push, and Sync -## Visual Output +## Skills -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔀 GIT-FLOW · Commit Sync │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the workflow. +- skills/visual-header.md +- skills/commit-conventions.md +- skills/sync-workflow.md +- skills/merge-workflow.md +- skills/environment-variables.md ## Purpose -Full sync operation: commit local changes, push to remote, sync with upstream/base branch, and clean up stale remote-tracking branches. +Full sync operation: commit local changes, push to remote, sync with upstream/base branch, and detect stale branches. -## Behavior +## Parameters -### Step 1: Run /commit +| Parameter | Description | +|-----------|-------------| +| `--base` | Override default base branch | +| `--no-rebase` | Use merge instead of rebase | -Execute the standard commit workflow. +## Workflow -### Step 2: Push to Remote - -Push committed changes to remote branch. - -### Step 3: Sync with Base - -Pull latest from base branch and rebase/merge: - -```bash -# Fetch all with prune (removes stale remote-tracking refs) -git fetch --all --prune - -# Rebase on base branch -git rebase origin/ - -# Push again (if rebased) -git push --force-with-lease -``` - -### Step 4: Detect Stale Local Branches - -Check for local branches tracking deleted remotes: - -```bash -# Find local branches with gone upstreams -git branch -vv | grep ': gone]' -``` - -If stale branches found, report them: - -``` -Stale local branches (remote deleted): - - feat/old-feature (was tracking origin/feat/old-feature) - - fix/merged-bugfix (was tracking origin/fix/merged-bugfix) - -Run /branch-cleanup to remove these branches. -``` - -### Step 5: Report Status - -``` -Sync complete: - -Local: feat/password-reset @ abc1234 -Remote: origin/feat/password-reset @ abc1234 -Base: development @ xyz7890 (synced) - -Your branch is up-to-date with development. -No conflicts detected. - -Cleanup: - Remote refs pruned: 2 - Stale local branches: 2 (run /branch-cleanup to remove) -``` - -## Environment Variables - -| Variable | Default | Description | -|----------|---------|-------------| -| `GIT_DEFAULT_BASE` | `development` | Branch to sync with | -| `GIT_SYNC_STRATEGY` | `rebase` | How to incorporate upstream changes | -| `GIT_AUTO_PRUNE` | `true` | Auto-prune stale remote refs on sync | - -## Conflict Handling - -If conflicts occur during rebase: - -``` -Conflicts detected while syncing with development. - -Conflicting files: -- src/auth/login.ts -- src/auth/types.ts - -Options: -1. Open conflict resolution (I'll guide you) -2. Abort sync (keep local state) -3. Accept all theirs (⚠️ loses your changes in conflicts) -4. Accept all ours (⚠️ ignores upstream in conflicts) -``` +1. **Display header** - Show GIT-FLOW Commit Sync header +2. **Run /commit** - Execute standard commit workflow +3. **Push to remote** - Push committed changes +4. **Fetch with prune** - `git fetch --all --prune` +5. **Sync with base** - Rebase on base branch (per sync-workflow.md) +6. **Handle conflicts** - Guide resolution if conflicts occur (per merge-workflow.md) +7. **Push again** - `git push --force-with-lease` if rebased +8. **Detect stale** - Report stale local branches +9. **Report status** - Show sync summary ## Output -On success: ``` Committed: abc1234 Pushed to: origin/feat/password-reset Synced with: development (xyz7890) Status: Clean, up-to-date -Stale branches: None (or N found - run /branch-cleanup) +Stale branches: 2 found - run /branch-cleanup ``` diff --git a/plugins/git-flow/commands/commit.md b/plugins/git-flow/commands/commit.md index abb96de..e49f48a 100644 --- a/plugins/git-flow/commands/commit.md +++ b/plugins/git-flow/commands/commit.md @@ -1,158 +1,41 @@ +--- +name: commit +description: Create a git commit with auto-generated conventional commit message +agent: git-assistant +--- + # /commit - Smart Commit -## Visual Output +## Skills -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔀 GIT-FLOW · Smart Commit │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the commit workflow. +- skills/visual-header.md +- skills/git-safety.md +- skills/commit-conventions.md +- skills/environment-variables.md ## Purpose Create a git commit with an auto-generated conventional commit message based on staged changes. -## Behavior +## Parameters -### Step 1: Check for Protected Branch +| Parameter | Description | +|-----------|-------------| +| `--message`, `-m` | Override auto-generated message | +| `--all`, `-a` | Stage all changes before commit | -Before any commit operation, check if the current branch is protected: +## Workflow -1. Get current branch: `git branch --show-current` -2. Check against `GIT_PROTECTED_BRANCHES` (default: `main,master,development,staging,production`) - -If on a protected branch, warn the user: - -``` -⚠️ You are on a protected branch: development - -Protected branches typically have push restrictions that will prevent -direct commits from being pushed to the remote. - -Options: -1. Create a feature branch and continue (Recommended) -2. Continue on this branch anyway (may fail on push) -3. Cancel -``` - -**If option 1 (create feature branch):** -- Prompt for branch type (feat/fix/chore/docs/refactor) -- Prompt for brief description -- Create branch using `/branch-start` naming conventions -- Continue with commit on the new branch - -**If option 2 (continue anyway):** -- Proceed with commit (user accepts risk of push rejection) -- Display reminder: "Remember: push may be rejected by remote protection rules" - -### Step 2: Analyze Changes - -1. Run `git status` to see staged and unstaged changes -2. Run `git diff --staged` to examine staged changes -3. If nothing staged, prompt user to stage changes - -### Step 3: Generate Commit Message - -Analyze the changes and generate a conventional commit message: - -``` -(): - -[optional body] - -[optional footer] -``` - -**Types:** -- `feat`: New feature -- `fix`: Bug fix -- `docs`: Documentation only -- `style`: Formatting, missing semicolons, etc. -- `refactor`: Code change that neither fixes a bug nor adds a feature -- `perf`: Performance improvement -- `test`: Adding/updating tests -- `chore`: Maintenance tasks -- `build`: Build system or external dependencies -- `ci`: CI configuration - -**Scope:** Determined from changed files (e.g., `auth`, `api`, `ui`) - -### Step 4: Confirm or Edit - -Present the generated message: - -``` -Proposed commit message: -─────────────────────── -feat(auth): add password reset functionality - -Implement forgot password flow with email verification. -Includes rate limiting and token expiration. -─────────────────────── - -Options: -1. Use this message (Recommended) -2. Edit the message -3. Regenerate with different focus -4. Cancel -``` - -### Step 5: Execute Commit - -If confirmed, run: - -```bash -git commit -m "$(cat <<'EOF' - - -Co-Authored-By: Claude -EOF -)" -``` - -## Environment Variables - -| Variable | Default | Description | -|----------|---------|-------------| -| `GIT_PROTECTED_BRANCHES` | `main,master,development,staging,production` | Branches that trigger protection warning | -| `GIT_COMMIT_STYLE` | `conventional` | Message style (conventional, simple, detailed) | -| `GIT_SIGN_COMMITS` | `false` | Use GPG signing | -| `GIT_CO_AUTHOR` | `true` | Include Claude co-author footer | - -## Edge Cases - -### No Changes Staged - -``` -No changes staged for commit. - -Would you like to: -1. Stage all changes (`git add -A`) -2. Stage specific files (I'll help you choose) -3. Cancel -``` - -### Untracked Files - -``` -Found 3 untracked files: -- src/new-feature.ts -- tests/new-feature.test.ts -- docs/new-feature.md - -Include these in the commit? -1. Yes, stage all (Recommended) -2. Let me pick which ones -3. No, commit only tracked files -``` +1. **Display header** - Show GIT-FLOW Smart Commit header +2. **Check protected branch** - Warn if on protected branch (per git-safety.md) +3. **Analyze changes** - Run `git status` and `git diff --staged` +4. **Handle unstaged** - Prompt to stage if nothing staged +5. **Generate message** - Create conventional commit message (per commit-conventions.md) +6. **Confirm or edit** - Present message with options to use, edit, regenerate, or cancel +7. **Execute commit** - Run `git commit` with message and co-author footer ## Output -On success: ``` Committed: abc1234 feat(auth): add password reset functionality diff --git a/plugins/git-flow/commands/git-config.md b/plugins/git-flow/commands/git-config.md index a9d19fe..d41cc02 100644 --- a/plugins/git-flow/commands/git-config.md +++ b/plugins/git-flow/commands/git-config.md @@ -1,106 +1,50 @@ +--- +name: git-config +description: Configure git-flow settings for the current project +agent: git-assistant +--- + # /git-config - Configure git-flow -## Visual Output +## Skills -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔀 GIT-FLOW · Configuration │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the configuration. +- skills/visual-header.md +- skills/environment-variables.md +- skills/workflow-patterns/branching-strategies.md ## Purpose -Configure git-flow settings for the current project. +Configure git-flow settings interactively or display current configuration. -## Behavior +## Parameters -### Interactive Configuration +| Parameter | Description | +|-----------|-------------| +| `--show` | Display current settings without prompting | +| `--reset` | Reset all settings to defaults | +| `=` | Set specific variable directly | -``` -git-flow Configuration -═══════════════════════════════════════════ +## Workflow -Current settings: - GIT_WORKFLOW_STYLE: feature-branch - GIT_DEFAULT_BASE: development - GIT_AUTO_DELETE_MERGED: true - GIT_AUTO_PUSH: false +1. **Display header** - Show GIT-FLOW Configuration header +2. **Load current settings** - Read from project and user config +3. **Present menu** - Show configuration options +4. **Handle selection** - Configure workflow style, base branch, protected branches, etc. +5. **Save settings** - Write to `.env` or `.claude/settings.json` +6. **Confirm** - Display saved configuration -What would you like to configure? -1. Workflow style +## Configuration Menu + +1. Workflow style (simple, feature-branch, pr-required, trunk-based) 2. Default base branch 3. Auto-delete merged branches 4. Auto-push after commit 5. Protected branches 6. View all settings 7. Reset to defaults -``` - -### Setting: Workflow Style - -``` -Choose your workflow style: - -1. simple - - Direct commits to development - - No feature branches required - - Good for solo projects - -2. feature-branch (Recommended) - - Feature branches from development - - Merge when complete - - Good for small teams - -3. pr-required - - Feature branches from development - - Requires PR for merge - - Good for code review workflows - -4. trunk-based - - Short-lived branches - - Frequent integration - - Good for CI/CD heavy workflows -``` - -### Setting: Protected Branches - -``` -Protected branches (comma-separated): -Current: main, master, development, staging, production - -These branches will: -- Never be auto-deleted -- Require confirmation before direct commits -- Warn before force push -``` - -## Environment Variables - -| Variable | Default | Options | -|----------|---------|---------| -| `GIT_WORKFLOW_STYLE` | `feature-branch` | simple, feature-branch, pr-required, trunk-based | -| `GIT_DEFAULT_BASE` | `development` | Any branch name | -| `GIT_AUTO_DELETE_MERGED` | `true` | true, false | -| `GIT_AUTO_PUSH` | `false` | true, false | -| `GIT_PROTECTED_BRANCHES` | `main,master,development,staging,production` | Comma-separated | -| `GIT_COMMIT_STYLE` | `conventional` | conventional, simple, detailed | -| `GIT_CO_AUTHOR` | `true` | true, false | - -## Storage - -Settings are stored in: -- Project: `.env` or `.claude/settings.json` -- User: `~/.config/claude/git-flow.env` - -Project settings override user settings. ## Output -After configuration: ``` Configuration saved! diff --git a/plugins/git-flow/commands/git-status.md b/plugins/git-flow/commands/git-status.md index 16786fa..4741b64 100644 --- a/plugins/git-flow/commands/git-status.md +++ b/plugins/git-flow/commands/git-status.md @@ -1,84 +1,56 @@ +--- +name: git-status +description: Show comprehensive git status with recommendations +agent: git-assistant +--- + # /git-status - Enhanced Status -## Visual Output +## Skills -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔀 GIT-FLOW · Status │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the status display. +- skills/visual-header.md +- skills/commit-conventions.md +- skills/environment-variables.md ## Purpose -Show comprehensive git status with recommendations and insights. +Show comprehensive git status with recommendations and insights beyond standard `git status`. -## Behavior +## Parameters -### Output Format +| Parameter | Description | +|-----------|-------------| +| `--short` | Compact output format | + +## Workflow + +1. **Display header** - Show GIT-FLOW Status header +2. **Gather info** - Branch, base comparison, remote status +3. **Categorize changes** - Staged, unstaged, untracked, deleted, renamed +4. **Generate recommendations** - What to stage, commit, sync +5. **Show quick actions** - Relevant /commands for current state + +## Output Format ``` -═══════════════════════════════════════════ Git Status: -═══════════════════════════════════════════ Branch: feat/password-reset Base: development (3 commits ahead, 0 behind) Remote: origin/feat/password-reset (synced) -─── Changes ─────────────────────────────── - +--- Changes --- Staged (ready to commit): - ✓ src/auth/reset.ts (modified) - ✓ src/auth/types.ts (modified) + [x] src/auth/reset.ts (modified) Unstaged: - • tests/auth.test.ts (modified) - • src/utils/email.ts (new file, untracked) - -─── Recommendations ─────────────────────── + [ ] tests/auth.test.ts (modified) +--- Recommendations --- 1. Stage test file: git add tests/auth.test.ts -2. Consider adding new file: git add src/utils/email.ts -3. Ready to commit with 2 staged files +2. Ready to commit with 1 staged file -─── Quick Actions ───────────────────────── - -• /commit - Commit staged changes -• /commit-push - Commit and push -• /commit-sync - Full sync with development - -═══════════════════════════════════════════ +--- Quick Actions --- +/commit - Commit staged changes +/commit-push - Commit and push ``` - -## Analysis Provided - -### Branch Health -- Commits ahead/behind base branch -- Sync status with remote -- Age of branch - -### Change Categories -- Staged (ready to commit) -- Modified (not staged) -- Untracked (new files) -- Deleted -- Renamed - -### Recommendations -- What to stage -- What to ignore -- When to commit -- When to sync - -### Warnings -- Large number of changes (consider splitting) -- Old branch (consider rebasing) -- Conflicts with upstream - -## Output - -Always produces the formatted status report with context-aware recommendations. diff --git a/plugins/git-flow/skills/branch-naming.md b/plugins/git-flow/skills/branch-naming.md new file mode 100644 index 0000000..6c2cf35 --- /dev/null +++ b/plugins/git-flow/skills/branch-naming.md @@ -0,0 +1,97 @@ +# Branch Naming + +## Purpose + +Defines branch naming conventions and validation rules for consistent repository organization. + +## When to Use + +- Creating new branches with `/branch-start` +- Validating branch names +- Converting descriptions to branch names + +## Branch Name Format + +``` +/ +``` + +## Branch Types + +| Type | Purpose | Example | +|------|---------|---------| +| `feat` | New feature | `feat/user-authentication` | +| `fix` | Bug fix | `fix/login-timeout` | +| `chore` | Maintenance | `chore/update-deps` | +| `docs` | Documentation | `docs/api-reference` | +| `refactor` | Code restructure | `refactor/auth-module` | +| `test` | Test additions | `test/auth-coverage` | +| `perf` | Performance | `perf/query-optimization` | +| `debug` | Debugging work | `debug/memory-leak` | + +## Naming Rules + +1. **Lowercase only** - Never use uppercase +2. **Hyphens for spaces** - Use `-` not `_` or ` ` +3. **No special characters** - Alphanumeric and hyphens only +4. **Descriptive** - 2-4 words recommended +5. **Max 50 characters** - Keep concise + +## Conversion Algorithm + +``` +Input: "Add User Authentication" +Output: "feat/add-user-authentication" + +Steps: +1. Lowercase: "add user authentication" +2. Replace spaces: "add-user-authentication" +3. Remove special chars: (none to remove) +4. Add prefix: "feat/add-user-authentication" +5. Truncate if > 50: (not needed) +``` + +## Validation Checks + +``` +Branch name validation: +[x] Lowercase +[x] Valid prefix (feat/) +[x] Descriptive (3+ words recommended) +[ ] Too long (52 chars, max 50) + +Suggested: feat/add-user-auth +``` + +## Examples + +**Valid:** +``` +feat/add-password-reset +fix/null-pointer-login +chore/upgrade-typescript-5 +docs/update-readme +refactor/simplify-auth +``` + +**Invalid:** +``` +Feature/Add_Password_Reset (wrong case, underscores) +fix-bug (too vague, no prefix) +my-branch (no type prefix) +feat/add-new-super-amazing-feature-for-users (too long) +``` + +## Issue-Linked Branches + +When working on issues, include issue number: +``` +feat/123-add-password-reset +fix/456-login-timeout +``` + +## Related Skills + +- skills/commit-conventions.md +- skills/git-safety.md +- skills/workflow-patterns/branching-strategies.md diff --git a/plugins/git-flow/skills/commit-conventions.md b/plugins/git-flow/skills/commit-conventions.md new file mode 100644 index 0000000..c98e4bf --- /dev/null +++ b/plugins/git-flow/skills/commit-conventions.md @@ -0,0 +1,95 @@ +# Commit Conventions + +## Purpose + +Defines conventional commit message format for consistent, parseable commit history. + +## When to Use + +- Generating commit messages in `/commit` +- Validating user-provided commit messages +- Explaining commit format to users + +## Message Format + +``` +(): + +[optional body] + +[optional footer] +``` + +## Commit Types + +| Type | Purpose | Example Scope | +|------|---------|---------------| +| `feat` | New feature | `auth`, `api`, `ui` | +| `fix` | Bug fix | `login`, `validation` | +| `docs` | Documentation only | `readme`, `api-docs` | +| `style` | Formatting, whitespace | `lint`, `format` | +| `refactor` | Code change (no bug fix, no feature) | `auth-module` | +| `perf` | Performance improvement | `query`, `cache` | +| `test` | Adding/updating tests | `unit`, `e2e` | +| `chore` | Maintenance tasks | `deps`, `build` | +| `build` | Build system or dependencies | `webpack`, `npm` | +| `ci` | CI configuration | `github-actions` | + +## Scope Detection + +Derive scope from changed files: +- `src/auth/*` -> `auth` +- `src/api/*` -> `api` +- `tests/*` -> `test` +- `docs/*` -> `docs` +- Multiple directories -> most significant or omit + +## Examples + +**Feature commit:** +``` +feat(auth): add password reset flow + +Implement forgot password with email verification. +Includes rate limiting (5 attempts/hour) and 24h token expiration. + +Closes #123 +``` + +**Bug fix:** +``` +fix(ui): resolve button alignment on mobile + +The submit button was misaligned on screens < 768px. +Added responsive flex rules. +``` + +**Maintenance:** +``` +chore(deps): update dependencies + +- typescript 5.3 -> 5.4 +- react 18.2 -> 18.3 +- node 18 -> 20 (LTS) +``` + +## Footer Conventions + +| Footer | Purpose | +|--------|---------| +| `Closes #123` | Auto-close issue | +| `Refs #123` | Reference without closing | +| `BREAKING CHANGE:` | Breaking change description | +| `Co-Authored-By:` | Credit co-author | + +## Co-Author Footer + +When Claude assists with commits: +``` +Co-Authored-By: Claude +``` + +## Related Skills + +- skills/branch-naming.md +- skills/git-safety.md diff --git a/plugins/git-flow/skills/environment-variables.md b/plugins/git-flow/skills/environment-variables.md new file mode 100644 index 0000000..7b9421b --- /dev/null +++ b/plugins/git-flow/skills/environment-variables.md @@ -0,0 +1,92 @@ +# Environment Variables + +## Purpose + +Centralized reference for all git-flow environment variables and their defaults. + +## When to Use + +- Configuring git-flow behavior in `/git-config` +- Documenting available options to users +- Setting up project-specific overrides + +## Core Variables + +| Variable | Default | Description | +|----------|---------|-------------| +| `GIT_DEFAULT_BASE` | `development` | Base branch for new branches and merges | +| `GIT_PROTECTED_BRANCHES` | `main,master,development,staging,production` | Comma-separated list of protected branches | +| `GIT_WORKFLOW_STYLE` | `feature-branch` | Workflow: simple, feature-branch, pr-required, trunk-based | + +## Commit Variables + +| Variable | Default | Description | +|----------|---------|-------------| +| `GIT_COMMIT_STYLE` | `conventional` | Message style: conventional, simple, detailed | +| `GIT_SIGN_COMMITS` | `false` | Use GPG signing | +| `GIT_CO_AUTHOR` | `true` | Include Claude co-author footer | + +## Push/Sync Variables + +| Variable | Default | Description | +|----------|---------|-------------| +| `GIT_AUTO_PUSH` | `false` | Auto-push after commit | +| `GIT_PUSH_STRATEGY` | `rebase` | Handle diverged branches: rebase, merge | +| `GIT_SYNC_STRATEGY` | `rebase` | Incorporate upstream changes: rebase, merge | +| `GIT_AUTO_PRUNE` | `true` | Auto-prune stale remote refs on sync | + +## Branch Variables + +| Variable | Default | Description | +|----------|---------|-------------| +| `GIT_BRANCH_PREFIX` | `true` | Use type/ prefix for branches | +| `GIT_AUTO_DELETE_MERGED` | `true` | Auto-delete merged branches | +| `GIT_AUTO_DELETE_REMOTE` | `false` | Auto-delete remote branches | +| `GIT_CLEANUP_STALE` | `true` | Include stale branches in cleanup | + +## Workflow Styles + +### simple +- Direct commits to main/development +- No feature branches required +- Best for: Solo projects, small scripts + +### feature-branch (Default) +- Feature branches from development +- Merge when complete +- Best for: Small teams + +### pr-required +- Feature branches from development +- Requires PR for merge +- Best for: Code review workflows + +### trunk-based +- Short-lived branches (< 1 day) +- Frequent integration +- Best for: CI/CD heavy workflows + +## Storage Locations + +| Scope | Location | Priority | +|-------|----------|----------| +| Project | `.env` or `.claude/settings.json` | Highest | +| User | `~/.config/claude/git-flow.env` | Lower | + +Project settings override user settings. + +## Example Configuration + +**.env file:** +```bash +GIT_DEFAULT_BASE=main +GIT_WORKFLOW_STYLE=pr-required +GIT_AUTO_DELETE_MERGED=true +GIT_COMMIT_STYLE=conventional +GIT_PROTECTED_BRANCHES=main,staging,production +``` + +## Related Skills + +- skills/git-safety.md +- skills/commit-conventions.md diff --git a/plugins/git-flow/skills/git-safety.md b/plugins/git-flow/skills/git-safety.md new file mode 100644 index 0000000..42d7c61 --- /dev/null +++ b/plugins/git-flow/skills/git-safety.md @@ -0,0 +1,105 @@ +# Git Safety + +## Purpose + +Defines protected branches, destructive command warnings, and safety checks to prevent accidental data loss. + +## When to Use + +- Before any commit, push, or merge operation +- When user attempts to work on protected branches +- Before executing destructive commands + +## Protected Branches + +Default protected branches (configurable via `GIT_PROTECTED_BRANCHES`): +- `main` +- `master` +- `development` +- `staging` +- `production` + +## Protection Rules + +| Action | Behavior | +|--------|----------| +| Direct commit | Warn and offer to create feature branch | +| Force push | Require explicit confirmation | +| Deletion | Block completely | +| Merge into | Allow with standard workflow | + +## Protected Branch Warning + +When committing on protected branch: + +``` +You are on a protected branch: development + +Protected branches typically have push restrictions that will prevent +direct commits from being pushed to the remote. + +Options: +1. Create a feature branch and continue (Recommended) +2. Continue on this branch anyway (may fail on push) +3. Cancel +``` + +## Destructive Commands + +Commands requiring extra confirmation: + +| Command | Risk | Mitigation | +|---------|------|------------| +| `git push --force` | Overwrites remote history | Use `--force-with-lease` | +| `git reset --hard` | Loses uncommitted changes | Warn about unsaved work | +| `git branch -D` | Deletes unmerged branch | Confirm branch name | +| `git clean -fd` | Deletes untracked files | List files first | + +## Safe Alternatives + +| Risky | Safe Alternative | +|-------|------------------| +| `git push --force` | `git push --force-with-lease` | +| `git branch -D` | `git branch -d` (merged only) | +| `git reset --hard` | `git stash` first | +| `git checkout .` | Review changes first | + +## Branch Deletion Safety + +**Merged branches (`-d`):** +```bash +git branch -d feat/old-feature # Safe: only deletes if merged +``` + +**Unmerged branches (`-D`):** +```bash +# Requires confirmation +git branch -D feat/abandoned # Force: deletes regardless +``` + +## Push Rejection Handling + +When push fails on protected branch: + +``` +Push rejected: Remote protection rules prevent direct push to development. + +Options: +1. Create a pull request instead (Recommended) +2. Review branch protection settings +3. Cancel +``` + +## Stale Branch Detection + +Branches with deleted remotes: +```bash +git branch -vv | grep ': gone]' +``` + +These are safe to delete locally with `-D` after confirmation. + +## Related Skills + +- skills/branch-naming.md +- skills/merge-workflow.md diff --git a/plugins/git-flow/skills/merge-workflow.md b/plugins/git-flow/skills/merge-workflow.md new file mode 100644 index 0000000..33cf689 --- /dev/null +++ b/plugins/git-flow/skills/merge-workflow.md @@ -0,0 +1,124 @@ +# Merge Workflow + +## Purpose + +Defines merge strategies, conflict resolution approaches, and post-merge cleanup procedures. + +## When to Use + +- Merging feature branches in `/commit-merge` +- Resolving conflicts during sync operations +- Cleaning up after successful merges + +## Merge Strategies + +### 1. Merge Commit (Default) + +```bash +git merge --no-ff +``` + +- **Preserves history** - All commits visible +- **Creates merge commit** - Clear merge point +- **Best for:** Feature branches, team workflows + +### 2. Squash and Merge + +```bash +git merge --squash +git commit -m "feat: complete feature" +``` + +- **Single commit** - Clean main branch history +- **Loses individual commits** - Combined into one +- **Best for:** PR workflows, many small commits + +### 3. Rebase + +```bash +git checkout +git rebase +git checkout +git merge --ff-only +``` + +- **Linear history** - No merge commits +- **Rewrites history** - Changes commit hashes +- **Best for:** Personal branches, clean history + +## Standard Merge Procedure + +```bash +# 1. Switch to target branch +git checkout + +# 2. Pull latest changes +git pull origin + +# 3. Merge feature branch +git merge [--squash] [--no-ff] + +# 4. Push merged result +git push origin +``` + +## Conflict Resolution + +When conflicts occur: + +``` +Conflicts detected while merging. + +Conflicting files: +- src/auth/login.ts +- src/auth/types.ts + +Options: +1. Open conflict resolution (guided) +2. Abort merge (keep local state) +3. Accept all theirs (loses your changes in conflicts) +4. Accept all ours (ignores upstream in conflicts) +``` + +### Manual Resolution Steps + +1. Open conflicting file +2. Find conflict markers: `<<<<<<<`, `=======`, `>>>>>>>` +3. Edit to desired state +4. Remove markers +5. Stage resolved file: `git add ` +6. Continue: `git merge --continue` or `git rebase --continue` + +## Post-Merge Cleanup + +After successful merge: + +``` +Merge complete. Delete the feature branch? +1. Yes, delete local and remote (Recommended) +2. Delete local only +3. Keep the branch +``` + +### Cleanup Commands + +```bash +# Delete local branch +git branch -d + +# Delete remote branch +git push origin --delete +``` + +## Pre-Merge Checks + +Before merging: +1. **Verify target exists** - `git branch -a | grep ` +2. **Check for uncommitted changes** - `git status` +3. **Preview conflicts** - `git merge --no-commit --no-ff ` +4. **Abort preview** - `git merge --abort` + +## Related Skills + +- skills/git-safety.md +- skills/sync-workflow.md diff --git a/plugins/git-flow/skills/sync-workflow.md b/plugins/git-flow/skills/sync-workflow.md new file mode 100644 index 0000000..7029812 --- /dev/null +++ b/plugins/git-flow/skills/sync-workflow.md @@ -0,0 +1,146 @@ +# Sync Workflow + +## Purpose + +Defines push/pull patterns, rebase strategies, upstream tracking, and stale branch detection. + +## When to Use + +- Pushing commits in `/commit-push` +- Full sync operations in `/commit-sync` +- Detecting and reporting stale branches + +## Push Workflow + +### First Push (No Upstream) + +```bash +git push -u origin +``` + +Sets upstream tracking for future pushes. + +### Subsequent Pushes + +```bash +git push +``` + +Pushes to tracked upstream. + +### Push After Rebase + +```bash +git push --force-with-lease +``` + +Safe force push - fails if remote has new commits. + +## Sync with Base Branch + +```bash +# 1. Fetch all with prune +git fetch --all --prune + +# 2. Rebase on base branch +git rebase origin/ + +# 3. Push (force if rebased) +git push --force-with-lease +``` + +## Push Conflict Handling + +When push fails due to diverged history: + +``` +Remote has changes not in your local branch. + +Options: +1. Pull and rebase, then push (Recommended) +2. Pull and merge, then push +3. Force push (destructive - requires confirmation) +4. Cancel and review manually +``` + +### Rebase Resolution + +```bash +git pull --rebase origin +git push +``` + +### Merge Resolution + +```bash +git pull origin +git push +``` + +## Stale Branch Detection + +Find local branches tracking deleted remotes: + +```bash +git branch -vv | grep ': gone]' +``` + +### Report Format + +``` +Stale local branches (remote deleted): + - feat/old-feature (was tracking origin/feat/old-feature) + - fix/merged-bugfix (was tracking origin/fix/merged-bugfix) + +Run /branch-cleanup to remove these branches. +``` + +## Remote Pruning + +Remove stale remote-tracking references: + +```bash +git fetch --prune +``` + +Or fetch all remotes: + +```bash +git fetch --all --prune +``` + +## Sync Status Report + +``` +Sync complete: + +Local: feat/password-reset @ abc1234 +Remote: origin/feat/password-reset @ abc1234 +Base: development @ xyz7890 (synced) + +Your branch is up-to-date with development. +No conflicts detected. + +Cleanup: + Remote refs pruned: 2 + Stale local branches: 2 (run /branch-cleanup to remove) +``` + +## Tracking Setup + +Check tracking status: + +```bash +git branch -vv +``` + +Set upstream: + +```bash +git branch --set-upstream-to=origin/ +``` + +## Related Skills + +- skills/git-safety.md +- skills/merge-workflow.md diff --git a/plugins/git-flow/skills/visual-header.md b/plugins/git-flow/skills/visual-header.md new file mode 100644 index 0000000..c84108d --- /dev/null +++ b/plugins/git-flow/skills/visual-header.md @@ -0,0 +1,84 @@ +# Visual Header + +## Purpose + +Standard header format for consistent visual output across all git-flow commands. + +## When to Use + +- At the start of every git-flow command execution +- Displaying command identity to user + +## Header Format + +``` ++----------------------------------------------------------------------+ +| GIT-FLOW [Command Name] | ++----------------------------------------------------------------------+ +``` + +## Command Headers + +### /commit +``` ++----------------------------------------------------------------------+ +| GIT-FLOW Smart Commit | ++----------------------------------------------------------------------+ +``` + +### /commit-push +``` ++----------------------------------------------------------------------+ +| GIT-FLOW Commit & Push | ++----------------------------------------------------------------------+ +``` + +### /commit-sync +``` ++----------------------------------------------------------------------+ +| GIT-FLOW Commit Sync | ++----------------------------------------------------------------------+ +``` + +### /commit-merge +``` ++----------------------------------------------------------------------+ +| GIT-FLOW Commit & Merge | ++----------------------------------------------------------------------+ +``` + +### /branch-start +``` ++----------------------------------------------------------------------+ +| GIT-FLOW Branch Start | ++----------------------------------------------------------------------+ +``` + +### /branch-cleanup +``` ++----------------------------------------------------------------------+ +| GIT-FLOW Branch Cleanup | ++----------------------------------------------------------------------+ +``` + +### /git-status +``` ++----------------------------------------------------------------------+ +| GIT-FLOW Status | ++----------------------------------------------------------------------+ +``` + +### /git-config +``` ++----------------------------------------------------------------------+ +| GIT-FLOW Configuration | ++----------------------------------------------------------------------+ +``` + +## Usage + +Display header immediately after command invocation, before any workflow steps. + +## Related Skills + +- None (standalone utility)