diff --git a/plugins/clarity-assist/commands/clarify.md b/plugins/clarity-assist/commands/clarify.md index 3069b36..7713088 100644 --- a/plugins/clarity-assist/commands/clarify.md +++ b/plugins/clarity-assist/commands/clarify.md @@ -2,16 +2,12 @@ ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 💬 CLARITY-ASSIST · Prompt Optimization │ -└──────────────────────────────────────────────────────────────────┘ ++----------------------------------------------------------------------+ +| CLARITY-ASSIST - Prompt Optimization | ++----------------------------------------------------------------------+ ``` -Then proceed with the workflow. - ## Purpose Transform vague, incomplete, or ambiguous requests into clear, actionable specifications using the 4-D methodology with neurodivergent-friendly accommodations. @@ -23,127 +19,22 @@ Transform vague, incomplete, or ambiguous requests into clear, actionable specif - Tasks requiring significant context gathering - When user seems uncertain about what they want -## 4-D Methodology +## Skills to Load -### Phase 1: Deconstruct +Load these skills before proceeding: -Break down the user's request into components: +- `skills/4d-methodology.md` - Core 4-phase process +- `skills/nd-accommodations.md` - ND-friendly question patterns +- `skills/clarification-techniques.md` - Anti-patterns and templates +- `skills/escalation-patterns.md` - When to adjust approach -1. **Extract explicit requirements** - What was directly stated -2. **Identify implicit assumptions** - What seems assumed but not stated -3. **Note ambiguities** - Points that could go multiple ways -4. **List dependencies** - External factors that might affect implementation +## Workflow -### Phase 2: Diagnose - -Analyze gaps and potential issues: - -1. **Missing information** - What do we need to know? -2. **Conflicting requirements** - Do any stated goals contradict? -3. **Scope boundaries** - What's in/out of scope? -4. **Technical constraints** - Platform, language, architecture limits - -### Phase 3: Develop - -Gather clarifications through structured questioning: - -**ND-Friendly Question Rules:** -- Present 2-4 concrete options (never open-ended alone) -- Include "Other" for custom responses -- Ask 1-2 questions at a time maximum -- Provide brief context for why you're asking -- Check for conflicts with previous answers - -**Example Format:** -``` -To help me understand the scope better: - -**How should errors be handled?** -1. Silent logging (user sees nothing) -2. Toast notifications (brief, dismissible) -3. Modal dialogs (requires user action) -4. Other - -[Context: This affects both UX and how much error-handling code we need] -``` - -### Phase 4: Deliver - -Produce the refined specification: - -```markdown -## Clarified Request - -### Summary -[1-2 sentence description of what will be built] - -### Scope -**In Scope:** -- [Item 1] -- [Item 2] - -**Out of Scope:** -- [Item 1] - -### Requirements - -| # | Requirement | Priority | Notes | -|---|-------------|----------|-------| -| 1 | ... | Must | ... | -| 2 | ... | Should | ... | - -### Assumptions -- [Assumption made based on conversation] - -### Open Questions -- [Any remaining ambiguities, if any] -``` - -## Conflict Detection - -Before each question, review previous answers for conflicts: - -``` -[Internal check] -Previous: User said "keep it simple" -Current question about: Adding configuration options -Potential conflict: More options = more complexity -→ Acknowledge: "Earlier you mentioned keeping it simple. With that in mind..." -``` - -## Escalation Protocol - -If the request is particularly messy or the user seems overwhelmed: - -1. Acknowledge the complexity -2. Offer to start with just ONE aspect -3. Build incrementally - -``` -"This touches a lot of areas. Rather than tackle everything at once, -let's start with [most critical piece]. Once that's clear, we can -add the other parts. Sound good?" -``` - -## Example Interaction - -**User:** Make the app faster - -**Clarify Response:** - -``` -Let me help clarify what kind of performance improvements you're looking for. - -**What type of slowness are you experiencing?** -1. Initial page load takes too long -2. Interactions feel sluggish (clicking, typing) -3. API calls are slow -4. All of the above -5. Other - -[I'm asking because each has very different solutions] -``` +1. **Deconstruct** - Break down request into components +2. **Diagnose** - Identify gaps and conflicts +3. **Develop** - Gather clarifications via structured questions +4. **Deliver** - Present refined specification ## Output Format -After gathering all necessary information, use the Deliver phase format to present the clarified specification for user confirmation. +Use the Deliver phase template from `skills/4d-methodology.md` to present the clarified specification for user confirmation. diff --git a/plugins/clarity-assist/commands/quick-clarify.md b/plugins/clarity-assist/commands/quick-clarify.md index 9f331b8..abfc31e 100644 --- a/plugins/clarity-assist/commands/quick-clarify.md +++ b/plugins/clarity-assist/commands/quick-clarify.md @@ -2,16 +2,12 @@ ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 💬 CLARITY-ASSIST · Quick Clarify │ -└──────────────────────────────────────────────────────────────────┘ ++----------------------------------------------------------------------+ +| CLARITY-ASSIST - Quick Clarify | ++----------------------------------------------------------------------+ ``` -Then proceed with the workflow. - ## Purpose Single-pass clarification for requests that are mostly clear but need minor disambiguation. @@ -23,74 +19,27 @@ Single-pass clarification for requests that are mostly clear but need minor disa - Follow-up to an already-clarified request - Simple feature additions or bug fixes -## Process +## Skills to Load -### Step 1: Echo Understanding +- `skills/nd-accommodations.md` - ND-friendly question patterns +- `skills/clarification-techniques.md` - Echo and micro-summary techniques +- `skills/escalation-patterns.md` - When to escalate to full /clarify -Restate what you understood in a single sentence: +## Workflow -``` -"I understand you want [X] that does [Y]." -``` - -### Step 2: Quick Disambiguation - -If needed, ask ONE multiple-choice question: - -``` -**Just to confirm:** Should this [A] or [B]? -1. [Option A with brief description] -2. [Option B with brief description] -3. Both -4. Neither / Other approach -``` - -### Step 3: Proceed or Confirm - -If confident (>90%), proceed with a brief confirmation: - -``` -"Got it. I'll implement [X with chosen option]. Starting now." -``` - -If less confident, offer a micro-summary: - -``` -"Quick summary before I start: -- [Key point 1] -- [Key point 2] -- [Assumption made] - -Proceed? (Or clarify anything)" -``` - -## Example Interaction - -**User:** Add a delete button to the user list - -**Quick-Clarify Response:** - -``` -I'll add a delete button to each row in the user list. - -**Should deletion require confirmation?** -1. Yes - show confirmation dialog (Recommended) -2. No - delete immediately -3. Soft delete - mark as deleted but keep data - -[Asking because accidental deletions can be problematic] -``` - -## Escalation to Full /clarify - -If quick-clarify reveals complexity: - -``` -"This is more involved than it first appeared - there are -several decisions to make. Want me to switch to a more -thorough clarification process? (Just say 'yes' or 'clarify')" -``` +1. **Echo Understanding** - Restate in a single sentence +2. **Quick Disambiguation** - Ask ONE multiple-choice question if needed +3. **Proceed or Confirm** - Start work or offer micro-summary ## Output Format -For quick-clarify, no formal specification document is needed. Just proceed with the task after brief confirmation, documenting assumptions inline with the work. +No formal specification document needed. Proceed after brief confirmation, documenting assumptions inline with the work. + +## Escalation + +If complexity emerges, offer to switch to full `/clarify`: + +``` +"This is more involved than it first appeared. Want me to switch +to a more thorough clarification process?" +``` diff --git a/plugins/clarity-assist/skills/4d-methodology.md b/plugins/clarity-assist/skills/4d-methodology.md new file mode 100644 index 0000000..0b34bcc --- /dev/null +++ b/plugins/clarity-assist/skills/4d-methodology.md @@ -0,0 +1,76 @@ +# 4-D Methodology for Prompt Clarification + +The 4-D methodology transforms vague requests into actionable specifications. + +## Phase 1: Deconstruct + +Break down the user's request into components: + +1. **Extract explicit requirements** - What was directly stated +2. **Identify implicit assumptions** - What seems assumed but not stated +3. **Note ambiguities** - Points that could go multiple ways +4. **List dependencies** - External factors that might affect implementation + +## Phase 2: Diagnose + +Analyze gaps and potential issues: + +1. **Missing information** - What do we need to know? +2. **Conflicting requirements** - Do any stated goals contradict? +3. **Scope boundaries** - What is in/out of scope? +4. **Technical constraints** - Platform, language, architecture limits + +## Phase 3: Develop + +Gather clarifications through structured questioning: + +- Present 2-4 concrete options (never open-ended alone) +- Include "Other" for custom responses +- Ask 1-2 questions at a time maximum +- Provide brief context for why you are asking +- Check for conflicts with previous answers + +**Example Format:** +``` +To help me understand the scope better: + +**How should errors be handled?** +1. Silent logging (user sees nothing) +2. Toast notifications (brief, dismissible) +3. Modal dialogs (requires user action) +4. Other + +[Context: This affects both UX and how much error-handling code we need] +``` + +## Phase 4: Deliver + +Produce the refined specification: + +```markdown +## Clarified Request + +### Summary +[1-2 sentence description of what will be built] + +### Scope +**In Scope:** +- [Item 1] +- [Item 2] + +**Out of Scope:** +- [Item 1] + +### Requirements + +| # | Requirement | Priority | Notes | +|---|-------------|----------|-------| +| 1 | ... | Must | ... | +| 2 | ... | Should | ... | + +### Assumptions +- [Assumption made based on conversation] + +### Open Questions +- [Any remaining ambiguities, if any] +``` diff --git a/plugins/clarity-assist/skills/clarification-techniques.md b/plugins/clarity-assist/skills/clarification-techniques.md new file mode 100644 index 0000000..011a5e3 --- /dev/null +++ b/plugins/clarity-assist/skills/clarification-techniques.md @@ -0,0 +1,86 @@ +# Clarification Techniques + +Structured approaches for disambiguating user requests. + +## Anti-Patterns to Detect + +### Vague Requests +**Triggers:** "improve", "fix", "update", "change", "better", "faster", "cleaner" + +**Response:** Ask for specific metrics or outcomes + +### Scope Creep Signals +**Triggers:** "while you're at it", "also", "might as well", "and another thing" + +**Response:** Acknowledge, then isolate: "I'll note that for after the main task" + +### Assumption Gaps +**Triggers:** References to "the" thing (which thing?), "it" (what?), "there" (where?) + +**Response:** Echo back specific understanding + +### Conflicting Requirements +**Triggers:** "Simple but comprehensive", "Fast but thorough", "Minimal but complete" + +**Response:** Prioritize: "Which matters more: simplicity or completeness?" + +## Question Templates + +### For Unclear Purpose +``` +**What problem does this solve?** +1. [Specific problem A] +2. [Specific problem B] +3. Combination +4. Different problem: ____ +``` + +### For Missing Scope +``` +**What should this include?** +- [ ] Feature A +- [ ] Feature B +- [ ] Feature C +- [ ] Other: ____ +``` + +### For Ambiguous Behavior +``` +**When [trigger event], what should happen?** +1. [Behavior option A] +2. [Behavior option B] +3. Nothing (ignore) +4. Depends on: ____ +``` + +### For Technical Decisions +``` +**Implementation approach:** +1. [Approach A] - pros: X, cons: Y +2. [Approach B] - pros: X, cons: Y +3. Let me decide based on codebase +4. Need more info about: ____ +``` + +## Echo Understanding Technique + +Before diving into questions, restate understanding: + +``` +"I understand you want [X] that does [Y]." +``` + +This validates comprehension and gives user a chance to correct early. + +## Micro-Summary Technique + +For quick confirmations before proceeding: + +``` +"Quick summary before I start: +- [Key point 1] +- [Key point 2] +- [Assumption made] + +Proceed? (Or clarify anything)" +``` diff --git a/plugins/clarity-assist/skills/escalation-patterns.md b/plugins/clarity-assist/skills/escalation-patterns.md new file mode 100644 index 0000000..eba07ab --- /dev/null +++ b/plugins/clarity-assist/skills/escalation-patterns.md @@ -0,0 +1,57 @@ +# Escalation Patterns + +Guidelines for when to escalate between clarification modes. + +## Quick-Clarify to Full Clarify + +Escalate when quick-clarify reveals unexpected complexity: + +``` +"This is more involved than it first appeared - there are +several decisions to make. Want me to switch to a more +thorough clarification process? (Just say 'yes' or 'clarify')" +``` + +### Triggers for Escalation + +- Multiple ambiguities discovered during quick pass +- User's answer reveals hidden dependencies +- Scope expands beyond original understanding +- Technical constraints emerge that need discussion +- Conflicting requirements surface + +## Full Clarify to Incremental + +When user is overwhelmed by full 4-D process: + +``` +"This touches a lot of areas. Rather than tackle everything at once, +let's start with [most critical piece]. Once that's clear, we can +add the other parts. Sound good?" +``` + +### Signs of Overwhelm + +- Long pauses or hesitation +- "I don't know" responses +- Requesting breaks +- Contradicting earlier answers +- Expressing frustration + +## Choosing Initial Mode + +### Use /quick-clarify When + +- Request is fairly clear, just one or two ambiguities +- User is in a hurry +- Follow-up to an already-clarified request +- Simple feature additions or bug fixes +- Confidence is high (>90%) + +### Use /clarify When + +- Complex multi-step requests +- Requirements with multiple possible interpretations +- Tasks requiring significant context gathering +- User seems uncertain about what they want +- First time working on this feature/area diff --git a/plugins/clarity-assist/skills/nd-accommodations.md b/plugins/clarity-assist/skills/nd-accommodations.md new file mode 100644 index 0000000..594636e --- /dev/null +++ b/plugins/clarity-assist/skills/nd-accommodations.md @@ -0,0 +1,74 @@ +# Neurodivergent-Friendly Accommodations + +Guidelines for making clarification interactions accessible and comfortable for neurodivergent users. + +## Core Principles + +### Reduce Cognitive Load +- Maximum 4 options per question +- Always include "Other" escape hatch +- Provide examples, not just descriptions +- Use numbered lists for easy reference + +### Support Working Memory +- Summarize frequently +- Reference earlier decisions explicitly +- Do not assume user remembers context from many turns ago +- Echo back understanding before proceeding + +### Allow Processing Time +- Do not rapid-fire questions +- Validate answers before moving on +- Offer to revisit or change earlier answers +- One question block at a time + +### Manage Overwhelm +- Offer to break into smaller sessions +- Prioritize must-haves vs nice-to-haves +- Provide "good enough for now" options +- Acknowledge complexity openly + +## Question Formatting Rules + +**Always do:** +``` +**How should errors be handled?** +1. Silent logging (user sees nothing) +2. Toast notifications (brief, dismissible) +3. Modal dialogs (requires user action) +4. Other + +[Context: This affects both UX and error-handling complexity] +``` + +**Never do:** +``` +How do you want to handle errors? There are many approaches... +``` + +## Conflict Acknowledgment + +Before asking about something that might conflict with a previous answer: + +``` +[Internal check] +Previous: User said "keep it simple" +Current question about: Adding configuration options +Potential conflict: More options = more complexity +``` + +Then acknowledge: "Earlier you mentioned keeping it simple. With that in mind..." + +## Escalation for Overwhelm + +If the request is particularly complex or user seems overwhelmed: + +1. Acknowledge the complexity openly +2. Offer to start with just ONE aspect +3. Build incrementally + +``` +"This touches a lot of areas. Rather than tackle everything at once, +let's start with [most critical piece]. Once that's clear, we can +add the other parts. Sound good?" +``` 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/cmdb-assistant/agents/cmdb-assistant.md b/plugins/cmdb-assistant/agents/cmdb-assistant.md index 7fb3b13..f091371 100644 --- a/plugins/cmdb-assistant/agents/cmdb-assistant.md +++ b/plugins/cmdb-assistant/agents/cmdb-assistant.md @@ -1,21 +1,20 @@ # CMDB Assistant Agent -You are an infrastructure management assistant specialized in NetBox CMDB operations. You help users query, document, and manage their network infrastructure. +You are an infrastructure management assistant specialized in NetBox CMDB operations. -## Visual Output Requirements +## Skills to Load -**MANDATORY: Display header at start of every response.** +- `skills/visual-header.md` +- `skills/netbox-patterns/SKILL.md` +- `skills/mcp-tools-reference.md` -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · Infrastructure Management │ -└──────────────────────────────────────────────────────────────────┘ -``` +## Visual Output + +Execute `skills/visual-header.md` with context "Infrastructure Management". ## Capabilities -You have full access to NetBox via MCP tools covering: - +Full access to NetBox via MCP tools covering: - **DCIM**: Sites, locations, racks, devices, interfaces, cables, power - **IPAM**: IP addresses, prefixes, VLANs, VRFs, ASNs, services - **Circuits**: Providers, circuits, terminations @@ -29,183 +28,66 @@ You have full access to NetBox via MCP tools covering: ### Query Operations - Start with list operations to find objects -- Use filters to narrow results (name, status, site_id, etc.) -- Follow up with get operations for detailed information -- Present results in clear, organized format +- Use filters to narrow results +- Follow up with get operations for details ### Create Operations -- Always confirm required fields with user before creating -- Look up related object IDs (device_type, role, site) first -- Provide the created object details after success -- Suggest follow-up actions (add interfaces, assign IPs, etc.) +- Confirm required fields before creating +- Look up related object IDs first +- Suggest follow-up actions after success ### Update Operations - Show current values before updating - Confirm changes with user -- Report what was changed after success ### Delete Operations -- ALWAYS ask for explicit confirmation before deleting -- Show what will be deleted -- Warn about dependent objects that may be affected - -## Common Workflows - -### Document a New Server -1. Create device with `dcim_create_device` -2. Add interfaces with `dcim_create_interface` -3. Assign IPs with `ipam_create_ip_address` -4. Add journal entry with `extras_create_journal_entry` - -### Allocate IP Space -1. Find available prefixes with `ipam_list_available_prefixes` -2. Create prefix with `ipam_create_prefix` or `ipam_create_available_prefix` -3. Allocate IPs with `ipam_create_available_ip` - -### Audit Infrastructure -1. List recent changes with `extras_list_object_changes` -2. Review devices by site with `dcim_list_devices` -3. Check IP utilization with prefix operations - -### Cable Management -1. List interfaces with `dcim_list_interfaces` -2. Create cable with `dcim_create_cable` -3. Verify connectivity - -## Response Format - -When presenting data: -- Use tables for lists -- Highlight key fields (name, status, IPs) -- Include IDs for reference in follow-up operations -- Suggest next steps when appropriate - -## Error Handling - -- If an operation fails, explain why clearly -- Suggest corrective actions -- For permission errors, note what access is needed -- For validation errors, explain required fields/formats +- ALWAYS ask for explicit confirmation +- Warn about dependent objects ## Data Quality Validation -**IMPORTANT:** Load the `netbox-patterns` skill for best practice reference. +Reference `skills/netbox-patterns/SKILL.md` for best practices: -Before ANY create or update operation, validate against NetBox best practices: +### Before VM Operations +1. Cluster/Site assignment required +2. Recommend tenant if not provided +3. Check naming convention -### VM Operations +### Before Device Operations +1. Site is REQUIRED +2. Recommend platform +3. Check naming convention +4. Offer to set primary IP after creation -**Required checks before `virt_create_vm` or `virt_update_vm`:** +### Before Creating Roles +1. List existing roles first +2. Recommend consolidation if >10 specific roles -1. **Cluster/Site Assignment** - VMs must have either cluster or site -2. **Tenant Assignment** - Recommend if not provided -3. **Platform Assignment** - Recommend for OS tracking -4. **Naming Convention** - Check against `{env}-{app}-{number}` pattern -5. **Role Assignment** - Recommend appropriate role - -**If user provides no site/tenant, ASK:** - -> "This VM has no site or tenant assigned. NetBox best practices recommend: -> - **Site**: For location-based queries and power budgeting -> - **Tenant**: For resource isolation and ownership tracking -> -> Would you like me to: -> 1. Assign to an existing site/tenant (list available) -> 2. Create new site/tenant first -> 3. Proceed without (not recommended for production use)" - -### Device Operations - -**Required checks before `dcim_create_device` or `dcim_update_device`:** - -1. **Site is REQUIRED** - Fail without it -2. **Platform Assignment** - Recommend for OS tracking -3. **Naming Convention** - Check against `{role}-{location}-{number}` pattern -4. **Role Assignment** - Ensure appropriate role selected -5. **After Creation** - Offer to set primary IP - -### Cluster Operations - -**Required checks before `virt_create_cluster`:** - -1. **Site Scope** - Recommend assigning to site -2. **Cluster Type** - Ensure appropriate type selected -3. **Device Association** - Recommend linking to host device - -### Role Management - -**Before creating a new device role:** - -1. List existing roles with `dcim_list_device_roles` -2. Check if a more general role already exists -3. Recommend role consolidation if >10 specific roles exist - -**Example guidance:** - -> "You're creating role 'nginx-web-server'. An existing 'web-server' role exists. -> Consider using 'web-server' and tracking nginx via the platform field instead. -> This reduces role fragmentation and improves maintainability." - -## Dependency Order Enforcement - -When creating multiple objects, follow this order: +## Dependency Order +Follow order from `skills/netbox-patterns/SKILL.md`: ``` -1. Regions → Sites → Locations → Racks -2. Tenant Groups → Tenants -3. Manufacturers → Device Types +1. Regions -> Sites -> Locations -> Racks +2. Tenant Groups -> Tenants +3. Manufacturers -> Device Types 4. Device Roles, Platforms 5. Devices (with site, role, type) 6. Clusters (with type, optional site) 7. VMs (with cluster) -8. Interfaces → IP Addresses → Primary IP assignment +8. Interfaces -> IP Addresses -> Primary IP ``` -**CRITICAL Rules:** -- NEVER create a VM before its cluster exists -- NEVER create a device before its site exists -- NEVER create an interface before its device exists -- NEVER create an IP before its interface exists (if assigning) - -## Naming Convention Enforcement - -When user provides a name, check against patterns: - -| Object Type | Pattern | Example | -|-------------|---------|---------| -| Device | `{role}-{site}-{number}` | `web-dc1-01` | -| VM | `{env}-{app}-{number}` or `{prefix}_{service}` | `prod-api-01` | -| Cluster | `{site}-{type}` | `dc1-vmware`, `home-docker` | -| Prefix | Include purpose in description | "Production /24 for web tier" | - -**If name doesn't match patterns, warn:** - -> "The name 'HotServ' doesn't follow naming conventions. -> Suggested: `prod-hotserv-01` or `hotserv-cloud-01`. -> Consistent naming improves searchability and automation compatibility. -> Proceed with original name? [Y/n]" - ## Duplicate Prevention -Before creating objects, always check for existing duplicates: - +Before creating, check for existing: ``` -# Before creating device dcim_list_devices name= - -# Before creating VM virt_list_vms name= - -# Before creating prefix ipam_list_prefixes prefix= ``` -If duplicate found, inform user and suggest update instead of create. - ## Available Commands -Users can invoke these commands for structured workflows: - | Command | Purpose | |---------|---------| | `/cmdb-search ` | Search across all CMDB objects | @@ -215,3 +97,6 @@ Users can invoke these commands for structured workflows: | `/cmdb-audit [scope]` | Data quality analysis | | `/cmdb-register` | Register current machine | | `/cmdb-sync` | Sync machine state with NetBox | +| `/cmdb-topology ` | Generate infrastructure diagrams | +| `/change-audit [filters]` | Audit NetBox changes | +| `/ip-conflicts [scope]` | Detect IP conflicts | diff --git a/plugins/cmdb-assistant/commands/change-audit.md b/plugins/cmdb-assistant/commands/change-audit.md index 1c4de44..83636f9 100644 --- a/plugins/cmdb-assistant/commands/change-audit.md +++ b/plugins/cmdb-assistant/commands/change-audit.md @@ -4,20 +4,14 @@ description: Audit NetBox changes with filtering by date, user, or object type # CMDB Change Audit -## Visual Output - -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · Change Audit │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the audit. - Query and analyze the NetBox audit log for change tracking and compliance. +## Skills to Load + +- `skills/visual-header.md` +- `skills/change-audit.md` +- `skills/mcp-tools-reference.md` + ## Usage ``` @@ -33,142 +27,30 @@ Query and analyze the NetBox audit log for change tracking and compliance. ## Instructions -You are a change auditor that queries NetBox's object change log and generates audit reports. +Execute `skills/visual-header.md` with context "Change Audit". -### MCP Tools +Execute `skills/change-audit.md` which covers: +1. Parse user request for filters +2. Query object changes via MCP +3. Enrich data with detailed records +4. Analyze patterns +5. Generate report -Use these tools to query the audit log: - -- `extras_list_object_changes` - List changes with filters: - - `user_id` - Filter by user ID - - `changed_object_type` - Filter by object type (e.g., "dcim.device", "ipam.ipaddress") - - `action` - Filter by action: "create", "update", "delete" - -- `extras_get_object_change` - Get detailed change record by ID - -### Common Object Types - -| Category | Object Types | -|----------|--------------| -| DCIM | `dcim.device`, `dcim.interface`, `dcim.site`, `dcim.rack`, `dcim.cable` | -| IPAM | `ipam.ipaddress`, `ipam.prefix`, `ipam.vlan`, `ipam.vrf` | -| Virtualization | `virtualization.virtualmachine`, `virtualization.cluster` | -| Tenancy | `tenancy.tenant`, `tenancy.contact` | - -### Workflow - -1. **Parse user request** to determine filters -2. **Query object changes** using `extras_list_object_changes` -3. **Enrich data** by fetching detailed records if needed -4. **Analyze patterns** in the changes -5. **Generate report** in structured format - -### Report Format - -```markdown -## NetBox Change Audit Report - -**Generated:** [timestamp] -**Period:** [date range or "All time"] -**Filters:** [applied filters] - -### Summary - -| Metric | Count | -|--------|-------| -| Total Changes | X | -| Creates | Y | -| Updates | Z | -| Deletes | W | -| Unique Users | N | -| Object Types | M | - -### Changes by Action - -#### Created Objects (Y) - -| Time | User | Object Type | Object | Details | -|------|------|-------------|--------|---------| -| 2024-01-15 14:30 | admin | dcim.device | server-01 | Created device | -| ... | ... | ... | ... | ... | - -#### Updated Objects (Z) - -| Time | User | Object Type | Object | Changed Fields | -|------|------|-------------|--------|----------------| -| 2024-01-15 15:00 | john | ipam.ipaddress | 10.0.1.50/24 | status, description | -| ... | ... | ... | ... | ... | - -#### Deleted Objects (W) - -| Time | User | Object Type | Object | Details | -|------|------|-------------|--------|---------| -| 2024-01-14 09:00 | admin | dcim.interface | eth2 | Removed from server-01 | -| ... | ... | ... | ... | ... | - -### Changes by User - -| User | Creates | Updates | Deletes | Total | -|------|---------|---------|---------|-------| -| admin | 5 | 10 | 2 | 17 | -| john | 3 | 8 | 0 | 11 | - -### Changes by Object Type - -| Object Type | Creates | Updates | Deletes | Total | -|-------------|---------|---------|---------|-------| -| dcim.device | 2 | 5 | 0 | 7 | -| ipam.ipaddress | 4 | 3 | 1 | 8 | - -### Timeline - -``` -2024-01-15: ████████ 8 changes -2024-01-14: ████ 4 changes -2024-01-13: ██ 2 changes -``` - -### Notable Patterns - -- **Bulk operations:** [Identify if many changes happened in short time] -- **Unusual activity:** [Flag unexpected deletions or after-hours changes] -- **Missing audit trail:** [Note if expected changes are not logged] - -### Recommendations - -1. [Any security or process recommendations based on findings] -``` - -### Time Period Handling - -When user specifies "last N days": -- The NetBox API may not have direct date filtering in `extras_list_object_changes` -- Fetch recent changes and filter client-side by the `time` field -- Note any limitations in the report - -### Enriching Change Details - -For detailed audit, use `extras_get_object_change` with the change ID to see: -- `prechange_data` - Object state before change -- `postchange_data` - Object state after change -- `request_id` - Links related changes in same request - -### Security Audit Mode +## Security Audit Mode If user asks for "security audit" or "compliance report": -1. Focus on deletions and permission-sensitive changes -2. Highlight changes to critical objects (firewalls, VRFs, prefixes) -3. Flag changes outside business hours -4. Identify users with high change counts +- Focus on deletions and permission-sensitive changes +- Highlight changes to critical objects (firewalls, VRFs, prefixes) +- Flag changes outside business hours +- Identify users with high change counts ## Examples -- `/change-audit` - Show recent changes (last 24 hours) -- `/change-audit last 7 days` - Changes in past week -- `/change-audit by admin` - All changes by admin user +- `/change-audit` - Recent changes (last 24 hours) +- `/change-audit last 7 days` - Past week +- `/change-audit by admin` - All changes by admin - `/change-audit type dcim.device` - Device changes only - `/change-audit action delete` - All deletions -- `/change-audit object server-01` - Changes to server-01 ## User Request diff --git a/plugins/cmdb-assistant/commands/cmdb-audit.md b/plugins/cmdb-assistant/commands/cmdb-audit.md index 0832484..67ff7f5 100644 --- a/plugins/cmdb-assistant/commands/cmdb-audit.md +++ b/plugins/cmdb-assistant/commands/cmdb-audit.md @@ -4,20 +4,15 @@ description: Audit NetBox data quality and identify consistency issues # CMDB Data Quality Audit -## Visual Output - -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · Data Quality Audit │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the audit. - Analyze NetBox data for quality issues and best practice violations. +## Skills to Load + +- `skills/visual-header.md` +- `skills/audit-workflow.md` +- `skills/netbox-patterns/SKILL.md` +- `skills/mcp-tools-reference.md` + ## Usage ``` @@ -33,174 +28,30 @@ Analyze NetBox data for quality issues and best practice violations. ## Instructions -You are a data quality auditor for NetBox. Your job is to identify consistency issues and best practice violations. +Execute `skills/visual-header.md` with context "Data Quality Audit". -**IMPORTANT:** Load the `netbox-patterns` skill for best practice reference. +Execute `skills/audit-workflow.md` which covers: +1. Data collection via MCP +2. Quality checks by severity (CRITICAL, HIGH, MEDIUM, LOW) +3. Naming convention analysis +4. Role fragmentation analysis +5. Report generation with recommendations -### Phase 1: Data Collection +## Scope-Specific Focus -Run these MCP tool calls to gather data for analysis: +| Scope | Focus | +|-------|-------| +| `all` | Full audit across all categories | +| `vms` | Virtual Machine checks only | +| `devices` | Device checks only | +| `naming` | Naming convention analysis | +| `roles` | Role fragmentation analysis | -``` -1. virt_list_vms (no filters - get all) -2. dcim_list_devices (no filters - get all) -3. virt_list_clusters (no filters) -4. dcim_list_sites -5. tenancy_list_tenants -6. dcim_list_device_roles -7. dcim_list_platforms -``` +## Examples -Store the results for analysis. - -### Phase 2: Quality Checks - -Analyze collected data for these issues by severity: - -#### CRITICAL Issues (must fix immediately) - -| Check | Detection | -|-------|-----------| -| VMs without cluster | `cluster` field is null AND `site` field is null | -| Devices without site | `site` field is null | -| Active devices without primary IP | `status=active` AND `primary_ip4` is null AND `primary_ip6` is null | - -#### HIGH Issues (should fix soon) - -| Check | Detection | -|-------|-----------| -| VMs without site | VM has no site (neither direct nor via cluster.site) | -| VMs without tenant | `tenant` field is null | -| Devices without platform | `platform` field is null | -| Clusters not scoped to site | `site` field is null on cluster | -| VMs without role | `role` field is null | - -#### MEDIUM Issues (plan to address) - -| Check | Detection | -|-------|-----------| -| Inconsistent naming | Names don't match patterns: devices=`{role}-{site}-{num}`, VMs=`{env}-{app}-{num}` | -| Role fragmentation | More than 10 device roles with <3 assignments each | -| Missing tags on production | Active resources without any tags | -| Mixed naming separators | Some names use `_`, others use `-` | - -#### LOW Issues (informational) - -| Check | Detection | -|-------|-----------| -| Docker containers as VMs | Cluster type is "Docker Compose" - document this modeling choice | -| VMs without description | `description` field is empty | -| Sites without physical address | `physical_address` is empty | -| Devices without serial | `serial` field is empty | - -### Phase 3: Naming Convention Analysis - -For naming scope, analyze patterns: - -1. **Extract naming patterns** from existing objects -2. **Identify dominant patterns** (most common conventions) -3. **Flag outliers** that don't match dominant patterns -4. **Suggest standardization** based on best practices - -**Expected Patterns:** -- Devices: `{role}-{location}-{number}` (e.g., `web-dc1-01`) -- VMs: `{prefix}_{service}` or `{env}-{app}-{number}` (e.g., `prod-api-01`) -- Clusters: `{site}-{type}` (e.g., `home-docker`) - -### Phase 4: Role Analysis - -For roles scope, analyze fragmentation: - -1. **List all device roles** with assignment counts -2. **Identify single-use roles** (only 1 device/VM) -3. **Identify similar roles** that could be consolidated -4. **Suggest consolidation** based on patterns - -**Red Flags:** -- More than 15 highly specific roles -- Roles with technology in name (use platform instead) -- Roles that duplicate functionality - -### Phase 5: Report Generation - -Present findings in this structure: - -```markdown -## CMDB Data Quality Audit Report - -**Generated:** [timestamp] -**Scope:** [scope parameter] - -### Summary - -| Metric | Count | -|--------|-------| -| Total VMs | X | -| Total Devices | Y | -| Total Clusters | Z | -| **Total Issues** | **N** | - -| Severity | Count | -|----------|-------| -| Critical | A | -| High | B | -| Medium | C | -| Low | D | - -### Critical Issues - -[List each with specific object names and IDs] - -**Example:** -- VM `HotServ` (ID: 1) - No cluster or site assignment -- Device `server-01` (ID: 5) - No site assignment - -### High Issues - -[List each with specific object names] - -### Medium Issues - -[Grouped by category with counts] - -### Recommendations - -1. **[Most impactful fix]** - affects N objects -2. **[Second priority]** - affects M objects -... - -### Quick Fixes - -Commands to fix common issues: - -``` -# Assign site to VM -virt_update_vm id=X site=Y - -# Assign platform to device -dcim_update_device id=X platform=Y -``` - -### Next Steps - -- Run `/cmdb-register` to properly register new machines -- Use `/cmdb-sync` to update existing registrations -- Consider bulk updates via NetBox web UI for >10 items -``` - -## Scope-Specific Instructions - -### For `vms` scope: -Focus only on Virtual Machine checks. Skip device and role analysis. - -### For `devices` scope: -Focus only on Device checks. Skip VM and cluster analysis. - -### For `naming` scope: -Focus on naming convention analysis across all objects. Generate detailed pattern report. - -### For `roles` scope: -Focus on role fragmentation analysis. Generate consolidation recommendations. +- `/cmdb-audit` - Full audit +- `/cmdb-audit vms` - VM-specific checks +- `/cmdb-audit naming` - Naming conventions ## User Request diff --git a/plugins/cmdb-assistant/commands/cmdb-device.md b/plugins/cmdb-assistant/commands/cmdb-device.md index 42dd7e5..ccdc748 100644 --- a/plugins/cmdb-assistant/commands/cmdb-device.md +++ b/plugins/cmdb-assistant/commands/cmdb-device.md @@ -1,18 +1,11 @@ # CMDB Device Management -## Visual Output +Manage network devices in NetBox. -When executing this command, display the plugin header: +## Skills to Load -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · Device Management │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the operation. - -Manage network devices in NetBox - create, view, update, or delete. +- `skills/visual-header.md` +- `skills/mcp-tools-reference.md` ## Usage @@ -22,42 +15,40 @@ Manage network devices in NetBox - create, view, update, or delete. ## Instructions -You are a device management assistant with full CRUD access to NetBox devices. +Execute `skills/visual-header.md` with context "Device Management". ### Actions **List/View:** -- `list` or `show all` - List all devices using `dcim_list_devices` -- `show ` - Get device details using `dcim_list_devices` with name filter, then `dcim_get_device` -- `at ` - List devices at a specific site +- `list` or `show all` - List all devices: `dcim_list_devices` +- `show ` - Get device details: `dcim_get_device` +- `at ` - List devices at site **Create:** -- `create ` - Create a new device +- `create ` - Create new device - Required: name, device_type, role, site -- Use `dcim_list_device_types`, `dcim_list_device_roles`, `dcim_list_sites` to help user find IDs -- Then use `dcim_create_device` +- Use `dcim_list_device_types`, `dcim_list_device_roles`, `dcim_list_sites` to find IDs **Update:** - `update ` - Update device properties -- First get the device ID, then use `dcim_update_device` +- Get device ID first, then use `dcim_update_device` **Delete:** -- `delete ` - Delete a device (ask for confirmation first) -- Use `dcim_delete_device` +- `delete ` - Delete device (ask confirmation first) ### Related Operations After creating a device, offer to: -- Add interfaces with `dcim_create_interface` -- Assign IP addresses with `ipam_create_ip_address` -- Add to a rack with `dcim_update_device` +- Add interfaces: `dcim_create_interface` +- Assign IP addresses: `ipam_create_ip_address` +- Add to rack: `dcim_update_device` ## Examples -- `/cmdb-device list` - Show all devices -- `/cmdb-device show core-router-01` - Get details for specific device -- `/cmdb-device create web-server-03` - Create a new device -- `/cmdb-device at headquarters` - List devices at headquarters site +- `/cmdb-device list` +- `/cmdb-device show core-router-01` +- `/cmdb-device create web-server-03` +- `/cmdb-device at headquarters` ## User Request diff --git a/plugins/cmdb-assistant/commands/cmdb-ip.md b/plugins/cmdb-assistant/commands/cmdb-ip.md index f1826e7..751af23 100644 --- a/plugins/cmdb-assistant/commands/cmdb-ip.md +++ b/plugins/cmdb-assistant/commands/cmdb-ip.md @@ -1,19 +1,13 @@ # CMDB IP Management -## Visual Output - -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · IP Management │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the operation. - Manage IP addresses and prefixes in NetBox. +## Skills to Load + +- `skills/visual-header.md` +- `skills/ip-management.md` +- `skills/mcp-tools-reference.md` + ## Usage ``` @@ -22,43 +16,36 @@ Manage IP addresses and prefixes in NetBox. ## Instructions -You are an IP address management (IPAM) assistant with access to NetBox. +Execute `skills/visual-header.md` with context "IP Management". + +Execute operations from `skills/ip-management.md`. ### Actions **Prefixes:** -- `prefixes` - List all prefixes using `ipam_list_prefixes` -- `prefix ` - Get prefix details or find prefix containing address -- `available in ` - Show available IPs in a prefix using `ipam_list_available_ips` -- `create prefix ` - Create new prefix using `ipam_create_prefix` +- `prefixes` - List all prefixes +- `prefix ` - Get prefix details +- `available in ` - Show available IPs +- `create prefix ` - Create new prefix **IP Addresses:** -- `list` - List all IP addresses using `ipam_list_ip_addresses` +- `list` - List all IP addresses - `show
` - Get IP details -- `allocate from ` - Auto-allocate next available IP using `ipam_create_available_ip` -- `create
` - Create specific IP using `ipam_create_ip_address` -- `assign to ` - Assign IP to device interface +- `allocate from ` - Auto-allocate next available +- `create
` - Create specific IP +- `assign to ` - Assign IP to interface -**VLANs:** -- `vlans` - List VLANs using `ipam_list_vlans` +**VLANs and VRFs:** +- `vlans` - List VLANs - `vlan ` - Get VLAN details - -**VRFs:** -- `vrfs` - List VRFs using `ipam_list_vrfs` - -### Workflow Examples - -**Allocate IP to new server:** -1. Find available IPs in target prefix -2. Create the IP address -3. Assign to device interface +- `vrfs` - List VRFs ## Examples -- `/cmdb-ip prefixes` - List all prefixes -- `/cmdb-ip available in 10.0.1.0/24` - Show available IPs -- `/cmdb-ip allocate from 10.0.1.0/24` - Get next available IP -- `/cmdb-ip assign 10.0.1.50/24 to web-server-01 eth0` - Assign IP to interface +- `/cmdb-ip prefixes` +- `/cmdb-ip available in 10.0.1.0/24` +- `/cmdb-ip allocate from 10.0.1.0/24` +- `/cmdb-ip assign 10.0.1.50/24 to web-server-01 eth0` ## User Request diff --git a/plugins/cmdb-assistant/commands/cmdb-register.md b/plugins/cmdb-assistant/commands/cmdb-register.md index 3cd4a1d..1e0fcdb 100644 --- a/plugins/cmdb-assistant/commands/cmdb-register.md +++ b/plugins/cmdb-assistant/commands/cmdb-register.md @@ -4,19 +4,15 @@ description: Register the current machine into NetBox with all running applicati # CMDB Machine Registration -## Visual Output +Register the current machine into NetBox, including hardware info, network interfaces, and running applications. -When executing this command, display the plugin header: +## Skills to Load -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · Machine Registration │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the registration. - -Register the current machine into NetBox, including hardware info, network interfaces, and running applications (Docker containers, services). +- `skills/visual-header.md` +- `skills/device-registration.md` +- `skills/system-discovery.md` +- `skills/netbox-patterns/SKILL.md` +- `skills/mcp-tools-reference.md` ## Usage @@ -31,303 +27,24 @@ Register the current machine into NetBox, including hardware info, network inter ## Instructions -You are registering the current machine into NetBox. This is a multi-phase process that discovers local system information and creates corresponding NetBox objects. - -**IMPORTANT:** Load the `netbox-patterns` skill for best practice reference. - -### Phase 1: System Discovery (via Bash) - -Gather system information using these commands: - -#### 1.1 Basic Device Info - -```bash -# Hostname -hostname - -# OS/Platform info -cat /etc/os-release 2>/dev/null || uname -a - -# Hardware model (varies by system) -# Raspberry Pi: -cat /proc/device-tree/model 2>/dev/null || echo "Unknown" - -# x86 systems: -cat /sys/class/dmi/id/product_name 2>/dev/null || echo "Unknown" - -# Serial number -# Raspberry Pi: -cat /proc/device-tree/serial-number 2>/dev/null || cat /proc/cpuinfo | grep Serial | cut -d: -f2 | tr -d ' ' 2>/dev/null - -# x86 systems: -cat /sys/class/dmi/id/product_serial 2>/dev/null || echo "Unknown" - -# CPU info -nproc - -# Memory (MB) -free -m | awk '/Mem:/ {print $2}' - -# Disk (GB, root filesystem) -df -BG / | awk 'NR==2 {print $2}' | tr -d 'G' -``` - -#### 1.2 Network Interfaces - -```bash -# Get interfaces with IPs (JSON format) -ip -j addr show 2>/dev/null || ip addr show - -# Get default gateway interface -ip route | grep default | awk '{print $5}' | head -1 - -# Get MAC addresses -ip -j link show 2>/dev/null || ip link show -``` - -#### 1.3 Running Applications - -```bash -# Docker containers (if docker available) -docker ps --format '{"name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}","ports":"{{.Ports}}"}' 2>/dev/null || echo "Docker not available" - -# Docker Compose projects (check common locations) -find ~/apps /home/*/apps -name "docker-compose.yml" -o -name "docker-compose.yaml" 2>/dev/null | head -20 - -# Systemd services (running) -systemctl list-units --type=service --state=running --no-pager --plain 2>/dev/null | grep -v "^UNIT" | head -30 -``` - -### Phase 2: Pre-Registration Checks (via MCP) - -Before creating objects, verify prerequisites: - -#### 2.1 Check if Device Already Exists - -``` -dcim_list_devices name= -``` - -**If device exists:** -- Inform user and suggest `/cmdb-sync` instead -- Ask if they want to proceed with re-registration (will update existing) - -#### 2.2 Verify/Create Site - -If `--site` provided: -``` -dcim_list_sites name= -``` - -If site doesn't exist, ask user if they want to create it. - -If no site provided, list available sites and ask user to choose: -``` -dcim_list_sites -``` - -#### 2.3 Verify/Create Platform - -Based on OS detected, check if platform exists: -``` -dcim_list_platforms name= -``` - -**Platform naming:** -- `Raspberry Pi OS (Bookworm)` for Raspberry Pi -- `Ubuntu 24.04 LTS` for Ubuntu -- `Debian 12` for Debian -- Use format: `{OS Name} {Version}` - -If platform doesn't exist, create it: -``` -dcim_create_platform name= slug= -``` - -#### 2.4 Verify/Create Device Role - -Based on detected services: -- If Docker containers found → `Docker Host` -- If only basic services → `Server` -- If specific role specified → Use that - -``` -dcim_list_device_roles name= -``` - -### Phase 3: Device Registration (via MCP) - -#### 3.1 Get/Create Manufacturer and Device Type - -For Raspberry Pi: -``` -dcim_list_manufacturers name="Raspberry Pi Foundation" -dcim_list_device_types manufacturer_id=X model="Raspberry Pi 4 Model B" -``` - -Create if not exists. - -For generic x86: -``` -dcim_list_manufacturers name= -``` - -#### 3.2 Create Device - -``` -dcim_create_device - name= - device_type= - role= - site= - platform= - tenant= # if provided - serial= - description="Registered via cmdb-assistant" -``` - -#### 3.3 Create Interfaces - -For each network interface discovered: -``` -dcim_create_interface - device= - name= # eth0, wlan0, tailscale0, etc. - type= # 1000base-t, virtual, other - mac_address= - enabled=true -``` - -**Interface type mapping:** -- `eth*`, `enp*` → `1000base-t` -- `wlan*` → `ieee802.11ax` (or appropriate wifi type) -- `tailscale*`, `docker*`, `br-*` → `virtual` -- `lo` → skip (loopback) - -#### 3.4 Create IP Addresses - -For each IP on each interface: -``` -ipam_create_ip_address - address= # e.g., "192.168.1.100/24" - assigned_object_type="dcim.interface" - assigned_object_id= - status="active" - description="Discovered via cmdb-register" -``` - -#### 3.5 Set Primary IP - -Identify primary IP (interface with default route): -``` -dcim_update_device - id= - primary_ip4= -``` - -### Phase 4: Container Registration (via MCP) - -If Docker containers were discovered: - -#### 4.1 Create/Get Cluster Type - -``` -virt_list_cluster_types name="Docker Compose" -``` - -Create if not exists: -``` -virt_create_cluster_type name="Docker Compose" slug="docker-compose" -``` - -#### 4.2 Create Cluster - -For each Docker Compose project directory found: -``` -virt_create_cluster - name= # e.g., "apps-hotport" - type= - site= - description="Docker Compose stack on " -``` - -#### 4.3 Create VMs for Containers - -For each running container: -``` -virt_create_vm - name= - cluster= - site= - role= # Map container function to role - status="active" - vcpus= # Default 1.0 if unknown - memory= # Default 256 if unknown - disk= # Default 5 if unknown - description= - comments= -``` - -**Container role mapping:** -- `*caddy*`, `*nginx*`, `*traefik*` → "Reverse Proxy" -- `*db*`, `*postgres*`, `*mysql*`, `*redis*` → "Database" -- `*webui*`, `*frontend*` → "Web Application" -- Others → Infer from image name or use generic "Container" - -### Phase 5: Documentation - -#### 5.1 Add Journal Entry - -``` -extras_create_journal_entry - assigned_object_type="dcim.device" - assigned_object_id= - comments="Device registered via /cmdb-register command\n\nDiscovered:\n- X network interfaces\n- Y IP addresses\n- Z Docker containers" -``` - -### Phase 6: Summary Report - -Present registration summary: - -```markdown -## Machine Registration Complete - -### Device Created -- **Name:** -- **Site:** -- **Platform:** -- **Role:** -- **ID:** -- **URL:** https://netbox.example.com/dcim/devices// - -### Network Interfaces -| Interface | Type | MAC | IP Address | -|-----------|------|-----|------------| -| eth0 | 1000base-t | aa:bb:cc:dd:ee:ff | 192.168.1.100/24 | -| tailscale0 | virtual | - | 100.x.x.x/32 | - -### Primary IP: 192.168.1.100 - -### Docker Containers Registered (if applicable) -**Cluster:** (ID: ) - -| Container | Role | vCPUs | Memory | Status | -|-----------|------|-------|--------|--------| -| media_jellyfin | Media Server | 2.0 | 2048MB | Active | -| media_sonarr | Media Management | 1.0 | 512MB | Active | - -### Next Steps -- Run `/cmdb-sync` periodically to keep data current -- Run `/cmdb-audit` to check data quality -- Add tags for classification (env:*, team:*, etc.) -``` +Execute `skills/visual-header.md` with context "Machine Registration". + +Execute `skills/device-registration.md` which covers: +1. System discovery via Bash (use `skills/system-discovery.md`) +2. Pre-registration checks (device exists?, site?, platform?, role?) +3. Device creation via MCP +4. Interface and IP creation +5. Container registration (if Docker found) +6. Journal entry documentation ## Error Handling -- **Device already exists:** Suggest `/cmdb-sync` or ask to proceed -- **Site not found:** List available sites, offer to create new -- **Docker not available:** Skip container registration, note in summary -- **Permission denied:** Note which operations failed, suggest fixes +| Error | Action | +|-------|--------| +| Device already exists | Suggest `/cmdb-sync` or ask to proceed | +| Site not found | List available sites, offer to create new | +| Docker not available | Skip container registration, note in summary | +| Permission denied | Note which operations failed, suggest fixes | ## User Request diff --git a/plugins/cmdb-assistant/commands/cmdb-site.md b/plugins/cmdb-assistant/commands/cmdb-site.md index 1b9dbf0..68fcfc5 100644 --- a/plugins/cmdb-assistant/commands/cmdb-site.md +++ b/plugins/cmdb-assistant/commands/cmdb-site.md @@ -1,19 +1,12 @@ # CMDB Site Management -## Visual Output - -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · Site Management │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the operation. - Manage sites and locations in NetBox. +## Skills to Load + +- `skills/visual-header.md` +- `skills/mcp-tools-reference.md` + ## Usage ``` @@ -22,46 +15,35 @@ Manage sites and locations in NetBox. ## Instructions -You are a site/location management assistant with access to NetBox. +Execute `skills/visual-header.md` with context "Site Management". ### Actions **Sites:** -- `list` - List all sites using `dcim_list_sites` -- `show ` - Get site details using `dcim_get_site` -- `create ` - Create new site using `dcim_create_site` -- `update ` - Update site using `dcim_update_site` +- `list` - List all sites: `dcim_list_sites` +- `show ` - Get site details: `dcim_get_site` +- `create ` - Create new site: `dcim_create_site` +- `update ` - Update site: `dcim_update_site` - `delete ` - Delete site (with confirmation) -**Locations (within sites):** -- `locations at ` - List locations using `dcim_list_locations` -- `create location at ` - Create location using `dcim_create_location` +**Locations:** +- `locations at ` - List locations: `dcim_list_locations` +- `create location at ` - Create location **Racks:** -- `racks at ` - List racks using `dcim_list_racks` -- `create rack at ` - Create rack using `dcim_create_rack` +- `racks at ` - List racks: `dcim_list_racks` +- `create rack at ` - Create rack **Regions:** -- `regions` - List regions using `dcim_list_regions` -- `create region ` - Create region using `dcim_create_region` - -### Site Properties - -When creating/updating sites: -- name (required) -- slug (required, auto-generated if not provided) -- status: active, planned, staging, decommissioning, retired -- region: parent region ID -- facility: datacenter/building name -- physical_address, shipping_address -- time_zone +- `regions` - List regions: `dcim_list_regions` +- `create region ` - Create region ## Examples -- `/cmdb-site list` - Show all sites -- `/cmdb-site show headquarters` - Get HQ site details -- `/cmdb-site create branch-office-nyc` - Create new site -- `/cmdb-site racks at headquarters` - List racks at HQ +- `/cmdb-site list` +- `/cmdb-site show headquarters` +- `/cmdb-site create branch-office-nyc` +- `/cmdb-site racks at headquarters` ## User Request diff --git a/plugins/cmdb-assistant/commands/cmdb-sync.md b/plugins/cmdb-assistant/commands/cmdb-sync.md index e5db01a..1119aff 100644 --- a/plugins/cmdb-assistant/commands/cmdb-sync.md +++ b/plugins/cmdb-assistant/commands/cmdb-sync.md @@ -4,19 +4,14 @@ description: Synchronize current machine state with existing NetBox record # CMDB Machine Sync -## Visual Output +Update an existing NetBox device record with the current machine state. -When executing this command, display the plugin header: +## Skills to Load -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · Machine Sync │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the synchronization. - -Update an existing NetBox device record with the current machine state. Compares local system information with NetBox and applies changes. +- `skills/visual-header.md` +- `skills/sync-workflow.md` +- `skills/system-discovery.md` +- `skills/mcp-tools-reference.md` ## Usage @@ -30,318 +25,32 @@ Update an existing NetBox device record with the current machine state. Compares ## Instructions -You are synchronizing the current machine's state with its NetBox record. This involves comparing current system state with stored data and updating differences. - -**IMPORTANT:** Load the `netbox-patterns` skill for best practice reference. - -### Phase 1: Device Lookup (via MCP) - -First, find the existing device record: - -```bash -# Get current hostname -hostname -``` - -``` -dcim_list_devices name= -``` - -**If device not found:** -- Inform user: "Device '' not found in NetBox" -- Suggest: "Run `/cmdb-register` to register this machine first" -- Exit sync - -**If device found:** -- Store device ID and all current field values -- Fetch interfaces: `dcim_list_interfaces device_id=` -- Fetch IPs: `ipam_list_ip_addresses device_id=` - -Also check for associated clusters/VMs: -``` -virt_list_clusters # Look for cluster associated with this device -virt_list_vms cluster= # If cluster found -``` - -### Phase 2: Current State Discovery (via Bash) - -Gather current system information (same as `/cmdb-register`): - -```bash -# Device info -hostname -cat /etc/os-release 2>/dev/null || uname -a -nproc -free -m | awk '/Mem:/ {print $2}' -df -BG / | awk 'NR==2 {print $2}' | tr -d 'G' - -# Network interfaces with IPs -ip -j addr show 2>/dev/null || ip addr show - -# Docker containers -docker ps --format '{"name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}"}' 2>/dev/null || echo "[]" -``` - -### Phase 3: Comparison - -Compare discovered state with NetBox record: - -#### 3.1 Device Attributes - -| Field | Compare | -|-------|---------| -| Platform | OS version changed? | -| Status | Still active? | -| Serial | Match? | -| Description | Keep existing | - -#### 3.2 Network Interfaces - -| Change Type | Detection | -|-------------|-----------| -| New interface | Interface exists locally but not in NetBox | -| Removed interface | Interface in NetBox but not locally | -| Changed MAC | MAC address different | -| Interface type | Type mismatch | - -#### 3.3 IP Addresses - -| Change Type | Detection | -|-------------|-----------| -| New IP | IP exists locally but not in NetBox | -| Removed IP | IP in NetBox but not locally (on this device) | -| Primary IP changed | Default route interface changed | - -#### 3.4 Docker Containers - -| Change Type | Detection | -|-------------|-----------| -| New container | Container running locally but no VM in cluster | -| Stopped container | VM exists but container not running | -| Resource change | vCPUs/memory different (if trackable) | - -### Phase 4: Diff Report - -Present changes to user: - -```markdown -## Sync Diff Report - -**Device:** (ID: ) -**NetBox URL:** https://netbox.example.com/dcim/devices// - -### Device Attributes -| Field | NetBox Value | Current Value | Action | -|-------|--------------|---------------|--------| -| Platform | Ubuntu 22.04 | Ubuntu 24.04 | UPDATE | -| Status | active | active | - | - -### Network Interfaces - -#### New Interfaces (will create) -| Interface | Type | MAC | IPs | -|-----------|------|-----|-----| -| tailscale0 | virtual | - | 100.x.x.x/32 | - -#### Removed Interfaces (will mark offline) -| Interface | Type | Reason | -|-----------|------|--------| -| eth1 | 1000base-t | Not found locally | - -#### Changed Interfaces -| Interface | Field | Old | New | -|-----------|-------|-----|-----| -| eth0 | mac_address | aa:bb:cc:00:00:00 | aa:bb:cc:11:11:11 | - -### IP Addresses - -#### New IPs (will create) -- 192.168.1.150/24 on eth0 - -#### Removed IPs (will unassign) -- 192.168.1.100/24 from eth0 - -### Docker Containers - -#### New Containers (will create VMs) -| Container | Image | Role | -|-----------|-------|------| -| media_lidarr | linuxserver/lidarr | Media Management | - -#### Stopped Containers (will mark offline) -| Container | Last Status | -|-----------|-------------| -| media_bazarr | Exited | - -### Summary -- **Updates:** X -- **Creates:** Y -- **Removals/Offline:** Z -``` - -### Phase 5: User Confirmation - -If not `--dry-run`: - -``` -The following changes will be applied: -- Update device platform to "Ubuntu 24.04" -- Create interface "tailscale0" -- Create IP "100.x.x.x/32" on tailscale0 -- Create VM "media_lidarr" in cluster -- Mark VM "media_bazarr" as offline - -Proceed with sync? [Y/n] -``` - -**Use AskUserQuestion** to get confirmation. - -### Phase 6: Apply Updates (via MCP) - -Only if user confirms (or `--full` specified): - -#### 6.1 Device Updates - -``` -dcim_update_device - id= - platform= - # ... other changed fields -``` - -#### 6.2 Interface Updates - -**For new interfaces:** -``` -dcim_create_interface - device= - name= - type= - mac_address= - enabled=true -``` - -**For removed interfaces:** -``` -dcim_update_interface - id= - enabled=false - description="Marked offline by cmdb-sync - interface no longer present" -``` - -**For changed interfaces:** -``` -dcim_update_interface - id= - mac_address= -``` - -#### 6.3 IP Address Updates - -**For new IPs:** -``` -ipam_create_ip_address - address= - assigned_object_type="dcim.interface" - assigned_object_id= - status="active" -``` - -**For removed IPs:** -``` -ipam_update_ip_address - id= - assigned_object_type=null - assigned_object_id=null - description="Unassigned by cmdb-sync" -``` - -#### 6.4 Primary IP Update - -If primary IP changed: -``` -dcim_update_device - id= - primary_ip4= -``` - -#### 6.5 Container/VM Updates - -**For new containers:** -``` -virt_create_vm - name= - cluster= - status="active" - # ... other fields -``` - -**For stopped containers:** -``` -virt_update_vm - id= - status="offline" - description="Container stopped - detected by cmdb-sync" -``` - -### Phase 7: Journal Entry - -Document the sync: - -``` -extras_create_journal_entry - assigned_object_type="dcim.device" - assigned_object_id= - comments="Device synced via /cmdb-sync command\n\nChanges applied:\n- " -``` - -### Phase 8: Summary Report - -```markdown -## Sync Complete - -**Device:** -**Sync Time:** - -### Changes Applied -- Updated platform: Ubuntu 22.04 → Ubuntu 24.04 -- Created interface: tailscale0 (ID: X) -- Created IP: 100.x.x.x/32 (ID: Y) -- Created VM: media_lidarr (ID: Z) -- Marked VM offline: media_bazarr (ID: W) - -### Current State -- **Interfaces:** 4 (3 active, 1 offline) -- **IP Addresses:** 5 -- **Containers/VMs:** 8 (7 active, 1 offline) - -### Next Sync -Run `/cmdb-sync` again after: -- Adding/removing Docker containers -- Changing network configuration -- OS upgrades -``` - -## Dry Run Mode - -If `--dry-run` specified: -- Complete Phase 1-4 (lookup, discovery, compare, diff report) -- Skip Phase 5-8 (no confirmation, no updates, no journal) -- End with: "Dry run complete. No changes applied. Run without --dry-run to apply." - -## Full Sync Mode - -If `--full` specified: -- Skip user confirmation -- Update all fields even if unchanged (force refresh) -- Useful for ensuring NetBox matches current state exactly +Execute `skills/visual-header.md` with context "Machine Sync". + +Execute `skills/sync-workflow.md` which covers: +1. Device lookup via MCP +2. Current state discovery via Bash +3. Comparison of NetBox vs local state +4. Diff report generation +5. User confirmation (unless dry-run) +6. Apply updates via MCP +7. Journal entry creation + +## Modes + +| Mode | Behavior | +|------|----------| +| Default | Show diff, ask confirmation, apply changes | +| `--dry-run` | Show diff only, no changes applied | +| `--full` | Skip confirmation, update all fields | ## Error Handling -- **Device not found:** Suggest `/cmdb-register` -- **Permission denied on updates:** Note which failed, continue with others -- **Cluster not found:** Offer to create or skip container sync -- **API errors:** Log error, continue with remaining updates +| Error | Action | +|-------|--------| +| Device not found | Suggest `/cmdb-register` | +| Permission denied | Note which failed, continue others | +| Cluster not found | Offer to create or skip container sync | ## User Request diff --git a/plugins/cmdb-assistant/commands/cmdb-topology.md b/plugins/cmdb-assistant/commands/cmdb-topology.md index 9572370..d021dc1 100644 --- a/plugins/cmdb-assistant/commands/cmdb-topology.md +++ b/plugins/cmdb-assistant/commands/cmdb-topology.md @@ -4,20 +4,14 @@ description: Generate infrastructure topology diagrams from NetBox data # CMDB Topology Visualization -## Visual Output - -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · Topology │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the visualization. - Generate Mermaid diagrams showing infrastructure topology from NetBox. +## Skills to Load + +- `skills/visual-header.md` +- `skills/topology-generation.md` +- `skills/mcp-tools-reference.md` + ## Usage ``` @@ -26,168 +20,34 @@ Generate Mermaid diagrams showing infrastructure topology from NetBox. **Views:** - `rack ` - Rack elevation showing devices and positions -- `network [site]` - Network topology showing device connections via cables +- `network [site]` - Network topology showing device connections - `site ` - Site overview with racks and device counts - `full` - Full infrastructure overview ## Instructions -You are a topology visualization assistant that queries NetBox and generates Mermaid diagrams. +Execute `skills/visual-header.md` with context "Topology". -### View: Rack Elevation +Execute `skills/topology-generation.md` which covers: +- Data collection via MCP for each view type +- Mermaid diagram generation with proper shapes +- Legend and data notes -Generate a rack view showing devices and their positions. - -**Data Collection:** -1. Use `dcim_list_racks` to find the rack by name -2. Use `dcim_list_devices` with `rack_id` filter to get devices in rack -3. For each device, note: `position`, `u_height`, `face`, `name`, `role` - -**Mermaid Output:** - -```mermaid -graph TB - subgraph rack["Rack: (U)"] - direction TB - u42["U42: empty"] - u41["U41: empty"] - u40["U40: server-01 (Server)"] - u39["U39: server-01 (cont.)"] - u38["U38: switch-01 (Switch)"] - %% ... continue for all units - end -``` - -**For devices spanning multiple U:** -- Mark the top U with device name and role -- Mark subsequent Us as "(cont.)" for the same device -- Empty Us should show "empty" - -### View: Network Topology - -Generate a network diagram showing device connections. - -**Data Collection:** -1. Use `dcim_list_sites` if no site specified (get all) -2. Use `dcim_list_devices` with optional `site_id` filter -3. Use `dcim_list_cables` to get all connections -4. Use `dcim_list_interfaces` for each device to understand port names - -**Mermaid Output:** - -```mermaid -graph TD - subgraph site1["Site: Home"] - router1[("core-router-01
Router")] - switch1[["dist-switch-01
Switch"]] - server1["web-server-01
Server"] - server2["db-server-01
Server"] - end - - router1 -->|"eth0 - eth1"| switch1 - switch1 -->|"gi0/1 - eth0"| server1 - switch1 -->|"gi0/2 - eth0"| server2 -``` - -**Node shapes by role:** -- Router: `[(" ")]` (cylinder/database shape) -- Switch: `[[ ]]` (double brackets) -- Server: `[ ]` (rectangle) -- Firewall: `{{ }}` (hexagon) -- Other: `[ ]` (rectangle) - -**Edge labels:** Show interface names on both ends (A-side - B-side) - -### View: Site Overview - -Generate a site-level view showing racks and summary counts. - -**Data Collection:** -1. Use `dcim_get_site` to get site details -2. Use `dcim_list_racks` with `site_id` filter -3. Use `dcim_list_devices` with `site_id` filter for counts per rack - -**Mermaid Output:** - -```mermaid -graph TB - subgraph site["Site: Headquarters"] - subgraph row1["Row 1"] - rack1["Rack A1
12/42 U used
5 devices"] - rack2["Rack A2
20/42 U used
8 devices"] - end - subgraph row2["Row 2"] - rack3["Rack B1
8/42 U used
3 devices"] - end - end -``` - -### View: Full Infrastructure - -Generate a high-level view of all sites and their relationships. - -**Data Collection:** -1. Use `dcim_list_regions` to get hierarchy -2. Use `dcim_list_sites` to get all sites -3. Use `dcim_list_devices` with status filter for counts - -**Mermaid Output:** - -```mermaid -graph TB - subgraph region1["Region: Americas"] - site1["Headquarters
3 racks, 25 devices"] - site2["Branch Office
1 rack, 5 devices"] - end - subgraph region2["Region: Europe"] - site3["EU Datacenter
10 racks, 100 devices"] - end - - site1 -.->|"WAN Link"| site3 -``` - -### Output Format +## Output Format Always provide: - -1. **Summary** - Brief description of what the diagram shows -2. **Mermaid Code Block** - The diagram code in a fenced code block -3. **Legend** - Explanation of shapes and colors used -4. **Data Notes** - Any data quality issues (e.g., devices without position, missing cables) - -**Example Output:** - -```markdown -## Network Topology: Home Site - -This diagram shows the network connections between 4 devices at the Home site. - -```mermaid -graph TD - router1[("core-router
Router")] - switch1[["main-switch
Switch"]] - server1["homelab-01
Server"] - - router1 -->|"eth0 - gi0/24"| switch1 - switch1 -->|"gi0/1 - eth0"| server1 -``` - -**Legend:** -- Cylinder shape: Routers -- Double brackets: Switches -- Rectangle: Servers - -**Data Notes:** -- 1 device (nas-01) has no cable connections documented -``` +1. **Summary** - Brief description +2. **Mermaid Code Block** - The diagram +3. **Legend** - Shape explanations +4. **Data Notes** - Quality issues found ## Examples -- `/cmdb-topology rack server-rack-01` - Show devices in server-rack-01 -- `/cmdb-topology network` - Show all network connections -- `/cmdb-topology network Home` - Show network topology for Home site only -- `/cmdb-topology site Headquarters` - Show rack overview for Headquarters -- `/cmdb-topology full` - Show full infrastructure overview +- `/cmdb-topology rack server-rack-01` - Rack elevation +- `/cmdb-topology network` - All network connections +- `/cmdb-topology network Home` - Network for Home site +- `/cmdb-topology site Headquarters` - Site overview +- `/cmdb-topology full` - Full infrastructure ## User Request diff --git a/plugins/cmdb-assistant/commands/initial-setup.md b/plugins/cmdb-assistant/commands/initial-setup.md index df189dc..e89758e 100644 --- a/plugins/cmdb-assistant/commands/initial-setup.md +++ b/plugins/cmdb-assistant/commands/initial-setup.md @@ -1,176 +1,74 @@ --- -description: Interactive setup wizard for cmdb-assistant plugin - configures NetBox MCP server +description: Interactive setup wizard for cmdb-assistant plugin --- # CMDB Assistant Setup Wizard -## Visual Output +Configure the cmdb-assistant plugin with NetBox integration. -When executing this command, display the plugin header: +## Skills to Load -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · Setup Wizard │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the setup. - -This command sets up the cmdb-assistant plugin with NetBox integration. +- `skills/visual-header.md` ## Important Context -- **This command uses Bash, Read, Write, and AskUserQuestion tools** - NOT MCP tools -- **MCP tools won't work until after setup + session restart** -- **Uses NetBox MCP server (separate from Gitea MCP)** +- **Uses Bash, Read, Write, AskUserQuestion tools** - NOT MCP tools +- **MCP tools unavailable until after setup + session restart** ---- +## Usage -## Phase 1: Environment Validation +``` +/initial-setup +``` -### Step 1.1: Check Python Version +## Instructions + +Execute `skills/visual-header.md` with context "Setup Wizard". + +### Phase 1: Environment Validation ```bash python3 --version ``` +If below 3.10, stop and inform user. -If below 3.10, stop setup and inform user. +### Phase 2: MCP Server Setup ---- +1. Locate NetBox MCP server in marketplace +2. Check virtual environment exists +3. Create venv if missing: `python3 -m venv .venv && pip install -r requirements.txt` -## Phase 2: MCP Server Setup +### Phase 3: System Configuration -### Step 2.1: Locate NetBox MCP Server +1. Create config directory: `mkdir -p ~/.config/claude` +2. Check `~/.config/claude/netbox.env` exists +3. If missing, ask user for NetBox API URL (must include `/api`) +4. Create config file with placeholder token +5. Instruct user to add API token manually -```bash -find ~/.claude ~/.config/claude -name "mcp_server" -path "*netbox*" 2>/dev/null | head -5 -``` +### Phase 4: Validation -If not found, ask user for marketplace location. +1. Test API connection if token was added +2. Report result (200=success, 403=invalid token) +3. Display completion summary +4. Remind user to restart session for MCP tools -### Step 2.2: Check Virtual Environment - -```bash -ls -la /path/to/mcp-servers/netbox/.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/netbox && python3 -m venv .venv && source .venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt && deactivate -``` - ---- - -## Phase 3: System Configuration - -### Step 3.1: Create Config Directory - -```bash -mkdir -p ~/.config/claude -``` - -### Step 3.2: Check NetBox Configuration - -```bash -cat ~/.config/claude/netbox.env 2>/dev/null || echo "FILE_NOT_FOUND" -``` - -**If file exists with valid values:** Skip to Phase 4. -**If missing or has placeholders:** Continue. - -### Step 3.3: Gather NetBox Information - -Use AskUserQuestion: -- Question: "What is your NetBox API URL? (e.g., https://netbox.company.com/api)" -- Header: "NetBox URL" -- Options: - - "Other (I'll provide the URL)" - -Ask user to provide the URL. - -**Important:** The URL must include `/api` at the end. If the user provides a URL without `/api`, append it automatically. - -### Step 3.4: Create Configuration File - -```bash -cat > ~/.config/claude/netbox.env << 'EOF' -# NetBox API Configuration -# Generated by cmdb-assistant /initial-setup - -NETBOX_API_URL= -NETBOX_API_TOKEN=PASTE_YOUR_TOKEN_HERE -EOF -chmod 600 ~/.config/claude/netbox.env -``` - -### Step 3.5: Token Instructions - ---- - -**Action Required: Add Your NetBox API Token** - -I've created `~/.config/claude/netbox.env` but you need to add your API token manually. - -**Steps:** -1. Open: `nano ~/.config/claude/netbox.env` -2. Generate token in NetBox: Admin → API Tokens → Add Token -3. Replace `PASTE_YOUR_TOKEN_HERE` with your token -4. Save the file - ---- - -Use AskUserQuestion: -- Question: "Have you added your NetBox token?" -- Header: "Token" -- Options: - - "Yes, I've added the token" - - "Skip for now" - ---- - -## Phase 4: Validation - -### Step 4.1: Test Configuration (if token was added) - -```bash -source ~/.config/claude/netbox.env && curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Token $NETBOX_API_TOKEN" "$NETBOX_API_URL/" -``` - -**Note:** The URL already includes `/api`, so we just append `/` for the root API endpoint. - -Report result: -- 200: Success -- 403: Invalid token -- Other: Connection issue - -### Step 4.2: Summary +## Completion Summary ``` -╔════════════════════════════════════════════════════════════╗ -║ CMDB-ASSISTANT SETUP COMPLETE ║ -╠════════════════════════════════════════════════════════════╣ -║ MCP Server (NetBox): ✓ Ready ║ -║ System Config: ✓ ~/.config/claude/netbox.env ║ -╚════════════════════════════════════════════════════════════╝ +CMDB-ASSISTANT SETUP COMPLETE +MCP Server (NetBox): Ready +System Config: ~/.config/claude/netbox.env + +Restart your Claude Code session for MCP tools. + +After restart, try: +- /cmdb-device +- /cmdb-ip
+- /cmdb-site +- /cmdb-search ``` -### Step 4.3: Session Restart Notice +## User Request ---- - -**⚠️ Session Restart Required** - -Restart your Claude Code session for MCP tools to become available. - -**After restart, you can:** -- Run `/cmdb-device ` to look up a device -- Run `/cmdb-ip
` to look up an IP address -- Run `/cmdb-site ` to look up a site -- Run `/cmdb-search ` for general search - ---- - -## Note on Project Configuration - -cmdb-assistant does not require project-level configuration. The NetBox connection is system-wide and not tied to specific repositories. +$ARGUMENTS diff --git a/plugins/cmdb-assistant/commands/ip-conflicts.md b/plugins/cmdb-assistant/commands/ip-conflicts.md index 1d8d437..5f1e2b7 100644 --- a/plugins/cmdb-assistant/commands/ip-conflicts.md +++ b/plugins/cmdb-assistant/commands/ip-conflicts.md @@ -4,20 +4,14 @@ description: Detect IP address conflicts and overlapping prefixes in NetBox # CMDB IP Conflict Detection -## Visual Output - -When executing this command, display the plugin header: - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🖥️ CMDB-ASSISTANT · IP Conflict Detection │ -└──────────────────────────────────────────────────────────────────┘ -``` - -Then proceed with the analysis. - Scan NetBox IPAM data to identify IP address conflicts and overlapping prefixes. +## Skills to Load + +- `skills/visual-header.md` +- `skills/ip-management.md` +- `skills/mcp-tools-reference.md` + ## Usage ``` @@ -33,205 +27,31 @@ Scan NetBox IPAM data to identify IP address conflicts and overlapping prefixes. ## Instructions -You are an IP conflict detection specialist that analyzes NetBox IPAM data for conflicts and issues. +Execute `skills/visual-header.md` with context "IP Conflict Detection". -### Conflict Types to Detect +Execute conflict detection from `skills/ip-management.md`: -#### 1. Duplicate IP Addresses +1. **Data Collection** - Fetch IPs, prefixes, VRFs via MCP +2. **Duplicate Detection** - Group by address+VRF, flag >1 record +3. **Overlap Detection** - Compare prefixes pairwise using CIDR math +4. **Orphan IP Detection** - Find IPs without containing prefix +5. **Generate Report** - Use template from skill -Multiple IP address records with the same address (within same VRF). +## Conflict Types -**Detection:** -1. Use `ipam_list_ip_addresses` to get all addresses -2. Group by address + VRF combination -3. Flag groups with more than one record - -**Exception:** Anycast addresses may legitimately appear multiple times - check the `role` field for "anycast". - -#### 2. Overlapping Prefixes - -Prefixes that contain the same address space (within same VRF). - -**Detection:** -1. Use `ipam_list_prefixes` to get all prefixes -2. For each prefix pair in the same VRF, check if one contains the other -3. Legitimate hierarchies should have proper parent-child relationships - -**Legitimate Overlaps:** -- Parent/child prefix hierarchy (e.g., 10.0.0.0/8 contains 10.0.1.0/24) -- Different VRFs (isolated routing tables) -- Marked as "container" status - -#### 3. IPs Outside Their Prefix - -IP addresses that don't fall within any defined prefix. - -**Detection:** -1. For each IP address, find the most specific prefix that contains it -2. Flag IPs with no matching prefix - -#### 4. Prefix Overlap Across VRFs (Informational) - -Same prefix appearing in multiple VRFs - not necessarily a conflict, but worth noting. - -### MCP Tools - -- `ipam_list_ip_addresses` - Get all IP addresses with filters: - - `address` - Filter by specific address - - `vrf_id` - Filter by VRF - - `parent` - Filter by parent prefix - - `status` - Filter by status - -- `ipam_list_prefixes` - Get all prefixes with filters: - - `prefix` - Filter by prefix CIDR - - `vrf_id` - Filter by VRF - - `within` - Find prefixes within a parent - - `contains` - Find prefixes containing an address - -- `ipam_list_vrfs` - List VRFs for context -- `ipam_get_ip_address` - Get detailed IP info including assigned device/interface -- `ipam_get_prefix` - Get detailed prefix info - -### Workflow - -1. **Data Collection** - - Fetch all IP addresses (or filtered set) - - Fetch all prefixes (or filtered set) - - Fetch VRFs for context - -2. **Duplicate Detection** - - Build address map: `{address+vrf: [records]}` - - Filter for entries with >1 record - -3. **Overlap Detection** - - For each VRF, compare prefixes pairwise - - Check using CIDR math: does prefix A contain prefix B or vice versa? - - Ignore legitimate hierarchies (status=container) - -4. **Orphan IP Detection** - - For each IP, find containing prefix - - Flag IPs with no prefix match - -5. **Generate Report** - -### Report Format - -```markdown -## IP Conflict Detection Report - -**Generated:** [timestamp] -**Scope:** [scope parameter] - -### Summary - -| Check | Status | Count | -|-------|--------|-------| -| Duplicate IPs | [PASS/FAIL] | X | -| Overlapping Prefixes | [PASS/FAIL] | Y | -| Orphan IPs | [PASS/FAIL] | Z | -| Total Issues | - | N | - -### Critical Issues - -#### Duplicate IP Addresses - -| Address | VRF | Count | Assigned To | -|---------|-----|-------|-------------| -| 10.0.1.50/24 | Global | 2 | server-01 (eth0), server-02 (eth0) | -| 192.168.1.100/24 | Global | 2 | router-01 (gi0/1), switch-01 (vlan10) | - -**Impact:** IP conflicts cause network connectivity issues. Devices will have intermittent connectivity. - -**Resolution:** -- Determine which device should have the IP -- Update or remove the duplicate assignment -- Consider IP reservation to prevent future conflicts - -#### Overlapping Prefixes - -| Prefix 1 | Prefix 2 | VRF | Type | -|----------|----------|-----|------| -| 10.0.0.0/24 | 10.0.0.0/25 | Global | Unstructured overlap | -| 192.168.0.0/16 | 192.168.1.0/24 | Production | Missing container flag | - -**Impact:** Overlapping prefixes can cause routing ambiguity and IP management confusion. - -**Resolution:** -- For legitimate hierarchies: Mark parent prefix as status="container" -- For accidental overlaps: Consolidate or re-address one prefix - -### Warnings - -#### IPs Without Prefix - -| Address | VRF | Assigned To | Nearest Prefix | -|---------|-----|-------------|----------------| -| 172.16.5.10/24 | Global | server-03 (eth0) | None found | - -**Impact:** IPs without a prefix bypass IPAM allocation controls. - -**Resolution:** -- Create appropriate prefix to contain the IP -- Or update IP to correct address within existing prefix - -### Informational - -#### Same Prefix in Multiple VRFs - -| Prefix | VRFs | Purpose | -|--------|------|---------| -| 10.0.0.0/24 | Global, DMZ, Internal | [Check if intentional] | - -### Statistics - -| Metric | Value | -|--------|-------| -| Total IP Addresses | X | -| Total Prefixes | Y | -| Total VRFs | Z | -| Utilization (IPs/Prefix space) | W% | - -### Remediation Commands - -``` -# Remove duplicate IP (keep server-01's assignment) -ipam_delete_ip_address id=123 - -# Mark prefix as container -ipam_update_prefix id=456 status=container - -# Create missing prefix for orphan IP -ipam_create_prefix prefix=172.16.5.0/24 status=active -``` -``` - -### CIDR Math Reference - -For overlap detection, use these rules: -- Prefix A **contains** Prefix B if: A.network <= B.network AND A.broadcast >= B.broadcast -- Two prefixes **overlap** if: A.network <= B.broadcast AND B.network <= A.broadcast - -**Example:** -- 10.0.0.0/8 contains 10.0.1.0/24 (legitimate hierarchy) -- 10.0.0.0/24 and 10.0.0.128/25 overlap (10.0.0.128/25 is within 10.0.0.0/24) - -### Severity Levels - -| Issue | Severity | Description | -|-------|----------|-------------| -| Duplicate IP (same interface type) | CRITICAL | Active conflict, causes outages | -| Duplicate IP (different roles) | HIGH | Potential conflict | -| Overlapping prefixes (same status) | HIGH | IPAM management issue | -| Overlapping prefixes (container ok) | LOW | May need status update | -| Orphan IP | MEDIUM | Bypasses IPAM controls | +| Type | Severity | +|------|----------| +| Duplicate IP (same interface type) | CRITICAL | +| Duplicate IP (different roles) | HIGH | +| Overlapping prefixes (same status) | HIGH | +| Overlapping prefixes (container ok) | LOW | +| Orphan IP | MEDIUM | ## Examples -- `/ip-conflicts` - Full scan for all conflicts -- `/ip-conflicts addresses` - Check only for duplicate IPs -- `/ip-conflicts prefixes` - Check only for overlapping prefixes -- `/ip-conflicts vrf Production` - Scan only Production VRF -- `/ip-conflicts prefix 10.0.0.0/8` - Scan within specific prefix range +- `/ip-conflicts` - Full scan +- `/ip-conflicts addresses` - Duplicate IPs only +- `/ip-conflicts vrf Production` - Scan specific VRF ## User Request diff --git a/plugins/cmdb-assistant/hooks/hooks.json b/plugins/cmdb-assistant/hooks/hooks.json index d90fb51..367453a 100644 --- a/plugins/cmdb-assistant/hooks/hooks.json +++ b/plugins/cmdb-assistant/hooks/hooks.json @@ -2,8 +2,12 @@ "hooks": { "SessionStart": [ { - "type": "command", - "command": "${CLAUDE_PLUGIN_ROOT}/hooks/startup-check.sh" + "hooks": [ + { + "type": "command", + "command": "${CLAUDE_PLUGIN_ROOT}/hooks/startup-check.sh" + } + ] } ], "PreToolUse": [ diff --git a/plugins/cmdb-assistant/skills/audit-workflow.md b/plugins/cmdb-assistant/skills/audit-workflow.md new file mode 100644 index 0000000..b504579 --- /dev/null +++ b/plugins/cmdb-assistant/skills/audit-workflow.md @@ -0,0 +1,163 @@ +# Audit Workflow Skill + +How to audit NetBox data quality. + +## Prerequisites + +Load these skills: +- `netbox-patterns` - Best practices reference +- `mcp-tools-reference` - MCP tool reference + +## Data Collection + +``` +virt_list_vms +dcim_list_devices +virt_list_clusters +dcim_list_sites +tenancy_list_tenants +dcim_list_device_roles +dcim_list_platforms +``` + +## Quality Checks by Severity + +### CRITICAL (must fix immediately) + +| Check | Detection | +|-------|-----------| +| VMs without cluster | `cluster` is null AND `site` is null | +| Devices without site | `site` is null | +| Active devices without primary IP | `status=active` AND `primary_ip4` is null AND `primary_ip6` is null | + +### HIGH (should fix soon) + +| Check | Detection | +|-------|-----------| +| VMs without site | No site (neither direct nor via cluster.site) | +| VMs without tenant | `tenant` is null | +| Devices without platform | `platform` is null | +| Clusters not scoped to site | `site` is null on cluster | +| VMs without role | `role` is null | + +### MEDIUM (plan to address) + +| Check | Detection | +|-------|-----------| +| Inconsistent naming | Names don't match patterns | +| Role fragmentation | >10 device roles with <3 assignments each | +| Missing tags on production | Active resources without tags | +| Mixed naming separators | Some `_`, others `-` | + +### LOW (informational) + +| Check | Detection | +|-------|-----------| +| Docker containers as VMs | Cluster type is "Docker Compose" | +| VMs without description | `description` is empty | +| Sites without physical address | `physical_address` is empty | +| Devices without serial | `serial` is empty | + +## Naming Convention Analysis + +### Expected Patterns + +| Object Type | Pattern | Example | +|-------------|---------|---------| +| Devices | `{role}-{location}-{number}` | `web-dc1-01` | +| VMs | `{env}-{app}-{number}` | `prod-api-01` | +| Clusters | `{site}-{type}` | `home-docker` | + +### Analysis Steps + +1. Extract naming patterns from existing objects +2. Identify dominant patterns (most common) +3. Flag outliers that don't match +4. Suggest standardization + +## Role Fragmentation Analysis + +### Red Flags + +- More than 15 highly specific roles +- Roles with technology in name (use platform instead) +- Roles that duplicate functionality +- Single-use roles (only 1 device/VM) + +### Recommended Consolidation + +Use general roles + platform/tags for specificity: +- Instead of `nginx-web-server`, use `web-server` + platform `nginx` + +## Report Template + +```markdown +## CMDB Data Quality Audit Report + +**Generated:** [timestamp] +**Scope:** [scope parameter] + +### Summary + +| Metric | Count | +|--------|-------| +| Total VMs | X | +| Total Devices | Y | +| Total Clusters | Z | +| **Total Issues** | **N** | + +| Severity | Count | +|----------|-------| +| Critical | A | +| High | B | +| Medium | C | +| Low | D | + +### Critical Issues + +[List each with specific object names and IDs] + +- VM `HotServ` (ID: 1) - No cluster or site assignment +- Device `server-01` (ID: 5) - No site assignment + +### High Issues + +[List each with specific object names] + +### Medium Issues + +[Grouped by category with counts] + +### Recommendations + +1. **[Most impactful fix]** - affects N objects +2. **[Second priority]** - affects M objects + +### Quick Fixes + +Commands to fix common issues: + +``` +# Assign site to VM +virt_update_vm id=X site=Y + +# Assign platform to device +dcim_update_device id=X platform=Y +``` + +### Next Steps + +- Run `/cmdb-register` to properly register new machines +- Use `/cmdb-sync` to update existing registrations +- Consider bulk updates via NetBox web UI for >10 items +``` + +## Scope-Specific Focus + +| Scope | Focus | +|-------|-------| +| `all` | Full audit across all categories | +| `vms` | Virtual Machine checks only | +| `devices` | Device checks only | +| `naming` | Naming convention analysis | +| `roles` | Role fragmentation analysis | diff --git a/plugins/cmdb-assistant/skills/change-audit.md b/plugins/cmdb-assistant/skills/change-audit.md new file mode 100644 index 0000000..9bc7acf --- /dev/null +++ b/plugins/cmdb-assistant/skills/change-audit.md @@ -0,0 +1,130 @@ +# Change Audit Skill + +Audit NetBox changes for tracking and compliance. + +## Prerequisites + +Load skill: `mcp-tools-reference` + +## MCP Tools + +| Tool | Purpose | Parameters | +|------|---------|------------| +| `extras_list_object_changes` | List changes | `user_id`, `changed_object_type`, `action` | +| `extras_get_object_change` | Get change details | `id` | + +## Common Object Types + +| Category | Object Types | +|----------|--------------| +| DCIM | `dcim.device`, `dcim.interface`, `dcim.site`, `dcim.rack`, `dcim.cable` | +| IPAM | `ipam.ipaddress`, `ipam.prefix`, `ipam.vlan`, `ipam.vrf` | +| Virtualization | `virtualization.virtualmachine`, `virtualization.cluster` | +| Tenancy | `tenancy.tenant`, `tenancy.contact` | + +## Audit Workflow + +1. **Parse user request** - Determine filters +2. **Query object changes** - `extras_list_object_changes` +3. **Enrich data** - Fetch detailed records if needed +4. **Analyze patterns** - Identify bulk operations, unusual activity +5. **Generate report** - Structured format + +## Report Template + +```markdown +## NetBox Change Audit Report + +**Generated:** [timestamp] +**Period:** [date range or "All time"] +**Filters:** [applied filters] + +### Summary + +| Metric | Count | +|--------|-------| +| Total Changes | X | +| Creates | Y | +| Updates | Z | +| Deletes | W | +| Unique Users | N | +| Object Types | M | + +### Changes by Action + +#### Created Objects (Y) + +| Time | User | Object Type | Object | Details | +|------|------|-------------|--------|---------| +| 2024-01-15 14:30 | admin | dcim.device | server-01 | Created device | + +#### Updated Objects (Z) + +| Time | User | Object Type | Object | Changed Fields | +|------|------|-------------|--------|----------------| +| 2024-01-15 15:00 | john | ipam.ipaddress | 10.0.1.50/24 | status, description | + +#### Deleted Objects (W) + +| Time | User | Object Type | Object | Details | +|------|------|-------------|--------|---------| +| 2024-01-14 09:00 | admin | dcim.interface | eth2 | Removed from server-01 | + +### Changes by User + +| User | Creates | Updates | Deletes | Total | +|------|---------|---------|---------|-------| +| admin | 5 | 10 | 2 | 17 | +| john | 3 | 8 | 0 | 11 | + +### Changes by Object Type + +| Object Type | Creates | Updates | Deletes | Total | +|-------------|---------|---------|---------|-------| +| dcim.device | 2 | 5 | 0 | 7 | +| ipam.ipaddress | 4 | 3 | 1 | 8 | + +### Timeline + +``` +2024-01-15: ######## 8 changes +2024-01-14: #### 4 changes +2024-01-13: ## 2 changes +``` + +### Notable Patterns + +- **Bulk operations:** [Many changes in short time] +- **Unusual activity:** [Unexpected deletions, after-hours changes] +- **Missing audit trail:** [Expected changes not logged] + +### Recommendations + +1. [Security or process recommendations based on findings] +``` + +## Enriching Change Details + +For detailed audit, use `extras_get_object_change` to see: +- `prechange_data` - Object state before change +- `postchange_data` - Object state after change +- `request_id` - Links related changes in same request + +## Security Audit Mode + +When user asks for "security audit" or "compliance report": + +1. Focus on deletions and permission-sensitive changes +2. Highlight changes to critical objects (firewalls, VRFs, prefixes) +3. Flag changes outside business hours +4. Identify users with high change counts + +## Filter Examples + +| Request | Filter | +|---------|--------| +| Recent changes | None (last 24 hours default) | +| Last 7 days | Filter by `time` field | +| By user | `user_id=` | +| Device changes | `changed_object_type=dcim.device` | +| All deletions | `action=delete` | diff --git a/plugins/cmdb-assistant/skills/device-registration.md b/plugins/cmdb-assistant/skills/device-registration.md new file mode 100644 index 0000000..9553d8a --- /dev/null +++ b/plugins/cmdb-assistant/skills/device-registration.md @@ -0,0 +1,177 @@ +# Device Registration Skill + +How to register devices into NetBox. + +## Prerequisites + +Load these skills: +- `system-discovery` - Bash commands for gathering system info +- `netbox-patterns` - Best practices for data quality +- `mcp-tools-reference` - MCP tool reference + +## Registration Workflow + +### Phase 1: System Discovery + +Use commands from `system-discovery` skill to gather: +- Hostname, OS, hardware model, serial number +- CPU, memory, disk +- Network interfaces with IPs +- Running Docker containers + +### Phase 2: Pre-Registration Checks + +1. **Check if device exists:** + ``` + dcim_list_devices name= + ``` + If exists, suggest `/cmdb-sync` instead. + +2. **Verify/Create site:** + ``` + dcim_list_sites name= + ``` + If not found, list available sites or offer to create. + +3. **Verify/Create platform:** + ``` + dcim_list_platforms name= + ``` + Create if not exists with `dcim_create_platform`. + +4. **Verify/Create device role:** + ``` + dcim_list_device_roles name= + ``` + +### Phase 3: Device Creation + +1. **Get/Create manufacturer and device type:** + ``` + dcim_list_manufacturers name="" + dcim_list_device_types manufacturer_id=X model="" + ``` + +2. **Create device:** + ``` + dcim_create_device + name= + device_type= + role= + site= + platform= + tenant= # if provided + serial= + description="Registered via cmdb-assistant" + ``` + +3. **Create interfaces:** + For each network interface: + ``` + dcim_create_interface + device= + name= + type= + mac_address= + enabled=true + ``` + +4. **Create IP addresses:** + For each IP: + ``` + ipam_create_ip_address + address= + assigned_object_type="dcim.interface" + assigned_object_id= + status="active" + ``` + +5. **Set primary IP:** + ``` + dcim_update_device + id= + primary_ip4= + ``` + +### Phase 4: Container Registration (if Docker) + +1. **Create/Get cluster type:** + ``` + virt_list_cluster_types name="Docker Compose" + virt_create_cluster_type name="Docker Compose" slug="docker-compose" + ``` + +2. **Create cluster:** + ``` + virt_create_cluster + name= + type= + site= + description="Docker Compose stack on " + ``` + +3. **Create VMs for containers:** + For each running container: + ``` + virt_create_vm + name= + cluster= + site= + role= + status="active" + vcpus= + memory= + disk= + ``` + +### Phase 5: Documentation + +Add journal entry: +``` +extras_create_journal_entry + assigned_object_type="dcim.device" + assigned_object_id= + comments="Device registered via /cmdb-register command\n\nDiscovered:\n- X network interfaces\n- Y IP addresses\n- Z Docker containers" +``` + +## Summary Report Template + +```markdown +## Machine Registration Complete + +### Device Created +- **Name:** +- **Site:** +- **Platform:** +- **Role:** +- **ID:** +- **URL:** https://netbox.example.com/dcim/devices// + +### Network Interfaces +| Interface | Type | MAC | IP Address | +|-----------|------|-----|------------| +| eth0 | 1000base-t | aa:bb:cc:dd:ee:ff | 192.168.1.100/24 | + +### Primary IP: 192.168.1.100 + +### Docker Containers Registered (if applicable) +**Cluster:** (ID: ) + +| Container | Role | vCPUs | Memory | Status | +|-----------|------|-------|--------|--------| +| media_jellyfin | Media Server | 2.0 | 2048MB | Active | + +### Next Steps +- Run `/cmdb-sync` periodically to keep data current +- Run `/cmdb-audit` to check data quality +- Add tags for classification +``` + +## Error Handling + +| Error | Action | +|-------|--------| +| Device already exists | Suggest `/cmdb-sync` or ask to proceed | +| Site not found | List available sites, offer to create new | +| Docker not available | Skip container registration, note in summary | +| Permission denied | Note which operations failed, suggest fixes | diff --git a/plugins/cmdb-assistant/skills/ip-management.md b/plugins/cmdb-assistant/skills/ip-management.md new file mode 100644 index 0000000..ae3e24b --- /dev/null +++ b/plugins/cmdb-assistant/skills/ip-management.md @@ -0,0 +1,162 @@ +# IP Management Skill + +IP address and prefix management in NetBox. + +## Prerequisites + +Load skill: `mcp-tools-reference` + +## IPAM Operations + +### Prefix Management + +| Action | Tool | Key Parameters | +|--------|------|----------------| +| List prefixes | `ipam_list_prefixes` | `prefix`, `vrf_id`, `within`, `contains` | +| Get details | `ipam_get_prefix` | `id` | +| Find available child | `ipam_list_available_prefixes` | `prefix_id` | +| Create prefix | `ipam_create_prefix` | `prefix`, `status`, `site`, `vrf` | +| Allocate child | `ipam_create_available_prefix` | `prefix_id`, `prefix_length` | + +### IP Address Management + +| Action | Tool | Key Parameters | +|--------|------|----------------| +| List IPs | `ipam_list_ip_addresses` | `address`, `vrf_id`, `device_id` | +| Get details | `ipam_get_ip_address` | `id` | +| Find available | `ipam_list_available_ips` | `prefix_id` | +| Create IP | `ipam_create_ip_address` | `address`, `assigned_object_type`, `assigned_object_id` | +| Allocate next | `ipam_create_available_ip` | `prefix_id` | +| Assign to interface | `ipam_update_ip_address` | `id`, `assigned_object_id` | + +### VLAN and VRF + +| Action | Tool | +|--------|------| +| List VLANs | `ipam_list_vlans` | +| Get VLAN | `ipam_get_vlan` | +| Create VLAN | `ipam_create_vlan` | +| List VRFs | `ipam_list_vrfs` | +| Get VRF | `ipam_get_vrf` | + +## IP Allocation Workflow + +1. **Find available IPs in target prefix:** + ``` + ipam_list_available_ips prefix_id= + ``` + +2. **Create the IP address:** + ``` + ipam_create_ip_address + address= + assigned_object_type="dcim.interface" + assigned_object_id= + status="active" + ``` + +3. **Set as primary (if needed):** + ``` + dcim_update_device id= primary_ip4= + ``` + +## IP Conflict Detection + +### Conflict Types + +1. **Duplicate IP Addresses** + - Multiple records with same address in same VRF + - Exception: Anycast addresses (check `role` field) + +2. **Overlapping Prefixes** + - Prefixes containing same address space in same VRF + - Legitimate: Parent/child hierarchy, different VRFs, "container" status + +3. **IPs Outside Prefix** + - IP addresses not within any defined prefix + +4. **Same Prefix in Multiple VRFs** (informational) + +### Detection Workflow + +1. **Duplicate Detection:** + - Get all addresses: `ipam_list_ip_addresses` + - Group by address + VRF + - Flag groups with >1 record + +2. **Overlap Detection:** + - Get all prefixes: `ipam_list_prefixes` + - For each VRF, compare prefixes pairwise + - Check if prefix A contains prefix B or vice versa + - Ignore legitimate hierarchies (status=container) + +3. **Orphan IP Detection:** + - For each IP, find containing prefix + - Flag IPs with no prefix match + +### CIDR Math Rules + +- Prefix A **contains** Prefix B if: `A.network <= B.network AND A.broadcast >= B.broadcast` +- Two prefixes **overlap** if: `A.network <= B.broadcast AND B.network <= A.broadcast` + +### Severity Levels + +| Issue | Severity | +|-------|----------| +| Duplicate IP (same interface type) | CRITICAL | +| Duplicate IP (different roles) | HIGH | +| Overlapping prefixes (same status) | HIGH | +| Overlapping prefixes (container ok) | LOW | +| Orphan IP | MEDIUM | + +## Conflict Report Template + +```markdown +## IP Conflict Detection Report + +**Generated:** [timestamp] +**Scope:** [scope parameter] + +### Summary + +| Check | Status | Count | +|-------|--------|-------| +| Duplicate IPs | [PASS/FAIL] | X | +| Overlapping Prefixes | [PASS/FAIL] | Y | +| Orphan IPs | [PASS/FAIL] | Z | + +### Critical Issues + +#### Duplicate IP Addresses + +| Address | VRF | Count | Assigned To | +|---------|-----|-------|-------------| +| 10.0.1.50/24 | Global | 2 | server-01, server-02 | + +**Resolution:** +- Determine which device should have the IP +- Update or remove the duplicate + +#### Overlapping Prefixes + +| Prefix 1 | Prefix 2 | VRF | Type | +|----------|----------|-----|------| +| 10.0.0.0/24 | 10.0.0.0/25 | Global | Unstructured | + +**Resolution:** +- For legitimate hierarchies: Mark parent as status="container" +- For accidental: Consolidate or re-address + +### Remediation Commands + +``` +# Remove duplicate IP +ipam_delete_ip_address id=123 + +# Mark prefix as container +ipam_update_prefix id=456 status=container + +# Create missing prefix +ipam_create_prefix prefix=172.16.5.0/24 status=active +``` +``` diff --git a/plugins/cmdb-assistant/skills/mcp-tools-reference.md b/plugins/cmdb-assistant/skills/mcp-tools-reference.md new file mode 100644 index 0000000..2cd38d4 --- /dev/null +++ b/plugins/cmdb-assistant/skills/mcp-tools-reference.md @@ -0,0 +1,281 @@ +# NetBox MCP Tools Reference + +Complete reference for NetBox MCP tools organized by category. + +## DCIM (Data Center Infrastructure Management) + +### Sites and Locations +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `dcim_list_sites` | List all sites | `name`, `status`, `region_id` | +| `dcim_get_site` | Get site details | `id` | +| `dcim_create_site` | Create new site | `name`, `slug`, `status` | +| `dcim_update_site` | Update site | `id`, fields to update | +| `dcim_delete_site` | Delete site | `id` | +| `dcim_list_locations` | List locations within sites | `site_id`, `parent_id` | +| `dcim_get_location` | Get location details | `id` | +| `dcim_create_location` | Create location | `name`, `slug`, `site` | +| `dcim_update_location` | Update location | `id`, fields to update | +| `dcim_delete_location` | Delete location | `id` | +| `dcim_list_regions` | List regions | `name` | +| `dcim_get_region` | Get region details | `id` | +| `dcim_create_region` | Create region | `name`, `slug` | +| `dcim_update_region` | Update region | `id`, fields to update | +| `dcim_delete_region` | Delete region | `id` | + +### Racks +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `dcim_list_racks` | List racks | `site_id`, `location_id`, `name` | +| `dcim_get_rack` | Get rack details | `id` | +| `dcim_create_rack` | Create rack | `name`, `site`, `u_height` | +| `dcim_update_rack` | Update rack | `id`, fields to update | +| `dcim_delete_rack` | Delete rack | `id` | + +### Devices +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `dcim_list_devices` | List devices | `name`, `site_id`, `role_id`, `status` | +| `dcim_get_device` | Get device details | `id` | +| `dcim_create_device` | Create device | `name`, `device_type`, `role`, `site` | +| `dcim_update_device` | Update device | `id`, `primary_ip4`, etc. | +| `dcim_delete_device` | Delete device | `id` | + +### Device Types and Roles +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `dcim_list_device_types` | List device types | `manufacturer_id`, `model` | +| `dcim_get_device_type` | Get type details | `id` | +| `dcim_create_device_type` | Create device type | `manufacturer`, `model`, `slug` | +| `dcim_update_device_type` | Update device type | `id`, fields | +| `dcim_delete_device_type` | Delete device type | `id` | +| `dcim_list_device_roles` | List device roles | `name` | +| `dcim_get_device_role` | Get role details | `id` | +| `dcim_create_device_role` | Create device role | `name`, `slug` | +| `dcim_update_device_role` | Update device role | `id`, fields | +| `dcim_delete_device_role` | Delete device role | `id` | + +### Manufacturers and Platforms +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `dcim_list_manufacturers` | List manufacturers | `name` | +| `dcim_get_manufacturer` | Get manufacturer details | `id` | +| `dcim_create_manufacturer` | Create manufacturer | `name`, `slug` | +| `dcim_update_manufacturer` | Update manufacturer | `id`, fields | +| `dcim_delete_manufacturer` | Delete manufacturer | `id` | +| `dcim_list_platforms` | List platforms | `name` | +| `dcim_get_platform` | Get platform details | `id` | +| `dcim_create_platform` | Create platform | `name`, `slug` | +| `dcim_update_platform` | Update platform | `id`, fields | +| `dcim_delete_platform` | Delete platform | `id` | + +### Interfaces and Cables +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `dcim_list_interfaces` | List interfaces | `device_id`, `name`, `type` | +| `dcim_get_interface` | Get interface details | `id` | +| `dcim_create_interface` | Create interface | `device`, `name`, `type` | +| `dcim_update_interface` | Update interface | `id`, `enabled`, `mac_address` | +| `dcim_delete_interface` | Delete interface | `id` | +| `dcim_list_cables` | List cables | `device_id`, `site_id` | +| `dcim_get_cable` | Get cable details | `id` | +| `dcim_create_cable` | Create cable | `a_terminations`, `b_terminations` | +| `dcim_update_cable` | Update cable | `id`, fields | +| `dcim_delete_cable` | Delete cable | `id` | + +### Power +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `dcim_list_power_panels` | List power panels | `site_id` | +| `dcim_get_power_panel` | Get panel details | `id` | +| `dcim_create_power_panel` | Create power panel | `name`, `site` | +| `dcim_list_power_feeds` | List power feeds | `power_panel_id` | +| `dcim_get_power_feed` | Get feed details | `id` | +| `dcim_create_power_feed` | Create power feed | `name`, `power_panel`, `supply` | + +### Other DCIM +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `dcim_list_virtual_chassis` | List virtual chassis | (varies) | +| `dcim_get_virtual_chassis` | Get virtual chassis | `id` | +| `dcim_list_inventory_items` | List inventory items | `device_id` | +| `dcim_get_inventory_item` | Get inventory item | `id` | + +## IPAM (IP Address Management) + +### Prefixes +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `ipam_list_prefixes` | List prefixes | `prefix`, `vrf_id`, `within`, `contains` | +| `ipam_get_prefix` | Get prefix details | `id` | +| `ipam_create_prefix` | Create prefix | `prefix`, `status`, `site`, `vrf` | +| `ipam_update_prefix` | Update prefix | `id`, `status`, etc. | +| `ipam_delete_prefix` | Delete prefix | `id` | +| `ipam_list_available_prefixes` | List available child prefixes | `prefix_id` | +| `ipam_create_available_prefix` | Allocate from parent | `prefix_id`, `prefix_length` | + +### IP Addresses +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `ipam_list_ip_addresses` | List IP addresses | `address`, `vrf_id`, `device_id`, `status` | +| `ipam_get_ip_address` | Get IP details | `id` | +| `ipam_create_ip_address` | Create IP address | `address`, `assigned_object_type`, `assigned_object_id` | +| `ipam_update_ip_address` | Update IP address | `id`, `status`, etc. | +| `ipam_delete_ip_address` | Delete IP address | `id` | +| `ipam_list_available_ips` | List available IPs in prefix | `prefix_id` | +| `ipam_create_available_ip` | Allocate next available | `prefix_id` | + +### VLANs and VRFs +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `ipam_list_vlans` | List VLANs | `vid`, `name`, `site_id` | +| `ipam_get_vlan` | Get VLAN details | `id` | +| `ipam_create_vlan` | Create VLAN | `vid`, `name`, `site` | +| `ipam_update_vlan` | Update VLAN | `id`, fields | +| `ipam_delete_vlan` | Delete VLAN | `id` | +| `ipam_list_vlan_groups` | List VLAN groups | `site_id` | +| `ipam_get_vlan_group` | Get VLAN group | `id` | +| `ipam_create_vlan_group` | Create VLAN group | `name`, `slug`, `scope_type` | +| `ipam_list_vrfs` | List VRFs | `name` | +| `ipam_get_vrf` | Get VRF details | `id` | +| `ipam_create_vrf` | Create VRF | `name`, `rd` | +| `ipam_update_vrf` | Update VRF | `id`, fields | +| `ipam_delete_vrf` | Delete VRF | `id` | + +### Other IPAM +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `ipam_list_asns` | List ASNs | (varies) | +| `ipam_get_asn` | Get ASN details | `id` | +| `ipam_create_asn` | Create ASN | `asn`, `rir` | +| `ipam_list_rirs` | List RIRs | `name` | +| `ipam_get_rir` | Get RIR details | `id` | +| `ipam_list_aggregates` | List aggregates | `prefix`, `rir_id` | +| `ipam_get_aggregate` | Get aggregate | `id` | +| `ipam_create_aggregate` | Create aggregate | `prefix`, `rir` | +| `ipam_list_services` | List services | `device_id`, `name` | +| `ipam_get_service` | Get service details | `id` | +| `ipam_create_service` | Create service | `name`, `ports`, `protocol` | + +## Virtualization + +### Clusters +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `virt_list_cluster_types` | List cluster types | `name` | +| `virt_get_cluster_type` | Get cluster type | `id` | +| `virt_create_cluster_type` | Create cluster type | `name`, `slug` | +| `virt_list_cluster_groups` | List cluster groups | `name` | +| `virt_get_cluster_group` | Get cluster group | `id` | +| `virt_create_cluster_group` | Create cluster group | `name`, `slug` | +| `virt_list_clusters` | List clusters | `name`, `site_id`, `type_id` | +| `virt_get_cluster` | Get cluster details | `id` | +| `virt_create_cluster` | Create cluster | `name`, `type`, `site` | +| `virt_update_cluster` | Update cluster | `id`, fields | +| `virt_delete_cluster` | Delete cluster | `id` | + +### Virtual Machines +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `virt_list_vms` | List VMs | `name`, `cluster_id`, `site_id`, `status` | +| `virt_get_vm` | Get VM details | `id` | +| `virt_create_vm` | Create VM | `name`, `cluster`, `site`, `status` | +| `virt_update_vm` | Update VM | `id`, `status`, etc. | +| `virt_delete_vm` | Delete VM | `id` | +| `virt_list_vm_ifaces` | List VM interfaces | `virtual_machine_id` | +| `virt_get_vm_iface` | Get VM interface | `id` | +| `virt_create_vm_iface` | Create VM interface | `virtual_machine`, `name` | + +## Circuits + +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `circuits_list_providers` | List providers | `name` | +| `circuits_get_provider` | Get provider | `id` | +| `circuits_create_provider` | Create provider | `name`, `slug` | +| `circuits_update_provider` | Update provider | `id`, fields | +| `circuits_delete_provider` | Delete provider | `id` | +| `circ_list_types` | List circuit types | `name` | +| `circ_get_type` | Get circuit type | `id` | +| `circ_create_type` | Create circuit type | `name`, `slug` | +| `circuits_list_circuits` | List circuits | `provider_id`, `type_id` | +| `circuits_get_circuit` | Get circuit | `id` | +| `circuits_create_circuit` | Create circuit | `cid`, `provider`, `type` | +| `circuits_update_circuit` | Update circuit | `id`, fields | +| `circuits_delete_circuit` | Delete circuit | `id` | +| `circ_list_terminations` | List terminations | `circuit_id` | +| `circ_get_termination` | Get termination | `id` | +| `circ_create_termination` | Create termination | `circuit`, `site`, `term_side` | + +## Tenancy + +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `tenancy_list_tenant_groups` | List tenant groups | `name` | +| `tenancy_get_tenant_group` | Get tenant group | `id` | +| `tenancy_create_tenant_group` | Create tenant group | `name`, `slug` | +| `tenancy_list_tenants` | List tenants | `name`, `group_id` | +| `tenancy_get_tenant` | Get tenant | `id` | +| `tenancy_create_tenant` | Create tenant | `name`, `slug` | +| `tenancy_update_tenant` | Update tenant | `id`, fields | +| `tenancy_delete_tenant` | Delete tenant | `id` | +| `tenancy_list_contacts` | List contacts | `name` | +| `tenancy_get_contact` | Get contact | `id` | +| `tenancy_create_contact` | Create contact | `name` | + +## VPN + +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `vpn_list_tunnels` | List VPN tunnels | `name` | +| `vpn_get_tunnel` | Get tunnel | `id` | +| `vpn_create_tunnel` | Create tunnel | `name`, `status` | +| `vpn_list_l2vpns` | List L2VPNs | `name` | +| `vpn_get_l2vpn` | Get L2VPN | `id` | +| `vpn_create_l2vpn` | Create L2VPN | `name`, `type` | +| `vpn_list_ike_policies` | List IKE policies | (varies) | +| `vpn_list_ipsec_policies` | List IPSec policies | (varies) | +| `vpn_list_ipsec_profiles` | List IPSec profiles | (varies) | + +## Wireless + +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `wlan_list_groups` | List WLAN groups | `name` | +| `wlan_get_group` | Get WLAN group | `id` | +| `wlan_create_group` | Create WLAN group | `name`, `slug` | +| `wlan_list_lans` | List WLANs | `ssid` | +| `wlan_get_lan` | Get WLAN | `id` | +| `wlan_create_lan` | Create WLAN | `ssid`, `group` | +| `wlan_list_links` | List wireless links | (varies) | +| `wlan_get_link` | Get wireless link | `id` | + +## Extras + +| Tool | Purpose | Key Parameters | +|------|---------|----------------| +| `extras_list_tags` | List tags | `name` | +| `extras_get_tag` | Get tag | `id` | +| `extras_create_tag` | Create tag | `name`, `slug`, `color` | +| `extras_update_tag` | Update tag | `id`, fields | +| `extras_delete_tag` | Delete tag | `id` | +| `extras_list_custom_fields` | List custom fields | `name` | +| `extras_get_custom_field` | Get custom field | `id` | +| `extras_list_webhooks` | List webhooks | `name` | +| `extras_get_webhook` | Get webhook | `id` | +| `extras_list_journal_entries` | List journal entries | `assigned_object_type`, `assigned_object_id` | +| `extras_get_journal_entry` | Get journal entry | `id` | +| `extras_create_journal_entry` | Create journal entry | `assigned_object_type`, `assigned_object_id`, `comments` | +| `extras_list_object_changes` | List audit log | `user_id`, `changed_object_type`, `action` | +| `extras_get_object_change` | Get change details | `id` | +| `extras_list_config_contexts` | List config contexts | `name` | +| `extras_get_config_context` | Get config context | `id` | + +## Common Object Types for Filtering + +| Category | Object Types | +|----------|--------------| +| DCIM | `dcim.device`, `dcim.interface`, `dcim.site`, `dcim.rack`, `dcim.cable` | +| IPAM | `ipam.ipaddress`, `ipam.prefix`, `ipam.vlan`, `ipam.vrf` | +| Virtualization | `virtualization.virtualmachine`, `virtualization.cluster` | +| Tenancy | `tenancy.tenant`, `tenancy.contact` | diff --git a/plugins/cmdb-assistant/skills/sync-workflow.md b/plugins/cmdb-assistant/skills/sync-workflow.md new file mode 100644 index 0000000..f6b053f --- /dev/null +++ b/plugins/cmdb-assistant/skills/sync-workflow.md @@ -0,0 +1,191 @@ +# Sync Workflow Skill + +How to synchronize machine state with NetBox. + +## Prerequisites + +Load these skills: +- `system-discovery` - Bash commands for system info +- `mcp-tools-reference` - MCP tool reference + +## Sync Workflow + +### Phase 1: Device Lookup + +``` +dcim_list_devices name= +``` + +If not found, suggest `/cmdb-register` first. + +If found: +- Store device ID and current field values +- Fetch interfaces: `dcim_list_interfaces device_id=` +- Fetch IPs: `ipam_list_ip_addresses device_id=` +- Check clusters/VMs: `virt_list_clusters`, `virt_list_vms cluster=` + +### Phase 2: Current State Discovery + +Use commands from `system-discovery` skill. + +### Phase 3: Comparison + +#### Device Attributes +| Field | Compare | +|-------|---------| +| Platform | OS version changed? | +| Status | Still active? | +| Serial | Match? | +| Description | Keep existing | + +#### Network Interfaces +| Change Type | Detection | +|-------------|-----------| +| New interface | Exists locally but not in NetBox | +| Removed interface | In NetBox but not locally | +| Changed MAC | MAC address different | +| Interface type | Type mismatch | + +#### IP Addresses +| Change Type | Detection | +|-------------|-----------| +| New IP | Exists locally but not in NetBox | +| Removed IP | In NetBox but not locally | +| Primary IP changed | Default route interface changed | + +#### Docker Containers +| Change Type | Detection | +|-------------|-----------| +| New container | Running locally but no VM in cluster | +| Stopped container | VM exists but container not running | +| Resource change | vCPUs/memory different | + +### Phase 4: Diff Report + +```markdown +## Sync Diff Report + +**Device:** (ID: ) +**NetBox URL:** https://netbox.example.com/dcim/devices// + +### Device Attributes +| Field | NetBox Value | Current Value | Action | +|-------|--------------|---------------|--------| +| Platform | Ubuntu 22.04 | Ubuntu 24.04 | UPDATE | + +### Network Interfaces + +#### New Interfaces (will create) +| Interface | Type | MAC | IPs | +|-----------|------|-----|-----| +| tailscale0 | virtual | - | 100.x.x.x/32 | + +#### Removed Interfaces (will mark offline) +| Interface | Type | Reason | +|-----------|------|--------| +| eth1 | 1000base-t | Not found locally | + +#### Changed Interfaces +| Interface | Field | Old | New | +|-----------|-------|-----|-----| +| eth0 | mac_address | aa:bb:cc:00:00:00 | aa:bb:cc:11:11:11 | + +### IP Addresses + +#### New IPs (will create) +- 192.168.1.150/24 on eth0 + +#### Removed IPs (will unassign) +- 192.168.1.100/24 from eth0 + +### Docker Containers + +#### New Containers (will create VMs) +| Container | Image | Role | +|-----------|-------|------| +| media_lidarr | linuxserver/lidarr | Media Management | + +### Summary +- **Updates:** X +- **Creates:** Y +- **Removals/Offline:** Z +``` + +### Phase 5: Apply Updates + +#### Device Updates +``` +dcim_update_device id= platform= +``` + +#### Interface Updates +New: +``` +dcim_create_interface device= name= type= +``` + +Removed (mark offline): +``` +dcim_update_interface id= enabled=false description="Marked offline by cmdb-sync" +``` + +Changed: +``` +dcim_update_interface id= mac_address= +``` + +#### IP Address Updates +New: +``` +ipam_create_ip_address address= assigned_object_type="dcim.interface" assigned_object_id= +``` + +Removed (unassign): +``` +ipam_update_ip_address id= assigned_object_type=null assigned_object_id=null +``` + +#### Primary IP Update +``` +dcim_update_device id= primary_ip4= +``` + +#### Container/VM Updates +New: +``` +virt_create_vm name= cluster= status="active" +``` + +Stopped: +``` +virt_update_vm id= status="offline" +``` + +### Phase 6: Journal Entry + +``` +extras_create_journal_entry + assigned_object_type="dcim.device" + assigned_object_id= + comments="Device synced via /cmdb-sync command\n\nChanges applied:\n- " +``` + +## Sync Modes + +### Dry Run Mode +- Complete phases 1-4 (lookup, discovery, compare, diff report) +- Skip phases 5-6 (no updates, no journal) +- End with: "Dry run complete. No changes applied." + +### Full Sync Mode +- Skip user confirmation +- Update all fields even if unchanged (force refresh) + +## Error Handling + +| Error | Action | +|-------|--------| +| Device not found | Suggest `/cmdb-register` | +| Permission denied | Note which failed, continue others | +| Cluster not found | Offer to create or skip container sync | +| API errors | Log error, continue with remaining | diff --git a/plugins/cmdb-assistant/skills/system-discovery.md b/plugins/cmdb-assistant/skills/system-discovery.md new file mode 100644 index 0000000..89cc80d --- /dev/null +++ b/plugins/cmdb-assistant/skills/system-discovery.md @@ -0,0 +1,101 @@ +# System Discovery Skill + +Bash commands for gathering system information from the current machine. + +## Basic Device Information + +```bash +# Hostname +hostname + +# OS/Platform info +cat /etc/os-release 2>/dev/null || uname -a + +# Hardware model - Raspberry Pi +cat /proc/device-tree/model 2>/dev/null || echo "Unknown" + +# Hardware model - x86 systems +cat /sys/class/dmi/id/product_name 2>/dev/null || echo "Unknown" + +# Serial number - Raspberry Pi +cat /proc/device-tree/serial-number 2>/dev/null || cat /proc/cpuinfo | grep Serial | cut -d: -f2 | tr -d ' ' 2>/dev/null + +# Serial number - x86 systems +cat /sys/class/dmi/id/product_serial 2>/dev/null || echo "Unknown" + +# CPU count +nproc + +# Memory in MB +free -m | awk '/Mem:/ {print $2}' + +# Disk size in GB (root filesystem) +df -BG / | awk 'NR==2 {print $2}' | tr -d 'G' +``` + +## Network Interfaces + +```bash +# Get interfaces with IPs (JSON format) +ip -j addr show 2>/dev/null || ip addr show + +# Get default gateway interface +ip route | grep default | awk '{print $5}' | head -1 + +# Get MAC addresses +ip -j link show 2>/dev/null || ip link show +``` + +## Running Applications + +```bash +# Docker containers (JSON format) +docker ps --format '{"name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}","ports":"{{.Ports}}"}' 2>/dev/null || echo "Docker not available" + +# Docker Compose projects (find compose files) +find ~/apps /home/*/apps -name "docker-compose.yml" -o -name "docker-compose.yaml" 2>/dev/null | head -20 + +# Running systemd services +systemctl list-units --type=service --state=running --no-pager --plain 2>/dev/null | grep -v "^UNIT" | head -30 +``` + +## Interface Type Mapping + +| Interface Pattern | NetBox Type | +|-------------------|-------------| +| `eth*`, `enp*` | `1000base-t` | +| `wlan*` | `ieee802.11ax` | +| `tailscale*`, `docker*`, `br-*` | `virtual` | +| `lo` | Skip (loopback) | + +## Platform Detection + +Based on OS detected, determine platform name: + +| OS Detection | Platform Name | +|--------------|---------------| +| Raspberry Pi OS | `Raspberry Pi OS (Bookworm)` | +| Ubuntu | `Ubuntu {version} LTS` | +| Debian | `Debian {version}` | +| Default | `{OS Name} {Version}` | + +## Device Role Auto-Detection + +Based on detected services: + +| Detection | Suggested Role | +|-----------|----------------| +| Docker containers found | `Docker Host` | +| Only basic services | `Server` | +| Specific role specified | Use specified | + +## Container Role Mapping + +Map container names/images to roles: + +| Container Pattern | Role | +|-------------------|------| +| `*caddy*`, `*nginx*`, `*traefik*` | Reverse Proxy | +| `*db*`, `*postgres*`, `*mysql*`, `*redis*` | Database | +| `*webui*`, `*frontend*` | Web Application | +| Others | Infer from image or use "Container" | diff --git a/plugins/cmdb-assistant/skills/topology-generation.md b/plugins/cmdb-assistant/skills/topology-generation.md new file mode 100644 index 0000000..d5c5fa6 --- /dev/null +++ b/plugins/cmdb-assistant/skills/topology-generation.md @@ -0,0 +1,155 @@ +# Topology Generation Skill + +Generate Mermaid diagrams from NetBox data. + +## Prerequisites + +Load skill: `mcp-tools-reference` + +## View: Rack Elevation + +### Data Collection + +1. Find rack: `dcim_list_racks name=` +2. Get devices: `dcim_list_devices rack_id=` +3. Note for each: `position`, `u_height`, `face`, `name`, `role` + +### Mermaid Template + +```mermaid +graph TB + subgraph rack["Rack: (U)"] + direction TB + u42["U42: empty"] + u41["U41: empty"] + u40["U40: server-01 (Server)"] + u39["U39: server-01 (cont.)"] + u38["U38: switch-01 (Switch)"] + end +``` + +### Rules + +- Mark top U with device name and role +- Mark subsequent Us as "(cont.)" for multi-U devices +- Empty Us show "empty" + +## View: Network Topology + +### Data Collection + +1. List sites: `dcim_list_sites` +2. List devices: `dcim_list_devices site_id=` +3. List cables: `dcim_list_cables` +4. List interfaces: `dcim_list_interfaces device_id=` + +### Mermaid Template + +```mermaid +graph TD + subgraph site1["Site: Home"] + router1[("core-router-01
Router")] + switch1[["dist-switch-01
Switch"]] + server1["web-server-01
Server"] + server2["db-server-01
Server"] + end + + router1 -->|"eth0 - eth1"| switch1 + switch1 -->|"gi0/1 - eth0"| server1 + switch1 -->|"gi0/2 - eth0"| server2 +``` + +### Node Shapes by Role + +| Role | Shape | Mermaid Syntax | +|------|-------|----------------| +| Router | Cylinder | `[(" ")]` | +| Switch | Double brackets | `[[ ]]` | +| Server | Rectangle | `[ ]` | +| Firewall | Hexagon | `{{ }}` | +| Other | Rectangle | `[ ]` | + +### Edge Labels + +Show interface names: `A-side - B-side` + +## View: Site Overview + +### Data Collection + +1. Get site: `dcim_get_site id=` +2. List racks: `dcim_list_racks site_id=` +3. Count devices per rack: `dcim_list_devices rack_id=` + +### Mermaid Template + +```mermaid +graph TB + subgraph site["Site: Headquarters"] + subgraph row1["Row 1"] + rack1["Rack A1
12/42 U used
5 devices"] + rack2["Rack A2
20/42 U used
8 devices"] + end + subgraph row2["Row 2"] + rack3["Rack B1
8/42 U used
3 devices"] + end + end +``` + +## View: Full Infrastructure + +### Data Collection + +1. List regions: `dcim_list_regions` +2. List sites: `dcim_list_sites` +3. Count devices: `dcim_list_devices status=active` + +### Mermaid Template + +```mermaid +graph TB + subgraph region1["Region: Americas"] + site1["Headquarters
3 racks, 25 devices"] + site2["Branch Office
1 rack, 5 devices"] + end + subgraph region2["Region: Europe"] + site3["EU Datacenter
10 racks, 100 devices"] + end + + site1 -.->|"WAN Link"| site3 +``` + +## Output Format + +Always provide: + +1. **Summary** - Brief description of diagram content +2. **Mermaid Code Block** - The diagram code +3. **Legend** - Explanation of shapes and colors +4. **Data Notes** - Any data quality issues + +### Example Output + +```markdown +## Network Topology: Home Site + +This diagram shows network connections between 4 devices at Home site. + +```mermaid +graph TD + router1[("core-router
Router")] + switch1[["main-switch
Switch"]] + server1["homelab-01
Server"] + + router1 -->|"eth0 - gi0/24"| switch1 + switch1 -->|"gi0/1 - eth0"| server1 +``` + +**Legend:** +- Cylinder shape: Routers +- Double brackets: Switches +- Rectangle: Servers + +**Data Notes:** +- 1 device (nas-01) has no cable connections documented +``` diff --git a/plugins/cmdb-assistant/skills/visual-header.md b/plugins/cmdb-assistant/skills/visual-header.md new file mode 100644 index 0000000..0c726e8 --- /dev/null +++ b/plugins/cmdb-assistant/skills/visual-header.md @@ -0,0 +1,32 @@ +# Visual Header Skill + +Standard visual header for cmdb-assistant commands. + +## Header Template + +``` ++----------------------------------------------------------------------+ +| CMDB-ASSISTANT - [Context] | ++----------------------------------------------------------------------+ +``` + +## Context Values by Command + +| Command | Context | +|---------|---------| +| `/cmdb-search` | Search | +| `/cmdb-device` | Device Management | +| `/cmdb-ip` | IP Management | +| `/cmdb-site` | Site Management | +| `/cmdb-audit` | Data Quality Audit | +| `/cmdb-register` | Machine Registration | +| `/cmdb-sync` | Machine Sync | +| `/cmdb-topology` | Topology | +| `/change-audit` | Change Audit | +| `/ip-conflicts` | IP Conflict Detection | +| `/initial-setup` | Setup Wizard | +| Agent mode | Infrastructure Management | + +## Usage + +Display header at the start of every command response before proceeding with the operation. 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) diff --git a/plugins/pr-review/commands/initial-setup.md b/plugins/pr-review/commands/initial-setup.md index 32dc619..375b1ef 100644 --- a/plugins/pr-review/commands/initial-setup.md +++ b/plugins/pr-review/commands/initial-setup.md @@ -1,285 +1,45 @@ --- -description: Interactive setup wizard for pr-review plugin - configures Gitea MCP and project settings +description: Interactive setup wizard for pr-review plugin --- # PR Review Setup Wizard ## Visual Output -When executing this command, display the plugin header: +Display header: `PR-REVIEW - Setup Wizard` -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔍 PR-REVIEW · Setup Wizard │ -└──────────────────────────────────────────────────────────────────┘ -``` +## Skills to Load -Then proceed with the setup. - -This command sets up the pr-review plugin. It shares the Gitea MCP server with projman, so if you've already run `/initial-setup` for projman, most of the work is done. +- skills/setup-workflow.md +- skills/mcp-tools-reference.md +- skills/output-formats.md ## Important Context -- **This command uses Bash, Read, Write, and AskUserQuestion tools** - NOT MCP tools -- **MCP tools won't work until after setup + session restart** -- **Shares Gitea MCP server with projman plugin** +- Uses Bash, Read, Write, AskUserQuestion - NOT MCP tools +- MCP tools won't work until after setup + session restart +- Shares Gitea MCP server with projman plugin ---- +## Workflow -## Phase 1: Check Existing Setup +### Phase 1: Check Existing Setup -### Step 1.1: Check if Gitea MCP is Already Configured +Check `~/.config/claude/gitea.env`. If valid, skip to Phase 3. -First, check if the system configuration already exists (from projman or previous setup): +### Phase 2: System Setup (if needed) -```bash -cat ~/.config/claude/gitea.env 2>/dev/null || echo "FILE_NOT_FOUND" -``` +Execute `skills/setup-workflow.md`: verify Python, create gitea.env, prompt for token -**If file exists with valid values (no placeholders):** -- Skip to Phase 3 (Project Configuration) -- Inform user: "Gitea configuration found. Skipping system setup." +### Phase 3: Project Configuration -**If file doesn't exist or has placeholders:** -- Continue to Phase 2 +Execute `skills/setup-workflow.md`: auto-detect org/repo, validate via API, create .env -### Step 1.2: Check if projman is Installed +### Phase 4: Validation -Check if projman plugin exists (they share MCP server): - -```bash -find ~/.claude ~/.config/claude -name "projman" -type d 2>/dev/null | head -1 -``` - -**If projman exists:** -- Suggest: "The projman plugin is installed and shares the same Gitea MCP server. Consider running `/initial-setup` from projman for the full setup wizard." - -Use AskUserQuestion: -- Question: "How would you like to proceed with setup?" -- Header: "Setup" -- Options: - - "Continue with pr-review setup (Recommended if not using projman)" - - "I'll use projman's /initial-setup instead" - -**If user chooses projman setup:** End here with instructions to run projman's setup. - ---- - -## Phase 2: System Setup (if needed) - -This is a condensed version focusing on what pr-review needs. - -### Step 2.1: Python and MCP Server - -Check Python version: -```bash -python3 --version -``` - -If below 3.10, stop and inform user. - -Locate and set up the MCP server: -```bash -find ~/.claude ~/.config/claude -name "mcp_server" -path "*gitea*" 2>/dev/null | head -5 -``` - -If venv doesn't exist, create it: -```bash -cd /path/to/mcp-servers/gitea && python3 -m venv .venv && source .venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt && deactivate -``` - -### Step 2.2: Gitea Configuration - -Create config directory: -```bash -mkdir -p ~/.config/claude -``` - -Use AskUserQuestion: -- Question: "What is your Gitea server URL?" -- Header: "Gitea URL" -- Options: - - "https://gitea.hotserv.cloud" - - "Other (I'll provide the URL)" - -Create configuration file (credentials only, org is per-project): -```bash -cat > ~/.config/claude/gitea.env << 'EOF' -# Gitea API Configuration -# Generated by pr-review /initial-setup -# Note: GITEA_ORG is configured per-project in .env - -GITEA_API_URL= -GITEA_API_TOKEN=PASTE_YOUR_TOKEN_HERE -EOF -chmod 600 ~/.config/claude/gitea.env -``` - -### Step 2.3: Token Instructions - -Display these instructions: - ---- - -**Action Required: Add Your Gitea API Token** - -I've created `~/.config/claude/gitea.env` but you need to add your API token manually. - -**Steps:** -1. Open: `nano ~/.config/claude/gitea.env` -2. Generate token in Gitea: Settings → Applications → Generate New Token - - Permissions needed: `repo`, `read:org`, `read:user` -3. Replace `PASTE_YOUR_TOKEN_HERE` with your token -4. Save the file - ---- - -Use AskUserQuestion: -- Question: "Have you added your Gitea token?" -- Header: "Token" -- Options: - - "Yes, I've added the token" - - "Skip for now" - ---- - -## Phase 3: Project Configuration - -### Step 3.1: Check Current Directory - -```bash -pwd && git rev-parse --show-toplevel 2>/dev/null || echo "NOT_A_GIT_REPO" -``` - -### Step 3.2: Check Existing Project Config - -```bash -cat .env 2>/dev/null | grep GITEA_REPO || echo "NOT_FOUND" -``` - -If `GITEA_REPO` is already set, skip to Phase 4. - -### Step 3.3: Detect Organization and Repository - -Extract organization: -```bash -git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\/[^/]*$/\1/' -``` - -Extract repository: -```bash -git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\.git$/\1/' | sed 's/.*\/\([^/]*\)$/\1/' -``` - -### Step 3.4: Validate Repository via Gitea API - -```bash -source ~/.config/claude/gitea.env -curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_API_TOKEN" "$GITEA_API_URL/repos//" -``` - -| HTTP Code | Action | -|-----------|--------| -| **200** | Auto-fill - "Verified: / exists" - skip to Step 3.7 | -| **404** | Not found - proceed to Step 3.5 | -| **401/403** | Permission issue - warn, proceed to Step 3.5 | - -### Step 3.5: Confirm Organization (only if validation failed) - -Use AskUserQuestion: -- Question: "Repository not found. Is '' the correct organization?" -- Header: "Organization" -- Options: - - "Yes, that's correct" - - "No, let me specify" - -### Step 3.6: Confirm Repository (only if validation failed) - -Use AskUserQuestion: -- Question: "Is '' the correct repository?" -- Header: "Repository" -- Options: - - "Yes, that's correct" - - "No, let me specify" - -**After corrections, re-validate via API (Step 3.4).** - -### Step 3.7: Create/Update Project Config - -If `.env` exists, append: -```bash -echo "GITEA_ORG=" >> .env -echo "GITEA_REPO=" >> .env -``` - -If `.env` doesn't exist: -```bash -cat > .env << 'EOF' -# Project Configuration -GITEA_ORG= -GITEA_REPO= -EOF -``` - -### Step 3.5: PR Review Settings (Optional) - -Use AskUserQuestion: -- Question: "Do you want to configure PR review settings?" -- Header: "Settings" -- Options: - - "Use defaults (Recommended)" - - "Let me customize" - -If customize, ask about: -- `PR_REVIEW_CONFIDENCE_THRESHOLD` (default: 0.5) -- `PR_REVIEW_AUTO_SUBMIT` (default: false) - ---- - -## Phase 4: Validation and Next Steps - -### Step 4.1: Test Configuration (if token was added) - -```bash -source ~/.config/claude/gitea.env && curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_API_TOKEN" "$GITEA_API_URL/user" -``` - -Report result: -- 200: Success -- 401: Invalid token -- Other: Connection issue - -### Step 4.2: Summary - -``` -╔════════════════════════════════════════════════════════════╗ -║ PR-REVIEW SETUP COMPLETE ║ -╠════════════════════════════════════════════════════════════╣ -║ MCP Server (Gitea): ✓ Ready ║ -║ System Config: ✓ ~/.config/claude/gitea.env ║ -║ Project Config: ✓ ./.env ║ -╚════════════════════════════════════════════════════════════╝ -``` - -### Step 4.3: Session Restart Notice - ---- - -**⚠️ Session Restart Required** - -Restart your Claude Code session for MCP tools to become available. - -**After restart, you can:** -- Run `/pr-review ` to review a pull request -- Run `/pr-summary ` for a quick summary -- Run `/pr-findings ` to list actionable findings - ---- +Test API connection, display completion summary, remind to restart session ## Available Commands After Setup -| Command | Description | -|---------|-------------| -| `/pr-review ` | Full multi-agent PR review with confidence scoring | -| `/pr-summary ` | Quick PR summary | -| `/pr-findings ` | List findings with severity and line numbers | +- `/pr-review ` - Full multi-agent review +- `/pr-summary ` - Quick summary +- `/pr-findings ` - List findings diff --git a/plugins/pr-review/commands/pr-diff.md b/plugins/pr-review/commands/pr-diff.md index 52ab643..ea28529 100644 --- a/plugins/pr-review/commands/pr-diff.md +++ b/plugins/pr-review/commands/pr-diff.md @@ -2,165 +2,47 @@ ## Visual Output -When executing this command, display the plugin header: +Display header: `PR-REVIEW - Diff Viewer` -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔍 PR-REVIEW · Diff Viewer │ -└──────────────────────────────────────────────────────────────────┘ -``` +## Skills to Load -Then proceed with the diff display. - -## Purpose - -Display the PR diff with inline annotations from review comments, making it easy to see what feedback has been given alongside the code changes. +- skills/mcp-tools-reference.md +- skills/pr-analysis.md +- skills/output-formats.md ## Usage ``` -/pr-diff [--repo owner/repo] [--context ] +/pr-diff [--repo owner/repo] [--context ] [--no-comments] [--file ] ``` -### Options +## Workflow -``` ---repo Override repository (default: from .env) ---context Lines of context around changes (default: 3) ---no-comments Show diff without comment annotations ---file Filter to specific files (glob pattern) -``` +### Step 1: Fetch Data -## Behavior - -### Step 1: Fetch PR Data - -Using Gitea MCP tools: -1. `get_pr_diff` - Unified diff of all changes -2. `get_pr_comments` - All review comments on the PR +Load MCP tools, then: `get_pr_diff`, `get_pr_comments` ### Step 2: Parse and Annotate -Parse the diff and overlay comments at their respective file/line positions: +Execute `skills/pr-analysis.md` Annotated Diff Display: +- Overlay comments at file/line positions +- Show commenter, timestamp, replies +- Mark resolved vs open -``` -═══════════════════════════════════════════════════ -PR #123 Diff - Add user authentication -═══════════════════════════════════════════════════ +### Step 3: Display -Branch: feat/user-auth → development -Files: 12 changed (+234 / -45) - -─────────────────────────────────────────────────── -src/api/users.ts (+85 / -12) -─────────────────────────────────────────────────── - -@@ -42,6 +42,15 @@ export async function getUser(id: string) { - 42 │ const db = getDatabase(); - 43 │ - 44 │- const user = db.query("SELECT * FROM users WHERE id = " + id); - │ ┌───────────────────────────────────────────────────────────── - │ │ COMMENT by @reviewer (2h ago): - │ │ This is a SQL injection vulnerability. Use parameterized - │ │ queries instead: `db.query("SELECT * FROM users WHERE id = ?", [id])` - │ └───────────────────────────────────────────────────────────── - 45 │+ const query = "SELECT * FROM users WHERE id = ?"; - 46 │+ const user = db.query(query, [id]); - 47 │ - 48 │ if (!user) { - 49 │ throw new NotFoundError("User not found"); - 50 │ } - -@@ -78,3 +87,12 @@ export async function updateUser(id: string, data: UserInput) { - 87 │+ // Validate input before update - 88 │+ validateUserInput(data); - 89 │+ - 90 │+ const result = db.query( - 91 │+ "UPDATE users SET name = ?, email = ? WHERE id = ?", - 92 │+ [data.name, data.email, id] - 93 │+ ); - │ ┌───────────────────────────────────────────────────────────── - │ │ COMMENT by @maintainer (1h ago): - │ │ Good use of parameterized query here! - │ │ - │ │ REPLY by @author (30m ago): - │ │ Thanks! Applied the same pattern throughout. - │ └───────────────────────────────────────────────────────────── - -─────────────────────────────────────────────────── -src/components/LoginForm.tsx (+65 / -0) [NEW FILE] -─────────────────────────────────────────────────── - -@@ -0,0 +1,65 @@ - 1 │+import React, { useState } from 'react'; - 2 │+import { useAuth } from '../context/AuthContext'; - 3 │+ - 4 │+export function LoginForm() { - 5 │+ const [email, setEmail] = useState(''); - 6 │+ const [password, setPassword] = useState(''); - 7 │+ const { login } = useAuth(); - -... (remaining diff content) - -═══════════════════════════════════════════════════ -Comment Summary: 5 comments, 2 resolved -═══════════════════════════════════════════════════ -``` - -### Step 3: Filter by Confidence (Optional) - -If `PR_REVIEW_CONFIDENCE_THRESHOLD` is set, also annotate with high-confidence findings from previous reviews: - -``` - 44 │- const user = db.query("SELECT * FROM users WHERE id = " + id); - │ ┌─── REVIEW FINDING (0.95 HIGH) ───────────────────────────── - │ │ [SEC-001] SQL Injection Vulnerability - │ │ Use parameterized queries to prevent injection attacks. - │ └───────────────────────────────────────────────────────────── - │ ┌─── COMMENT by @reviewer ──────────────────────────────────── - │ │ This is a SQL injection vulnerability... - │ └───────────────────────────────────────────────────────────── -``` - -## Output Formats - -### Default (Annotated Diff) - -Full diff with inline comments as shown above. - -### Plain (--no-comments) - -``` -/pr-diff 123 --no-comments - -# Standard unified diff output without annotations -``` - -### File Filter (--file) - -``` -/pr-diff 123 --file "src/api/*" - -# Shows diff only for files matching pattern -``` +Use annotated diff format from `skills/output-formats.md` ## Use Cases -- **Review preparation**: See the full context of changes with existing feedback -- **Followup work**: Understand what was commented on and where -- **Discussion context**: View threaded conversations alongside the code -- **Progress tracking**: See which comments have been resolved - -## Configuration - -| Variable | Default | Description | -|----------|---------|-------------| -| `PR_REVIEW_CONFIDENCE_THRESHOLD` | `0.7` | Minimum confidence for showing review findings | +- Review preparation with existing feedback +- Followup work - see what was commented +- Progress tracking on resolved comments ## Related Commands | Command | Purpose | |---------|---------| -| `/pr-summary` | Quick overview without diff | -| `/pr-review` | Full multi-agent review | -| `/pr-findings` | Filter review findings by category | +| `/pr-summary` | Quick overview | +| `/pr-review` | Full review | +| `/pr-findings` | Filter findings | diff --git a/plugins/pr-review/commands/pr-findings.md b/plugins/pr-review/commands/pr-findings.md index 00f9b9f..50ae9f1 100644 --- a/plugins/pr-review/commands/pr-findings.md +++ b/plugins/pr-review/commands/pr-findings.md @@ -2,148 +2,44 @@ ## Visual Output -When executing this command, display the plugin header: +Display header: `PR-REVIEW - Findings` -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔍 PR-REVIEW · Findings │ -└──────────────────────────────────────────────────────────────────┘ -``` +## Skills to Load -Then proceed with the findings display. - -## Purpose - -List and filter findings from a previous PR review by category, severity, or confidence level. +- skills/mcp-tools-reference.md +- skills/review-patterns/confidence-scoring.md +- skills/output-formats.md ## Usage ``` -/pr-findings [filters] +/pr-findings [--category ] [--severity ] [--confidence ] [--file ] [--compact] [--json] ``` -### Filters - -``` ---category Filter by category (security, performance, maintainability, tests) ---severity Filter by severity (critical, major, minor, suggestion) ---confidence Minimum confidence score (0.0-1.0) ---file Filter by file path pattern -``` - -## Examples - -``` -# Show only security findings -/pr-findings 123 --category security - -# Show critical and major issues only -/pr-findings 123 --severity critical,major - -# Show high-confidence findings only -/pr-findings 123 --confidence 0.8 - -# Show findings in specific files -/pr-findings 123 --file src/api/* -``` - -## Behavior +## Workflow ### Without Previous Review -If no review exists for this PR: - -``` -No review found for PR #123. - -Would you like to: -1. Run full /pr-review now -2. Run quick /pr-summary -3. Cancel -``` +Prompt: "No review found. Run /pr-review, /pr-summary, or cancel?" ### With Previous Review -Display filtered findings: - -``` -═══════════════════════════════════════════════════ -PR #123 Findings (filtered: security) -═══════════════════════════════════════════════════ - -Showing 3 of 8 total findings - -─────────────────────────────────────────────────── - -[SEC-001] SQL Injection Vulnerability -Confidence: 0.95 (HIGH) | Severity: Critical -File: src/api/users.ts:45 - -The query uses string interpolation without parameterization. - -Fix: Use parameterized queries. - -─────────────────────────────────────────────────── - -[SEC-002] Missing Input Validation -Confidence: 0.88 (MEDIUM) | Severity: Major -File: src/api/auth.ts:23 - -User input is passed directly to database without validation. - -Fix: Add input validation middleware. - -─────────────────────────────────────────────────── - -[SEC-003] Sensitive Data in Logs -Confidence: 0.72 (MEDIUM) | Severity: Minor -File: src/utils/logger.ts:15 - -Password field may be logged in debug mode. - -Fix: Sanitize sensitive fields before logging. - -═══════════════════════════════════════════════════ -``` +1. Load findings from previous review +2. Apply filters (category, severity, confidence, file) +3. Display using format from `skills/output-formats.md` ## Output Formats -### Default (Detailed) +Reference `skills/output-formats.md`: +- **Detailed** (default) - Full finding +- **Compact** (`--compact`) - Single line +- **JSON** (`--json`) - Structured data -Full finding details with descriptions and fixes. - -### Compact (--compact) +## Examples +```bash +/pr-findings 123 --category security +/pr-findings 123 --severity critical,major +/pr-findings 123 --confidence 0.8 +/pr-findings 123 --file src/api/* ``` -SEC-001 | Critical | 0.95 | src/api/users.ts:45 | SQL Injection -SEC-002 | Major | 0.88 | src/api/auth.ts:23 | Missing Validation -SEC-003 | Minor | 0.72 | src/utils/logger.ts | Sensitive Logs -``` - -### JSON (--json) - -```json -{ - "pr": 123, - "findings": [ - { - "id": "SEC-001", - "category": "security", - "severity": "critical", - "confidence": 0.95, - "file": "src/api/users.ts", - "line": 45, - "title": "SQL Injection Vulnerability", - "description": "...", - "fix": "..." - } - ] -} -``` - -## Use Cases - -- Focus on specific issue types -- Track resolution of findings -- Export findings for tracking -- Quick reference during fixes diff --git a/plugins/pr-review/commands/pr-review.md b/plugins/pr-review/commands/pr-review.md index e6ae203..cfec27c 100644 --- a/plugins/pr-review/commands/pr-review.md +++ b/plugins/pr-review/commands/pr-review.md @@ -2,19 +2,14 @@ ## Visual Output -When executing this command, display the plugin header: +Display header: `PR-REVIEW - Full Review` -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔍 PR-REVIEW · Full Review │ -└──────────────────────────────────────────────────────────────────┘ -``` +## Skills to Load -Then proceed with the review. - -## Purpose - -Conduct a comprehensive pull request review using specialized agents for security, performance, maintainability, and test coverage. +- skills/mcp-tools-reference.md +- skills/review-workflow.md +- skills/review-patterns/confidence-scoring.md +- skills/output-formats.md ## Usage @@ -22,132 +17,37 @@ Conduct a comprehensive pull request review using specialized agents for securit /pr-review [--repo owner/repo] ``` -## Behavior +## Workflow ### Step 1: Fetch PR Data -Using Gitea MCP tools: -1. `get_pull_request` - PR metadata -2. `get_pr_diff` - Code changes -3. `get_pr_comments` - Existing discussion +Load MCP tools, then: `get_pull_request`, `get_pr_diff`, `get_pr_comments` ### Step 2: Dispatch to Agents -The coordinator dispatches review tasks to specialized agents: +Execute `skills/review-workflow.md` - dispatch to Security, Performance, Maintainability, Test agents -``` -PR Review: #123 - Add user authentication -═══════════════════════════════════════════════════ +### Step 3: Aggregate and Filter -Dispatching to review agents: -├─ Security Reviewer → analyzing... -├─ Performance Analyst → analyzing... -├─ Maintainability Auditor → analyzing... -└─ Test Validator → analyzing... -``` +Apply confidence threshold (default: 0.7). See `skills/review-patterns/confidence-scoring.md` -### Step 3: Aggregate Findings +### Step 4: Generate Report -Collect findings from all agents, each with: -- Category (security, performance, maintainability, tests) -- Severity (critical, major, minor, suggestion) -- Confidence score (0.0 - 1.0) -- File and line reference -- Description -- Suggested fix (if applicable) +Use format from `skills/output-formats.md`. Group by severity: critical > major > minor > suggestion -### Step 4: Filter by Confidence +### Step 5: Determine Verdict -Filter findings based on `PR_REVIEW_CONFIDENCE_THRESHOLD` (default: 0.7): - -| Confidence | Label | Description | -|------------|-------|-------------| -| 0.9 - 1.0 | HIGH | Definite issue, must address | -| 0.7 - 0.89 | MEDIUM | Likely issue, should address | -| 0.5 - 0.69 | LOW | Possible concern, consider addressing | -| < threshold | (filtered) | Below configured threshold | - -**Note:** With the default threshold of 0.7, only MEDIUM and HIGH confidence findings are shown. Adjust `PR_REVIEW_CONFIDENCE_THRESHOLD` to include more or fewer findings. - -### Step 5: Generate Report - -``` -═══════════════════════════════════════════════════ -PR Review Report: #123 -═══════════════════════════════════════════════════ - -Summary: - Files changed: 12 - Lines added: 234 - Lines removed: 45 - -Findings: 8 total - 🔴 Critical: 1 - 🟠 Major: 2 - 🟡 Minor: 3 - 💡 Suggestions: 2 - -─────────────────────────────────────────────────── -CRITICAL FINDINGS -─────────────────────────────────────────────────── - -[SEC-001] SQL Injection Vulnerability (Confidence: 0.95) -File: src/api/users.ts:45 -Category: Security - -The query uses string interpolation without parameterization: -```ts -const query = `SELECT * FROM users WHERE id = ${userId}`; -``` - -Suggested fix: -```ts -const query = 'SELECT * FROM users WHERE id = ?'; -db.query(query, [userId]); -``` - -─────────────────────────────────────────────────── -MAJOR FINDINGS -─────────────────────────────────────────────────── - -[PERF-001] N+1 Query Pattern (Confidence: 0.82) -... - -─────────────────────────────────────────────────── -VERDICT -─────────────────────────────────────────────────── - -❌ REQUEST_CHANGES - -This PR has 1 critical security issue that must be addressed -before merging. See SEC-001 above. - -─────────────────────────────────────────────────── -``` +- Any critical or 2+ major: REQUEST_CHANGES +- Only minor/suggestions: COMMENT +- No significant findings: APPROVE ### Step 6: Submit Review (Optional) -``` -Submit this review to Gitea? -1. Yes, with REQUEST_CHANGES -2. Yes, as COMMENT only -3. No, just show me the report -``` - -If yes, use `create_pr_review` MCP tool. - -## Output - -Full review report with: -- Summary statistics -- Findings grouped by severity -- Code snippets with context -- Suggested fixes -- Overall verdict +Ask user to submit as REQUEST_CHANGES, COMMENT, or skip. Use `create_pr_review` MCP tool. ## Configuration -| Variable | Default | Description | -|----------|---------|-------------| -| `PR_REVIEW_CONFIDENCE_THRESHOLD` | `0.7` | Minimum confidence to report (0.0-1.0) | -| `PR_REVIEW_AUTO_SUBMIT` | `false` | Auto-submit to Gitea | +| Variable | Default | +|----------|---------| +| `PR_REVIEW_CONFIDENCE_THRESHOLD` | `0.7` | +| `PR_REVIEW_AUTO_SUBMIT` | `false` | diff --git a/plugins/pr-review/commands/pr-summary.md b/plugins/pr-review/commands/pr-summary.md index 02eaa6e..5a4cb3d 100644 --- a/plugins/pr-review/commands/pr-summary.md +++ b/plugins/pr-review/commands/pr-summary.md @@ -2,19 +2,13 @@ ## Visual Output -When executing this command, display the plugin header: +Display header: `PR-REVIEW - Quick Summary` -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔍 PR-REVIEW · Quick Summary │ -└──────────────────────────────────────────────────────────────────┘ -``` +## Skills to Load -Then proceed with the summary. - -## Purpose - -Generate a quick summary of PR changes without conducting a full multi-agent review. +- skills/mcp-tools-reference.md +- skills/pr-analysis.md +- skills/output-formats.md ## Usage @@ -22,94 +16,26 @@ Generate a quick summary of PR changes without conducting a full multi-agent rev /pr-summary [--repo owner/repo] ``` -## Behavior +## Workflow ### Step 1: Fetch PR Data -Using Gitea MCP tools: -1. `get_pull_request` - PR metadata -2. `get_pr_diff` - Code changes +Load MCP tools, then: `get_pull_request`, `get_pr_diff` ### Step 2: Analyze Changes -Quick analysis of: -- Files modified -- Types of changes (features, fixes, refactoring) -- Scope and impact +Execute `skills/pr-analysis.md`: +- Categorize changes (feature, fix, refactor) +- Calculate statistics +- Identify key files +- Assess scope and risk ### Step 3: Generate Summary -``` -═══════════════════════════════════════════════════ -PR Summary: #123 - Add user authentication -═══════════════════════════════════════════════════ - -Author: @johndoe -Branch: feat/user-auth → development -Status: Open (ready for review) - -─────────────────────────────────────────────────── -CHANGES OVERVIEW -─────────────────────────────────────────────────── - -Files: 12 changed - + 8 new files - ~ 3 modified files - - 1 deleted file - -Lines: +234 / -45 (net +189) - -─────────────────────────────────────────────────── -WHAT THIS PR DOES -─────────────────────────────────────────────────── - -This PR adds user authentication functionality: - -1. **New API endpoints** - - POST /api/auth/login - - POST /api/auth/register - - POST /api/auth/logout - -2. **Frontend components** - - LoginForm component - - RegisterForm component - - Auth context provider - -3. **Database changes** - - New users table - - Sessions table - -─────────────────────────────────────────────────── -KEY FILES -─────────────────────────────────────────────────── - -• src/api/auth/login.ts (+85) - Login endpoint -• src/api/auth/register.ts (+120) - Registration -• src/components/LoginForm.tsx (+65) - Login UI -• src/db/migrations/001_users.sql (+45) - Schema - -─────────────────────────────────────────────────── -QUICK ASSESSMENT -─────────────────────────────────────────────────── - -Scope: Medium (authentication feature) -Risk: Medium (new security-sensitive code) -Recommendation: Full /pr-review suggested - -═══════════════════════════════════════════════════ -``` - -## Output - -Summary report with: -- PR metadata -- Change statistics -- Plain-language description of changes -- Key files list -- Quick risk assessment +Use summary format from `skills/output-formats.md` ## When to Use -- Get quick overview before full review +- Quick overview before full review - Triage multiple PRs -- Understand PR scope +- Decide if /pr-review is needed diff --git a/plugins/pr-review/commands/project-init.md b/plugins/pr-review/commands/project-init.md index d5d0885..3a285aa 100644 --- a/plugins/pr-review/commands/project-init.md +++ b/plugins/pr-review/commands/project-init.md @@ -1,148 +1,45 @@ --- -description: Quick project setup - configures only project-level settings for PR review +description: Quick project setup - configures only project-level settings --- # Project Initialization (PR Review) ## Visual Output -When executing this command, display the plugin header: +Display header: `PR-REVIEW - Project Setup` -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔍 PR-REVIEW · Project Setup │ -└──────────────────────────────────────────────────────────────────┘ -``` +## Skills to Load -Then proceed with the setup. +- skills/setup-workflow.md +- skills/output-formats.md -Fast setup for a new project when system-level configuration is already complete. +## Purpose -**Use this when:** -- You've already run `/initial-setup` on this machine -- You're starting work on a new project/repository -- You just need to configure this project for PR reviews +Fast setup when system-level config already exists. ---- +**Use when:** Already ran `/initial-setup`, starting new project -## Pre-Flight Check +## Workflow -### Step 1: Verify System Configuration +### Pre-Flight Check -```bash -cat ~/.config/claude/gitea.env 2>/dev/null | grep -v "^#" | grep -v "PASTE_YOUR" | grep "GITEA_API_TOKEN=" && echo "SYSTEM_OK" || echo "SYSTEM_MISSING" -``` +Verify `~/.config/claude/gitea.env` exists. If missing: redirect to `/initial-setup` -**If SYSTEM_MISSING:** +### Project Setup ---- +Execute `skills/setup-workflow.md`: +1. Verify git repo +2. Check existing .env +3. Auto-detect org/repo from git remote +4. Validate via Gitea API +5. Create/update .env -**System configuration not found.** +### Complete -Please run `/initial-setup` first to configure Gitea credentials. +Display project configured format from `skills/output-formats.md` ---- +## Ready Commands -**If SYSTEM_OK:** Continue. - ---- - -## Project Setup - -### Step 2: Verify Current Directory - -```bash -pwd && git rev-parse --show-toplevel 2>/dev/null || echo "NOT_A_GIT_REPO" -``` - -### Step 3: Check Existing Configuration - -```bash -cat .env 2>/dev/null | grep "GITEA_REPO=" || echo "NOT_CONFIGURED" -``` - -If already configured, ask if user wants to keep or reconfigure. - -### Step 4: Detect Organization and Repository - -Extract organization: -```bash -git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\/[^/]*$/\1/' -``` - -Extract repository: -```bash -git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\.git$/\1/' | sed 's/.*\/\([^/]*\)$/\1/' -``` - -### Step 5: Validate Repository via Gitea API - -```bash -source ~/.config/claude/gitea.env -curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_API_TOKEN" "$GITEA_API_URL/repos//" -``` - -| HTTP Code | Action | -|-----------|--------| -| **200** | Auto-fill - "Verified: / exists" - skip to Step 8 | -| **404** | Not found - proceed to Step 6 | -| **401/403** | Permission issue - warn, proceed to Step 6 | - -### Step 6: Confirm Organization (only if validation failed) - -Use AskUserQuestion: -- Question: "Repository not found. Is '' the correct organization?" -- Header: "Organization" -- Options: - - "Yes, that's correct" - - "No, let me specify" - -### Step 7: Confirm Repository (only if validation failed) - -Use AskUserQuestion: -- Question: "Is '' the correct repository?" -- Header: "Repository" -- Options: - - "Yes, that's correct" - - "No, let me specify" - -**After corrections, re-validate via API (Step 5).** - -### Step 8: Create/Update .env - -```bash -echo "GITEA_ORG=" >> .env -echo "GITEA_REPO=" >> .env -``` - -### Step 9: Optional PR Review Settings - -Use AskUserQuestion: -- Question: "Configure PR review settings?" -- Header: "Settings" -- Options: - - "Use defaults (Recommended)" - - "Customize settings" - -If customize: -- `PR_REVIEW_CONFIDENCE_THRESHOLD` (default: 0.5) -- `PR_REVIEW_AUTO_SUBMIT` (default: false) - ---- - -## Complete - -``` -╔══════════════════════════════════════════════════════════════╗ -║ PROJECT CONFIGURED ║ -╠══════════════════════════════════════════════════════════════╣ -║ Organization: ║ -║ Repository: ║ -║ Config file: ./.env ║ -╚══════════════════════════════════════════════════════════════╝ - -Ready to review PRs: -• /pr-review - Full multi-agent review -• /pr-summary - Quick summary -• /pr-findings - List findings -``` +- `/pr-review ` - Full review +- `/pr-summary ` - Quick summary +- `/pr-findings ` - List findings diff --git a/plugins/pr-review/commands/project-sync.md b/plugins/pr-review/commands/project-sync.md index caa30f8..1e49d00 100644 --- a/plugins/pr-review/commands/project-sync.md +++ b/plugins/pr-review/commands/project-sync.md @@ -1,105 +1,32 @@ --- -description: Sync project configuration with current git remote - use after changing repository location +description: Sync project configuration with current git remote --- # Project Sync (PR Review) ## Visual Output -When executing this command, display the plugin header: +Display header: `PR-REVIEW - Project Sync` -``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🔍 PR-REVIEW · Project Sync │ -└──────────────────────────────────────────────────────────────────┘ -``` +## Skills to Load -Then proceed with the synchronization. +- skills/setup-workflow.md +- skills/output-formats.md -Updates project configuration when the git remote URL has changed. +## Purpose -**Use this when:** -- Repository was moved to a different organization -- Repository was renamed -- Git remote URL changed -- SessionStart hook detected a mismatch +Updates config when git remote URL changed. ---- +**Use when:** Repo moved/renamed, SessionStart detected mismatch -## Step 1: Verify System Configuration +## Workflow -```bash -cat ~/.config/claude/gitea.env 2>/dev/null | grep -v "^#" | grep -v "PASTE_YOUR" | grep "GITEA_API_TOKEN=" && echo "SYSTEM_OK" || echo "SYSTEM_MISSING" -``` +Execute `skills/setup-workflow.md` Sync Workflow: -**If SYSTEM_MISSING:** Run `/initial-setup` first. - ---- - -## Step 2: Read Current .env - -```bash -cat .env 2>/dev/null -``` - -Extract `GITEA_ORG` and `GITEA_REPO` values. - -**If missing:** Redirect to `/project-init`. - ---- - -## Step 3: Detect Git Remote - -```bash -git remote get-url origin 2>/dev/null -``` - -Extract organization and repository from URL. - ---- - -## Step 4: Compare Values - -| Scenario | Action | -|----------|--------| -| **Match** | "Configuration in sync" - exit | -| **Mismatch** | Show diff, proceed to validation | - ---- - -## Step 5: Validate via Gitea API - -```bash -source ~/.config/claude/gitea.env -curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_API_TOKEN" "$GITEA_API_URL/repos//" -``` - -| Code | Action | -|------|--------| -| **200** | Verified - proceed to update | -| **404** | Not found - ask to confirm | -| **401/403** | Permission issue - warn | - ---- - -## Step 6: Confirm and Update - -Use AskUserQuestion to confirm, then update .env: - -```bash -sed -i 's/^GITEA_ORG=.*/GITEA_ORG=/' .env -sed -i 's/^GITEA_REPO=.*/GITEA_REPO=/' .env -``` - ---- - -## Step 7: Confirm Success - -``` -╔══════════════════════════════════════════════════════════════╗ -║ CONFIGURATION UPDATED ║ -╠══════════════════════════════════════════════════════════════╣ -║ Organization: ║ -║ Repository: ║ -╚══════════════════════════════════════════════════════════════╝ -``` +1. Verify system config exists +2. Read current .env values +3. Detect org/repo from git remote +4. Compare - if match, exit; if mismatch, continue +5. Validate new values via API +6. Update .env with sed +7. Display confirmation from `skills/output-formats.md` diff --git a/plugins/pr-review/skills/mcp-tools-reference.md b/plugins/pr-review/skills/mcp-tools-reference.md new file mode 100644 index 0000000..a9f9ddf --- /dev/null +++ b/plugins/pr-review/skills/mcp-tools-reference.md @@ -0,0 +1,80 @@ +# MCP Tools Reference - Gitea PR Operations + +## Available Tools + +Use `ToolSearch` to load these tools before use. + +### Pull Request Tools + +| Tool | Purpose | +|------|---------| +| `mcp__gitea__list_pull_requests` | List PRs (open, closed, all) | +| `mcp__gitea__get_pull_request` | Get PR metadata, status, labels | +| `mcp__gitea__get_pr_diff` | Get unified diff of changes | +| `mcp__gitea__get_pr_comments` | Get review comments and discussions | +| `mcp__gitea__create_pr_review` | Submit review (approve, comment, request changes) | +| `mcp__gitea__add_pr_comment` | Add single comment to PR | +| `mcp__gitea__create_pull_request` | Create new PR | + +### Supporting Tools + +| Tool | Purpose | +|------|---------| +| `mcp__gitea__get_issue` | Get linked issue details | +| `mcp__gitea__get_labels` | Get available labels | +| `mcp__gitea__validate_repo_org` | Validate repository exists | + +## Loading Tools + +Before using MCP tools, load them: + +``` +Use ToolSearch with query: "+gitea pull_request" +``` + +## Common Operations + +### Fetch PR for Review + +``` +1. get_pull_request(pr_number) -> metadata +2. get_pr_diff(pr_number) -> code changes +3. get_pr_comments(pr_number) -> existing feedback +``` + +### Submit Review + +``` +create_pr_review: + pr_number: number + body: string (review summary) + event: "APPROVE" | "COMMENT" | "REQUEST_CHANGES" + comments: [{path, line, body}] (optional inline comments) +``` + +### Add Comment + +``` +add_pr_comment: + pr_number: number + body: string +``` + +## Environment Variables + +Required in `.env`: +- `GITEA_ORG` - Organization/owner name +- `GITEA_REPO` - Repository name + +Required in `~/.config/claude/gitea.env`: +- `GITEA_API_URL` - Gitea server URL +- `GITEA_API_TOKEN` - API token with repo permissions + +## Error Handling + +| Error | Cause | Resolution | +|-------|-------|------------| +| Tool not found | MCP not loaded | Run ToolSearch first | +| 401 Unauthorized | Invalid/expired token | Regenerate token | +| 404 Not Found | Wrong org/repo or PR doesn't exist | Check .env settings | +| 403 Forbidden | Insufficient permissions | Check token scopes | diff --git a/plugins/pr-review/skills/output-formats.md b/plugins/pr-review/skills/output-formats.md new file mode 100644 index 0000000..c363f9b --- /dev/null +++ b/plugins/pr-review/skills/output-formats.md @@ -0,0 +1,200 @@ +# Output Formats + +## Visual Header + +All commands display this header: + +``` ++----------------------------------------------------------------------+ +| PR-REVIEW [Command Name] | ++----------------------------------------------------------------------+ +``` + +## Review Report Format + +``` +=================================================== +PR Review Report: # +=================================================== + +Summary: + Files changed: + Lines: + / - + Agents consulted: + +Findings: + Critical: + Major: + Minor: + Suggestions: + +--------------------------------------------------- +CRITICAL FINDINGS +--------------------------------------------------- + +[] (Confidence: <score>) +File: <path>:<line> +Category: <category> + +<Description> + +Suggested fix: +<code block> + +--------------------------------------------------- +VERDICT: <APPROVE|COMMENT|REQUEST_CHANGES> +--------------------------------------------------- + +<Justification> +``` + +## Summary Format + +``` +=================================================== +PR Summary: #<number> - <title> +=================================================== + +Author: @<username> +Branch: <head> -> <base> +Status: <status> + +--------------------------------------------------- +CHANGES OVERVIEW +--------------------------------------------------- + +Files: <n> changed + + <n> new files + ~ <n> modified files + - <n> deleted files + +Lines: +<added> / -<removed> (net +<diff>) + +--------------------------------------------------- +WHAT THIS PR DOES +--------------------------------------------------- + +<Plain-language description> + +--------------------------------------------------- +KEY FILES +--------------------------------------------------- + +* <path> (+<lines>) - <description> + +--------------------------------------------------- +QUICK ASSESSMENT +--------------------------------------------------- + +Scope: <Small|Medium|Large> +Risk: <Low|Medium|High> +Recommendation: <action> +=================================================== +``` + +## Findings List Format + +### Detailed (default) + +``` +=================================================== +PR #<number> Findings (filtered: <filter>) +=================================================== + +Showing <n> of <total> findings + +--------------------------------------------------- + +[<ID>] <Title> +Confidence: <score> (<label>) | Severity: <level> +File: <path>:<line> + +<Description> + +Fix: <suggestion> + +--------------------------------------------------- +``` + +### Compact (--compact) + +``` +<ID> | <Severity> | <Confidence> | <File>:<Line> | <Title> +``` + +### JSON (--json) + +```json +{ + "pr": <number>, + "findings": [ + { + "id": "<ID>", + "category": "<category>", + "severity": "<severity>", + "confidence": <score>, + "file": "<path>", + "line": <number>, + "title": "<title>", + "description": "<description>", + "fix": "<suggestion>" + } + ] +} +``` + +## Setup Complete Format + +``` ++============================================================+ +| PR-REVIEW SETUP COMPLETE | ++============================================================+ +| MCP Server (Gitea): Ready | +| System Config: ~/.config/claude/gitea.env | +| Project Config: ./.env | ++============================================================+ +``` + +## Project Configured Format + +``` ++============================================================+ +| PROJECT CONFIGURED | ++============================================================+ +| Organization: <org> | +| Repository: <repo> | +| Config file: ./.env | ++============================================================+ + +Ready to review PRs: +- /pr-review <number> Full multi-agent review +- /pr-summary <number> Quick summary +- /pr-findings <number> List findings +``` + +## Annotated Diff Format + +``` +=================================================== +PR #<number> Diff - <title> +=================================================== + +Branch: <head> -> <base> +Files: <n> changed (+<added> / -<removed>) + +--------------------------------------------------- +<file> (+<added> / -<removed>) +--------------------------------------------------- + +@@ -<old>,<ctx> +<new>,<ctx> @@ <context> + <line> | existing code + <line> |- removed code + | +--- COMMENT by @<user> (<time>) --- + | | <comment text> + | +----------------------------------- + <line> |+ added code + +=================================================== +Comment Summary: <n> comments, <n> resolved +=================================================== +``` diff --git a/plugins/pr-review/skills/pr-analysis.md b/plugins/pr-review/skills/pr-analysis.md new file mode 100644 index 0000000..abacebf --- /dev/null +++ b/plugins/pr-review/skills/pr-analysis.md @@ -0,0 +1,135 @@ +# PR Analysis Patterns + +## Data Collection + +### Step 1: Fetch PR Metadata + +``` +get_pull_request(pr_number) returns: +- title, description +- author, assignees +- base/head branches +- status (open, closed, merged) +- labels, milestone +- created_at, updated_at +``` + +### Step 2: Get Code Changes + +``` +get_pr_diff(pr_number) returns: +- Unified diff format +- File paths with +/- indicators +- Hunk headers with line numbers +``` + +### Step 3: Get Existing Feedback + +``` +get_pr_comments(pr_number) returns: +- Review comments with file/line +- General comments +- Author, timestamp +- Thread context (replies) +``` + +## Change Analysis + +### Categorize Changes + +| Pattern | Category | +|---------|----------| +| New files only | Feature addition | +| Modified test files | Test updates | +| Modified + deleted | Refactoring | +| Single file fix | Bug fix | +| Config/docs only | Infrastructure | + +### Calculate Statistics + +- Files changed count +- Lines added/removed +- Net change (+added - removed) +- New vs modified vs deleted files + +### Identify Key Files + +Priority order: +1. Security-sensitive (`auth`, `crypto`, `sql`) +2. API endpoints +3. Database migrations +4. Core business logic +5. Utilities and helpers +6. Tests +7. Documentation + +## Risk Assessment + +### Scope Assessment + +| Files Changed | Lines Changed | Scope | +|---------------|---------------|-------| +| 1-3 | < 50 | Small | +| 4-10 | 50-200 | Medium | +| 10+ | 200+ | Large | + +### Risk Indicators + +| Indicator | Risk Level | +|-----------|------------| +| Security-sensitive files | High | +| Database migrations | High | +| API changes | Medium | +| New dependencies | Medium | +| Test-only changes | Low | +| Docs-only changes | Low | + +## Summary Generation + +### Quick Summary Template + +``` +This PR [adds|updates|fixes|removes] [feature/component]: + +1. **[Category 1]** + - Change description + +2. **[Category 2]** + - Change description + +Key files: +- path/to/important/file.ts (+lines) +``` + +### Assessment Template + +``` +Scope: [Small|Medium|Large] +Risk: [Low|Medium|High] +Recommendation: [/pr-review suggested | Looks good to merge] +``` + +## Annotated Diff Display + +### Format + +``` +File: src/api/users.ts (+85 / -12) +---------------------------------------- + +@@ -42,6 +42,15 @@ function description + 42 | existing line + 43 | + 44 |- removed line + | [COMMENT by @user (time ago)] + | Comment text here + 45 |+ added line + 46 |+ another added line +``` + +### Comment Overlay + +Position comments at their file/line locations: +- Show commenter username and time +- Include reply threads +- Mark resolved vs open diff --git a/plugins/pr-review/skills/review-workflow.md b/plugins/pr-review/skills/review-workflow.md new file mode 100644 index 0000000..2f0d9fe --- /dev/null +++ b/plugins/pr-review/skills/review-workflow.md @@ -0,0 +1,78 @@ +# Multi-Agent Review Workflow + +## Overview + +PR reviews use specialized agents that analyze different aspects of code changes. The coordinator dispatches to relevant agents and aggregates findings. + +## Agent Roles + +| Agent | Focus Area | File Patterns | +|-------|------------|---------------| +| **Security Reviewer** | Vulnerabilities, auth, injection | `*.ts`, `*.js`, `*.sql`, `*.py` | +| **Performance Analyst** | N+1, inefficient algorithms, memory | `*.ts`, `*.js`, `*.py`, `*.go` | +| **Maintainability Auditor** | Complexity, readability, DRY | All code files | +| **Test Validator** | Coverage, edge cases, assertions | `*.test.*`, `*_test.*`, `*_spec.*` | + +## Dispatch Logic + +1. **Analyze changed files** - Identify file types and patterns +2. **Select agents** - Match files to relevant agents +3. **Parallel dispatch** - Send review tasks to agents +4. **Collect findings** - Aggregate results from all agents +5. **Filter by confidence** - Apply threshold (default: 0.7) +6. **Generate report** - Structure findings by severity + +### Skip Patterns + +Don't dispatch agents for: +- `*.md`, `*.txt` - Documentation only +- `*.json` (config) - Unless security-sensitive +- Generated files - `*.min.js`, `*.d.ts`, etc. + +## Finding Structure + +Each finding includes: + +``` +{ + id: "SEC-001", + category: "security" | "performance" | "maintainability" | "tests", + severity: "critical" | "major" | "minor" | "suggestion", + confidence: 0.0 - 1.0, + file: "src/api/users.ts", + line: 45, + title: "SQL Injection Vulnerability", + description: "Detailed explanation...", + fix: "Suggested code fix..." (optional) +} +``` + +## Verdict Logic + +| Condition | Verdict | +|-----------|---------| +| Any critical finding | REQUEST_CHANGES | +| 2+ major findings | REQUEST_CHANGES | +| Only minor/suggestions | COMMENT | +| No significant findings | APPROVE | + +## Confidence Thresholds + +Reference: `skills/review-patterns/confidence-scoring.md` + +| Range | Label | Action | +|-------|-------|--------| +| 0.9 - 1.0 | HIGH | Must address | +| 0.7 - 0.89 | MEDIUM | Should address | +| 0.5 - 0.69 | LOW | Consider addressing | +| < threshold | Filtered | Not shown | + +Default threshold: 0.7 (MEDIUM and above) + +## Aggregation Rules + +When multiple agents find the same issue: +1. Keep highest confidence score +2. Merge descriptions +3. Use most severe category +4. Deduplicate fixes diff --git a/plugins/pr-review/skills/setup-workflow.md b/plugins/pr-review/skills/setup-workflow.md new file mode 100644 index 0000000..b4b262d --- /dev/null +++ b/plugins/pr-review/skills/setup-workflow.md @@ -0,0 +1,104 @@ +# Setup Workflow + +## Configuration Hierarchy + +| Level | Location | Contents | +|-------|----------|----------| +| System | `~/.config/claude/gitea.env` | API URL, token (shared across projects) | +| Project | `.env` in project root | Org, repo name (per project) | + +## System Configuration + +### Check Existing + +```bash +cat ~/.config/claude/gitea.env 2>/dev/null | grep -v "^#" | grep "GITEA_API_TOKEN=" && echo "OK" || echo "MISSING" +``` + +### Create New + +```bash +mkdir -p ~/.config/claude +cat > ~/.config/claude/gitea.env << 'EOF' +# Gitea API Configuration +GITEA_API_URL=https://your-gitea-server.com +GITEA_API_TOKEN=PASTE_YOUR_TOKEN_HERE +EOF +chmod 600 ~/.config/claude/gitea.env +``` + +### Token Generation + +1. Gitea: Settings > Applications > Generate New Token +2. Required scopes: `repo`, `read:org`, `read:user` + +## Project Configuration + +### Auto-Detect from Git Remote + +Extract organization: +```bash +git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\/[^/]*$/\1/' +``` + +Extract repository: +```bash +git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\.git$/\1/' | sed 's/.*\/\([^/]*\)$/\1/' +``` + +### Validate via API + +```bash +source ~/.config/claude/gitea.env +curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_API_TOKEN" "$GITEA_API_URL/repos/<org>/<repo>" +``` + +| Code | Meaning | +|------|---------| +| 200 | Repository verified | +| 404 | Not found - check org/repo names | +| 401/403 | Auth issue - check token | + +### Create/Update .env + +```bash +# New file +cat > .env << EOF +GITEA_ORG=<org> +GITEA_REPO=<repo> +EOF + +# Or append to existing +echo "GITEA_ORG=<org>" >> .env +echo "GITEA_REPO=<repo>" >> .env +``` + +## PR Review Settings (Optional) + +| Variable | Default | Description | +|----------|---------|-------------| +| `PR_REVIEW_CONFIDENCE_THRESHOLD` | `0.7` | Minimum confidence to report | +| `PR_REVIEW_AUTO_SUBMIT` | `false` | Auto-submit reviews to Gitea | + +## Sync Workflow + +When git remote changes: + +1. Detect new org/repo from git remote +2. Compare with .env values +3. Validate new values via API +4. Update .env with sed: + +```bash +sed -i 's/^GITEA_ORG=.*/GITEA_ORG=<new_org>/' .env +sed -i 's/^GITEA_REPO=.*/GITEA_REPO=<new_repo>/' .env +``` + +## Shared with projman + +The Gitea MCP server is shared with the projman plugin. If projman is already configured, system-level setup can be skipped. + +Check for projman: +```bash +find ~/.claude ~/.config/claude -name "projman" -type d 2>/dev/null | head -1 +``` diff --git a/plugins/viz-platform/commands/accessibility-check.md b/plugins/viz-platform/commands/accessibility-check.md index e1cd65f..86e116e 100644 --- a/plugins/viz-platform/commands/accessibility-check.md +++ b/plugins/viz-platform/commands/accessibility-check.md @@ -4,19 +4,19 @@ description: Validate color accessibility for color blind users # Accessibility Check +## Skills to Load +- skills/mcp-tools-reference.md +- skills/accessibility-rules.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🎨 VIZ-PLATFORM · Accessibility Check │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| VIZ-PLATFORM - Accessibility Check | ++------------------------------------------------------------------+ ``` -Then proceed with the accessibility validation. - -Validate theme or chart colors for color blind accessibility, checking contrast ratios and suggesting alternatives. +Validate theme or chart colors for color blind accessibility. ## Usage @@ -28,129 +28,18 @@ Validate theme or chart colors for color blind accessibility, checking contrast - `target` (optional): "theme" or "chart" - defaults to active theme -## Examples - -``` -/accessibility-check -/accessibility-check theme -/accessibility-check chart -``` - ## Tool Mapping -This command uses the `accessibility_validate_colors` MCP tool: - ```python accessibility_validate_colors( - colors=["#228be6", "#40c057", "#fa5252"], # Colors to check + colors=["#228be6", "#40c057"], check_types=["deuteranopia", "protanopia", "tritanopia"], - min_contrast_ratio=4.5 # WCAG AA standard + min_contrast_ratio=4.5 ) -``` - -Or validate a full theme: -```python -accessibility_validate_theme( - theme_name="corporate" -) -``` - -## Workflow - -1. **User invokes**: `/accessibility-check theme` -2. **Tool analyzes**: Theme color palette -3. **Tool simulates**: Color perception for each deficiency type -4. **Tool checks**: Contrast ratios between color pairs -5. **Tool returns**: Issues found and alternative suggestions - -## Color Blindness Types - -| Type | Affected Colors | Population | -|------|-----------------|------------| -| **Deuteranopia** | Red-Green (green-blind) | ~6% males, 0.4% females | -| **Protanopia** | Red-Green (red-blind) | ~2.5% males, 0.05% females | -| **Tritanopia** | Blue-Yellow | ~0.01% total | - -## Output Example - -```json -{ - "theme_name": "corporate", - "overall_score": "B", - "issues": [ - { - "type": "contrast", - "severity": "warning", - "colors": ["#fa5252", "#40c057"], - "affected_by": ["deuteranopia", "protanopia"], - "message": "Red and green may be indistinguishable for red-green color blind users", - "suggestion": "Use blue (#228be6) instead of green to differentiate from red" - }, - { - "type": "contrast_ratio", - "severity": "error", - "colors": ["#fab005", "#ffffff"], - "ratio": 2.1, - "required": 4.5, - "message": "Insufficient contrast for WCAG AA compliance", - "suggestion": "Darken yellow to #e6a200 for ratio of 4.5+" - } - ], - "recommendations": [ - "Add patterns or shapes to distinguish data series, not just color", - "Include labels directly on chart elements", - "Consider using a color-blind safe palette" - ], - "safe_palettes": { - "categorical": ["#4477AA", "#EE6677", "#228833", "#CCBB44", "#66CCEE", "#AA3377", "#BBBBBB"], - "sequential": ["#FEE0D2", "#FC9272", "#DE2D26"], - "diverging": ["#4575B4", "#FFFFBF", "#D73027"] - } -} -``` - -## WCAG Contrast Standards - -| Level | Ratio | Use Case | -|-------|-------|----------| -| AA (normal text) | 4.5:1 | Body text, labels | -| AA (large text) | 3:1 | Headings, 14pt+ bold | -| AAA (enhanced) | 7:1 | Highest accessibility | - -## Color-Blind Safe Palettes - -The tool can suggest complete color-blind safe palettes: - -### IBM Design Colors -Designed for accessibility: -``` -#648FFF #785EF0 #DC267F #FE6100 #FFB000 -``` - -### Tableau Colorblind 10 -Industry-standard accessible palette: -``` -#006BA4 #FF800E #ABABAB #595959 #5F9ED1 -#C85200 #898989 #A2C8EC #FFBC79 #CFCFCF -``` - -### Okabe-Ito -Optimized for all types of color blindness: -``` -#E69F00 #56B4E9 #009E73 #F0E442 #0072B2 -#D55E00 #CC79A7 #000000 +accessibility_validate_theme(theme_name="corporate") ``` ## Related Commands -- `/theme-new {name}` - Create accessible theme from the start -- `/theme-validate {name}` - General theme validation +- `/theme-new {name}` - Create accessible theme - `/chart {type}` - Create chart (check colors after) - -## Best Practices - -1. **Don't rely on color alone** - Use shapes, patterns, or labels -2. **Test with simulation** - View your visualizations through color blindness simulators -3. **Use sufficient contrast** - Minimum 4.5:1 for text, 3:1 for large elements -4. **Limit color count** - Fewer colors = easier to distinguish -5. **Use semantic colors** - Blue for information, red for errors (with icons) diff --git a/plugins/viz-platform/commands/breakpoints.md b/plugins/viz-platform/commands/breakpoints.md index 02d9a9f..62e0166 100644 --- a/plugins/viz-platform/commands/breakpoints.md +++ b/plugins/viz-platform/commands/breakpoints.md @@ -4,19 +4,19 @@ description: Configure responsive breakpoints for dashboard layouts # Configure Breakpoints +## Skills to Load +- skills/mcp-tools-reference.md +- skills/responsive-design.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🎨 VIZ-PLATFORM · Breakpoints │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| VIZ-PLATFORM - Breakpoints | ++------------------------------------------------------------------+ ``` -Then proceed with the configuration. - -Configure responsive breakpoints for a layout to support mobile-first design across different screen sizes. +Configure responsive breakpoints for mobile-first design across screen sizes. ## Usage @@ -28,178 +28,16 @@ Configure responsive breakpoints for a layout to support mobile-first design acr - `layout_ref` (required): Layout name to configure breakpoints for -## Examples - -``` -/breakpoints my-dashboard -/breakpoints sales-report -``` - -## Tool Mapping - -This command uses the `layout_set_breakpoints` MCP tool: - -```python -layout_set_breakpoints( - layout_ref="my-dashboard", - breakpoints={ - "xs": {"cols": 1, "spacing": "xs"}, # < 576px (mobile) - "sm": {"cols": 2, "spacing": "sm"}, # >= 576px (large mobile) - "md": {"cols": 6, "spacing": "md"}, # >= 768px (tablet) - "lg": {"cols": 12, "spacing": "md"}, # >= 992px (desktop) - "xl": {"cols": 12, "spacing": "lg"} # >= 1200px (large desktop) - }, - mobile_first=True -) -``` - ## Workflow 1. **User invokes**: `/breakpoints my-dashboard` 2. **Agent asks**: Which breakpoints to customize? (shows current settings) 3. **Agent asks**: Mobile column count? (xs, typically 1-2) 4. **Agent asks**: Tablet column count? (md, typically 4-6) -5. **Agent applies**: Breakpoint configuration +5. **Agent applies**: Breakpoint configuration via `layout_set_breakpoints` 6. **Agent returns**: Complete responsive configuration -## Breakpoint Sizes - -| Name | Min Width | Common Devices | -|------|-----------|----------------| -| `xs` | 0px | Small phones (portrait) | -| `sm` | 576px | Large phones, small tablets | -| `md` | 768px | Tablets (portrait) | -| `lg` | 992px | Tablets (landscape), laptops | -| `xl` | 1200px | Desktops, large screens | - -## Mobile-First Approach - -When `mobile_first=True` (default), styles cascade up: -- Define base styles for `xs` (mobile) -- Override only what changes at larger breakpoints -- Smaller CSS footprint, better performance - -```python -# Mobile-first example -{ - "xs": {"cols": 1}, # Stack everything on mobile - "md": {"cols": 6}, # Two-column on tablet - "lg": {"cols": 12} # Full grid on desktop -} -``` - -When `mobile_first=False`, styles cascade down: -- Define base styles for `xl` (desktop) -- Override for smaller screens -- Traditional "desktop-first" approach - -## Grid Configuration per Breakpoint - -Each breakpoint can configure: - -| Property | Description | Values | -|----------|-------------|--------| -| `cols` | Grid column count | 1-24 | -| `spacing` | Gap between items | xs, sm, md, lg, xl | -| `gutter` | Outer padding | xs, sm, md, lg, xl | -| `grow` | Items grow to fill | true, false | - -## Common Patterns - -### Dashboard (Charts & Filters) -```python -{ - "xs": {"cols": 1, "spacing": "xs"}, # Full-width cards - "sm": {"cols": 2, "spacing": "sm"}, # 2 cards per row - "md": {"cols": 3, "spacing": "md"}, # 3 cards per row - "lg": {"cols": 4, "spacing": "md"}, # 4 cards per row - "xl": {"cols": 6, "spacing": "lg"} # 6 cards per row -} -``` - -### Data Table -```python -{ - "xs": {"cols": 1, "scroll": true}, # Horizontal scroll - "md": {"cols": 1, "scroll": false}, # Full table visible - "lg": {"cols": 1} # Same as md -} -``` - -### Form Layout -```python -{ - "xs": {"cols": 1}, # Single column - "md": {"cols": 2}, # Two columns - "lg": {"cols": 3} # Three columns -} -``` - -### Sidebar Layout -```python -{ - "xs": {"sidebar": "hidden"}, # No sidebar on mobile - "md": {"sidebar": "collapsed"}, # Icon-only sidebar - "lg": {"sidebar": "expanded"} # Full sidebar -} -``` - -## Component Span - -Control how many columns a component spans at each breakpoint: - -```python -# A chart that spans full width on mobile, half on desktop -{ - "component": "sales-chart", - "span": { - "xs": 1, # Full width (1/1) - "md": 3, # Half width (3/6) - "lg": 6 # Half width (6/12) - } -} -``` - -## DMC Grid Integration - -This maps to Dash Mantine Components Grid: - -```python -dmc.Grid( - children=[ - dmc.GridCol( - children=[chart], - span={"base": 12, "sm": 6, "lg": 4} # Responsive span - ) - ], - gutter="md" -) -``` - -## Output - -```json -{ - "layout_ref": "my-dashboard", - "breakpoints": { - "xs": {"cols": 1, "spacing": "xs", "min_width": "0px"}, - "sm": {"cols": 2, "spacing": "sm", "min_width": "576px"}, - "md": {"cols": 6, "spacing": "md", "min_width": "768px"}, - "lg": {"cols": 12, "spacing": "md", "min_width": "992px"}, - "xl": {"cols": 12, "spacing": "lg", "min_width": "1200px"} - }, - "mobile_first": true, - "css_media_queries": [ - "@media (min-width: 576px) { ... }", - "@media (min-width: 768px) { ... }", - "@media (min-width: 992px) { ... }", - "@media (min-width: 1200px) { ... }" - ] -} -``` - ## Related Commands - `/dashboard {template}` - Create layout with default breakpoints -- `/layout-set-grid` - Configure grid without responsive settings - `/theme {name}` - Theme includes default spacing values diff --git a/plugins/viz-platform/commands/chart-export.md b/plugins/viz-platform/commands/chart-export.md index d2eab1a..0f25060 100644 --- a/plugins/viz-platform/commands/chart-export.md +++ b/plugins/viz-platform/commands/chart-export.md @@ -4,19 +4,19 @@ description: Export a Plotly chart to PNG, SVG, or PDF format # Export Chart +## Skills to Load +- skills/mcp-tools-reference.md +- skills/chart-types.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🎨 VIZ-PLATFORM · Chart Export │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| VIZ-PLATFORM - Chart Export | ++------------------------------------------------------------------+ ``` -Then proceed with the export. - -Export a Plotly chart to static image formats for sharing, embedding, or printing. +Export a Plotly chart to static image formats. ## Usage @@ -26,101 +26,17 @@ Export a Plotly chart to static image formats for sharing, embedding, or printin ## Arguments -- `format` (required): Output format - one of: png, svg, pdf - -## Examples - -``` -/chart-export png -/chart-export svg -/chart-export pdf -``` +- `format` (required): png, svg, or pdf ## Tool Mapping -This command uses the `chart_export` MCP tool: - ```python -chart_export( - figure=figure_json, # Plotly figure JSON from chart_create - format="png", # Output format: png, svg, pdf - width=1200, # Optional: image width in pixels - height=800, # Optional: image height in pixels - scale=2, # Optional: resolution scale factor - output_path=None # Optional: save to file path -) +chart_export(figure=figure_json, format="png", width=1200, height=800, scale=2) ``` -## Workflow - -1. **User invokes**: `/chart-export png` -2. **Agent asks**: Which chart to export? (if multiple charts in context) -3. **Agent asks**: Image dimensions? (optional, uses chart defaults) -4. **Agent exports**: Chart with `chart_export` tool -5. **Agent returns**: Base64 image data or file path - -## Output Formats - -| Format | Best For | File Size | -|--------|----------|-----------| -| `png` | Web, presentations, general use | Medium | -| `svg` | Scalable graphics, editing | Small | -| `pdf` | Print, documents, archival | Large | - -## Resolution Options - -### Width & Height -Specify exact pixel dimensions: -```python -chart_export(figure, format="png", width=1920, height=1080) -``` - -### Scale Factor -Increase resolution for high-DPI displays: -```python -chart_export(figure, format="png", scale=3) # 3x resolution -``` - -Common scale values: -- `1` - Standard resolution (72 DPI) -- `2` - Retina/HiDPI (144 DPI) -- `3` - Print quality (216 DPI) -- `4` - High-quality print (288 DPI) - -## Output Options - -### Return as Base64 -Default behavior - returns base64-encoded image data: -```python -result = chart_export(figure, format="png") -# result["image_data"] contains base64 string -``` - -### Save to File -Specify output path to save directly: -```python -chart_export(figure, format="png", output_path="/path/to/chart.png") -# result["file_path"] contains the saved path -``` - -## Requirements - -This tool requires the `kaleido` package for rendering: -```bash -pip install kaleido -``` - -Kaleido is a cross-platform library that renders Plotly figures without a browser. - -## Error Handling - -Common issues: -- **Kaleido not installed**: Install with `pip install kaleido` -- **Invalid figure**: Ensure figure is valid Plotly JSON -- **Permission denied**: Check write permissions for output path +Requires `kaleido` package: `pip install kaleido` ## Related Commands - `/chart {type}` - Create a chart - `/theme {name}` - Apply theme before export -- `/dashboard` - Create layout containing charts diff --git a/plugins/viz-platform/commands/chart.md b/plugins/viz-platform/commands/chart.md index 5f98443..47ecbf3 100644 --- a/plugins/viz-platform/commands/chart.md +++ b/plugins/viz-platform/commands/chart.md @@ -4,18 +4,18 @@ description: Create a Plotly chart with theme integration # Create Chart +## Skills to Load +- skills/mcp-tools-reference.md +- skills/chart-types.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🎨 VIZ-PLATFORM · Chart Builder │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| VIZ-PLATFORM - Chart Builder | ++------------------------------------------------------------------+ ``` -Then proceed with the chart creation. - Create a Plotly chart with automatic theme token application. ## Usage @@ -26,73 +26,16 @@ Create a Plotly chart with automatic theme token application. ## Arguments -- `type` (required): Chart type - one of: line, bar, scatter, pie, area, histogram, box, heatmap, sunburst, treemap - -## Examples - -``` -/chart line -/chart bar -/chart scatter -/chart pie -``` +- `type` (required): line, bar, scatter, pie, area, histogram, box, heatmap, sunburst, treemap ## Tool Mapping -This command uses the `chart_create` MCP tool: - ```python -chart_create( - chart_type="line", - data_ref="df_sales", # Reference to loaded DataFrame - x="date", # X-axis column - y="revenue", # Y-axis column - color=None, # Optional: column for color grouping - title="Sales Over Time", # Optional: chart title - theme=None # Optional: theme name to apply -) +chart_create(chart_type="line", data_ref="df", x="date", y="value", theme=None) ``` -## Workflow +## Related Commands -1. **User invokes**: `/chart line` -2. **Agent asks**: Which DataFrame to use? (list available with `list_data` from data-platform) -3. **Agent asks**: Which columns for X and Y axes? -4. **Agent asks**: Any grouping/color column? -5. **Agent creates**: Chart with `chart_create` tool -6. **Agent returns**: Plotly figure JSON ready for rendering - -## Chart Types - -| Type | Best For | -|------|----------| -| `line` | Time series, trends | -| `bar` | Comparisons, categories | -| `scatter` | Correlations, distributions | -| `pie` | Part-to-whole relationships | -| `area` | Cumulative trends | -| `histogram` | Frequency distributions | -| `box` | Statistical distributions | -| `heatmap` | Matrix correlations | -| `sunburst` | Hierarchical data | -| `treemap` | Hierarchical proportions | - -## Theme Integration - -Charts automatically inherit colors from the active theme: -- Primary color for main data -- Color palette for multi-series -- Font family and sizes -- Background colors - -Override with explicit theme: -```python -chart_create(chart_type="bar", ..., theme="my-dark-theme") -``` - -## Output - -Returns Plotly figure JSON that can be: -- Rendered in a Dash app -- Saved as HTML/PNG -- Embedded in a layout component +- `/chart-export {format}` - Export chart to image +- `/theme {name}` - Apply theme to charts +- `/dashboard` - Create layout with charts diff --git a/plugins/viz-platform/commands/component.md b/plugins/viz-platform/commands/component.md index 66ef550..6386706 100644 --- a/plugins/viz-platform/commands/component.md +++ b/plugins/viz-platform/commands/component.md @@ -4,19 +4,19 @@ description: Inspect Dash Mantine Component props and validation # Inspect Component +## Skills to Load +- skills/mcp-tools-reference.md +- skills/dmc-components.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🎨 VIZ-PLATFORM · Component Inspector │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| VIZ-PLATFORM - Component Inspector | ++------------------------------------------------------------------+ ``` -Then proceed with the inspection. - -Inspect a Dash Mantine Component's available props, types, and defaults. +Inspect a DMC component's props, types, and defaults. ## Usage @@ -28,145 +28,14 @@ Inspect a Dash Mantine Component's available props, types, and defaults. - `name` (required): DMC component name (e.g., Button, Card, TextInput) -## Examples - -``` -/component Button -/component TextInput -/component Select -/component Card -``` - ## Tool Mapping -This command uses the `get_component_props` MCP tool: - ```python get_component_props(component="Button") +list_components(category="inputs") +validate_component(component="Button", props={"variant": "filled"}) ``` -## Output Example - -```json -{ - "component": "Button", - "category": "inputs", - "props": { - "children": { - "type": "any", - "required": false, - "description": "Button content" - }, - "variant": { - "type": "string", - "enum": ["filled", "outline", "light", "subtle", "default", "gradient"], - "default": "filled", - "description": "Button appearance variant" - }, - "color": { - "type": "string", - "default": "blue", - "description": "Button color from theme" - }, - "size": { - "type": "string", - "enum": ["xs", "sm", "md", "lg", "xl"], - "default": "sm", - "description": "Button size" - }, - "radius": { - "type": "string", - "enum": ["xs", "sm", "md", "lg", "xl"], - "default": "sm", - "description": "Border radius" - }, - "disabled": { - "type": "boolean", - "default": false, - "description": "Disable button" - }, - "loading": { - "type": "boolean", - "default": false, - "description": "Show loading indicator" - }, - "fullWidth": { - "type": "boolean", - "default": false, - "description": "Button takes full width" - } - } -} -``` - -## Listing All Components - -To see all available components: - -```python -list_components(category=None) # All components -list_components(category="inputs") # Just input components -``` - -### Component Categories - -| Category | Components | -|----------|------------| -| `inputs` | Button, TextInput, Select, Checkbox, Radio, Switch, Slider, etc. | -| `navigation` | NavLink, Tabs, Breadcrumbs, Pagination, Stepper | -| `feedback` | Alert, Notification, Progress, Loader, Skeleton | -| `overlays` | Modal, Drawer, Tooltip, Popover, Menu | -| `typography` | Text, Title, Code, Blockquote, List | -| `layout` | Container, Grid, Stack, Group, Space, Divider | -| `data` | Table, Badge, Card, Paper, Timeline | - -## Validating Component Usage - -After inspecting props, validate your usage: - -```python -validate_component( - component="Button", - props={ - "variant": "filled", - "color": "blue", - "size": "lg", - "children": "Click me" - } -) -``` - -Returns: -```json -{ - "valid": true, - "errors": [], - "warnings": [] -} -``` - -Or with errors: -```json -{ - "valid": false, - "errors": [ - "Invalid prop 'colour' for Button. Did you mean 'color'?", - "Prop 'size' expects one of ['xs', 'sm', 'md', 'lg', 'xl'], got 'huge'" - ], - "warnings": [ - "Prop 'fullwidth' should be 'fullWidth' (camelCase)" - ] -} -``` - -## Why This Matters - -DMC components have many props with specific type constraints. This tool: -- Prevents hallucinated prop names -- Validates enum values -- Catches typos before runtime -- Documents available options - ## Related Commands - `/chart {type}` - Create charts diff --git a/plugins/viz-platform/commands/dashboard.md b/plugins/viz-platform/commands/dashboard.md index 531d227..08bef6e 100644 --- a/plugins/viz-platform/commands/dashboard.md +++ b/plugins/viz-platform/commands/dashboard.md @@ -4,19 +4,19 @@ description: Create a dashboard layout with the layout-builder agent # Create Dashboard +## Skills to Load +- skills/mcp-tools-reference.md +- skills/layout-templates.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🎨 VIZ-PLATFORM · Dashboard Builder │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| VIZ-PLATFORM - Dashboard Builder | ++------------------------------------------------------------------+ ``` -Then proceed with the dashboard creation. - -Create a dashboard layout structure with filters, grids, and sections. +Create a dashboard layout with filters, grids, and sections. ## Usage @@ -26,102 +26,16 @@ Create a dashboard layout structure with filters, grids, and sections. ## Arguments -- `template` (optional): Layout template - one of: basic, sidebar, tabs, split - -## Examples - -``` -/dashboard # Interactive layout builder -/dashboard basic # Simple single-column layout -/dashboard sidebar # Layout with sidebar navigation -/dashboard tabs # Tabbed multi-page layout -/dashboard split # Split-pane layout -``` +- `template` (optional): basic, sidebar, tabs, split ## Agent Mapping -This command activates the **layout-builder** agent which orchestrates multiple tools: +Activates **layout-builder** agent which orchestrates: +- `layout_create` - Create base layout structure +- `layout_add_filter` - Add filter components +- `layout_set_grid` - Configure responsive grid -1. `layout_create` - Create the base layout structure -2. `layout_add_filter` - Add filter components (dropdowns, date pickers) -3. `layout_set_grid` - Configure responsive grid settings -4. `layout_add_section` - Add content sections +## Related Commands -## Workflow - -1. **User invokes**: `/dashboard sidebar` -2. **Agent asks**: What is the dashboard purpose? -3. **Agent asks**: What filters are needed? -4. **Agent creates**: Base layout with `layout_create` -5. **Agent adds**: Filters with `layout_add_filter` -6. **Agent configures**: Grid with `layout_set_grid` -7. **Agent returns**: Complete layout structure - -## Templates - -### Basic -Single-column layout with header and content area. -``` -┌─────────────────────────────┐ -│ Header │ -├─────────────────────────────┤ -│ │ -│ Content │ -│ │ -└─────────────────────────────┘ -``` - -### Sidebar -Layout with collapsible sidebar navigation. -``` -┌────────┬────────────────────┐ -│ │ Header │ -│ Nav ├────────────────────┤ -│ │ │ -│ │ Content │ -│ │ │ -└────────┴────────────────────┘ -``` - -### Tabs -Tabbed layout for multi-page dashboards. -``` -┌─────────────────────────────┐ -│ Header │ -├──────┬──────┬──────┬────────┤ -│ Tab1 │ Tab2 │ Tab3 │ │ -├──────┴──────┴──────┴────────┤ -│ │ -│ Tab Content │ -│ │ -└─────────────────────────────┘ -``` - -### Split -Split-pane layout for comparisons. -``` -┌─────────────────────────────┐ -│ Header │ -├──────────────┬──────────────┤ -│ │ │ -│ Left │ Right │ -│ Pane │ Pane │ -│ │ │ -└──────────────┴──────────────┘ -``` - -## Filter Types - -Available filter components: -- `dropdown` - Single/multi-select dropdown -- `date_range` - Date range picker -- `slider` - Numeric range slider -- `checkbox` - Checkbox group -- `search` - Text search input - -## Output - -Returns a layout structure that can be: -- Used with page tools to create full app -- Rendered as a Dash layout -- Combined with chart components +- `/breakpoints {layout}` - Configure responsive breakpoints +- `/chart {type}` - Add charts to layout diff --git a/plugins/viz-platform/commands/initial-setup.md b/plugins/viz-platform/commands/initial-setup.md index ce8680b..077b01c 100644 --- a/plugins/viz-platform/commands/initial-setup.md +++ b/plugins/viz-platform/commands/initial-setup.md @@ -1,178 +1,45 @@ --- -description: Interactive setup wizard for viz-platform plugin - configures MCP server and theme preferences +description: Interactive setup wizard for viz-platform plugin --- # Viz-Platform Setup Wizard ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🎨 VIZ-PLATFORM · Setup Wizard │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| VIZ-PLATFORM - Setup Wizard | ++------------------------------------------------------------------+ ``` -Then proceed with the setup. +Sets up viz-platform with DMC validation and theming. -This command sets up the viz-platform plugin with Dash Mantine Components validation and theming. - -## Important Context - -- **This command uses Bash, Read, Write, and AskUserQuestion tools** - NOT MCP tools -- **MCP tools won't work until after setup + session restart** -- **DMC version detection is automatic** based on installed package - ---- +**Note:** Uses Bash/Read/Write tools - NOT MCP tools. Restart session after setup. ## Phase 1: Environment Validation -### Step 1.1: Check Python Version - +Check Python 3.10+ and DMC installation: ```bash python3 --version +python3 -c "import dash_mantine_components as dmc; print(dmc.__version__)" ``` -Requires Python 3.10+. If below, stop setup and inform user. - -### Step 1.2: Check DMC Installation - -```bash -python3 -c "import dash_mantine_components as dmc; print(f'DMC {dmc.__version__}')" 2>/dev/null || echo "DMC_NOT_INSTALLED" -``` - -If DMC is not installed, inform user: -``` -Dash Mantine Components is not installed. Install it with: - pip install dash-mantine-components>=0.14.0 -``` - ---- - ## Phase 2: MCP Server Setup -### Step 2.1: Locate Viz-Platform MCP Server - +Locate and create venv if missing: ```bash -# If running from installed marketplace -ls -la ~/.claude/plugins/marketplaces/leo-claude-mktplace/mcp-servers/viz-platform/ 2>/dev/null || echo "NOT_FOUND_INSTALLED" - -# If running from source -ls -la ~/claude-plugins-work/mcp-servers/viz-platform/ 2>/dev/null || echo "NOT_FOUND_SOURCE" +cd /path/to/mcp-servers/viz-platform && python3 -m venv .venv && .venv/bin/pip install -r requirements.txt ``` -### Step 2.2: Check Virtual Environment - -```bash -ls -la /path/to/mcp-servers/viz-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/viz-platform && python3 -m venv .venv && source .venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt && deactivate -``` - ---- - ## Phase 3: Theme Preferences (Optional) -### Step 3.1: Ask About Theme Setup - -Use AskUserQuestion: -- Question: "Do you want to configure a default theme for your projects?" -- Header: "Theme" -- Options: - - "Yes, set up a custom theme" - - "No, use Mantine defaults" - -**If user chooses "No":** Skip to Phase 4. - -### Step 3.2: Choose Base Theme - -Use AskUserQuestion: -- Question: "Which base color scheme do you prefer?" -- Header: "Colors" -- Options: - - "Light mode (default)" - - "Dark mode" - - "System preference (auto)" - -### Step 3.3: Choose Primary Color - -Use AskUserQuestion: -- Question: "What primary color should be used for buttons and accents?" -- Header: "Primary" -- Options: - - "Blue (default)" - - "Indigo" - - "Violet" - - "Other (I'll specify)" - -### Step 3.4: Create System Theme Config - -```bash -mkdir -p ~/.config/claude -cat > ~/.config/claude/viz-platform.env << 'EOF' -# Viz-Platform Configuration -# Generated by viz-platform /initial-setup - -VIZ_PLATFORM_COLOR_SCHEME=<SELECTED_SCHEME> -VIZ_PLATFORM_PRIMARY_COLOR=<SELECTED_COLOR> -EOF -chmod 600 ~/.config/claude/viz-platform.env -``` - ---- +Ask user about color scheme and primary color. Save to `~/.config/claude/viz-platform.env`. ## Phase 4: Validation -### Step 4.1: Verify MCP Server +Verify MCP server loads, display summary, prompt session restart. -```bash -cd /path/to/mcp-servers/viz-platform && .venv/bin/python -c "from mcp_server.server import VizPlatformMCPServer; print('MCP Server OK')" -``` +## Related Commands -### Step 4.2: Summary - -``` -╔════════════════════════════════════════════════════════════╗ -║ VIZ-PLATFORM SETUP COMPLETE ║ -╠════════════════════════════════════════════════════════════╣ -║ MCP Server: ✓ Ready ║ -║ DMC Version: [Detected version] ║ -║ DMC Tools: ✓ Available (3 tools) ║ -║ Chart Tools: ✓ Available (2 tools) ║ -║ Layout Tools: ✓ Available (5 tools) ║ -║ Theme Tools: ✓ Available (6 tools) ║ -║ Page Tools: ✓ Available (5 tools) ║ -╚════════════════════════════════════════════════════════════╝ -``` - -### Step 4.3: Session Restart Notice - ---- - -**⚠️ Session Restart Required** - -Restart your Claude Code session for MCP tools to become available. - -**After restart, you can:** -- Run `/component {name}` to inspect component props -- Run `/chart {type}` to create a chart -- Run `/dashboard {template}` to create a dashboard layout -- Run `/theme {name}` to apply a theme -- Run `/theme-new {name}` to create a custom theme - ---- - -## Tool Summary - -| Category | Tools | -|----------|-------| -| DMC Validation | list_components, get_component_props, validate_component | -| Charts | chart_create, chart_configure_interaction | -| Layouts | layout_create, layout_add_filter, layout_set_grid, layout_get, layout_add_section | -| Themes | theme_create, theme_extend, theme_validate, theme_export_css, theme_list, theme_activate | -| Pages | page_create, page_add_navbar, page_set_auth, page_list, page_get_app_config | +- `/component {name}` - Inspect component props +- `/chart {type}` - Create a chart diff --git a/plugins/viz-platform/commands/theme-css.md b/plugins/viz-platform/commands/theme-css.md index 945e68a..c305d7d 100644 --- a/plugins/viz-platform/commands/theme-css.md +++ b/plugins/viz-platform/commands/theme-css.md @@ -4,19 +4,19 @@ description: Export a theme as CSS custom properties # Export Theme as CSS +## Skills to Load +- skills/mcp-tools-reference.md +- skills/theming-system.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🎨 VIZ-PLATFORM · Theme CSS Export │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| VIZ-PLATFORM - Theme CSS Export | ++------------------------------------------------------------------+ ``` -Then proceed with the export. - -Export a theme's design tokens as CSS custom properties for use outside Dash. +Export a theme's design tokens as CSS custom properties. ## Usage @@ -28,94 +28,13 @@ Export a theme's design tokens as CSS custom properties for use outside Dash. - `name` (required): Theme name to export -## Examples - -``` -/theme-css dark -/theme-css corporate -/theme-css my-brand -``` - ## Tool Mapping -This command uses the `theme_export_css` MCP tool: - ```python theme_export_css(theme_name="corporate") ``` -## Output Example - -```css -:root { - /* Colors */ - --mantine-color-scheme: light; - --mantine-primary-color: indigo; - --mantine-color-primary-0: #edf2ff; - --mantine-color-primary-1: #dbe4ff; - --mantine-color-primary-2: #bac8ff; - --mantine-color-primary-3: #91a7ff; - --mantine-color-primary-4: #748ffc; - --mantine-color-primary-5: #5c7cfa; - --mantine-color-primary-6: #4c6ef5; - --mantine-color-primary-7: #4263eb; - --mantine-color-primary-8: #3b5bdb; - --mantine-color-primary-9: #364fc7; - - /* Typography */ - --mantine-font-family: Inter, sans-serif; - --mantine-heading-font-family: Inter, sans-serif; - --mantine-font-size-xs: 0.75rem; - --mantine-font-size-sm: 0.875rem; - --mantine-font-size-md: 1rem; - --mantine-font-size-lg: 1.125rem; - --mantine-font-size-xl: 1.25rem; - - /* Spacing */ - --mantine-spacing-xs: 0.625rem; - --mantine-spacing-sm: 0.75rem; - --mantine-spacing-md: 1rem; - --mantine-spacing-lg: 1.25rem; - --mantine-spacing-xl: 2rem; - - /* Border Radius */ - --mantine-radius-xs: 0.125rem; - --mantine-radius-sm: 0.25rem; - --mantine-radius-md: 0.5rem; - --mantine-radius-lg: 1rem; - --mantine-radius-xl: 2rem; - - /* Shadows */ - --mantine-shadow-xs: 0 1px 3px rgba(0, 0, 0, 0.05); - --mantine-shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1); - --mantine-shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1); - --mantine-shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1); - --mantine-shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.1); -} -``` - -## Use Cases - -### External CSS Files -Include the exported CSS in non-Dash projects: -```html -<link rel="stylesheet" href="theme-tokens.css"> -``` - -### Design Handoff -Share design tokens with designers or other teams. - -### Documentation -Generate theme documentation for style guides. - -### Other Frameworks -Use Mantine-compatible tokens in React, Vue, or other projects. - -## Workflow - -1. **User invokes**: `/theme-css corporate` -2. **Tool exports**: Theme tokens as CSS -3. **User can**: Save to file or copy to clipboard +Use cases: external CSS, design handoff, documentation, other frameworks. ## Related Commands diff --git a/plugins/viz-platform/commands/theme-new.md b/plugins/viz-platform/commands/theme-new.md index 96a18c7..8cdd317 100644 --- a/plugins/viz-platform/commands/theme-new.md +++ b/plugins/viz-platform/commands/theme-new.md @@ -4,18 +4,18 @@ description: Create a new custom theme with design tokens # Create New Theme +## Skills to Load +- skills/mcp-tools-reference.md +- skills/theming-system.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🎨 VIZ-PLATFORM · New Theme │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| VIZ-PLATFORM - New Theme | ++------------------------------------------------------------------+ ``` -Then proceed with the theme creation. - Create a new custom theme with specified design tokens. ## Usage @@ -28,99 +28,11 @@ Create a new custom theme with specified design tokens. - `name` (required): Name for the new theme -## Examples - -``` -/theme-new corporate -/theme-new dark-blue -/theme-new brand-theme -``` - ## Tool Mapping -This command uses the `theme_create` MCP tool: - ```python -theme_create( - name="corporate", - primary_color="indigo", - color_scheme="light", - font_family="Inter, sans-serif", - heading_font_family=None, # Optional: separate heading font - border_radius="md", # xs, sm, md, lg, xl - spacing_scale=1.0, # Multiplier for spacing - colors=None # Optional: custom color palette -) -``` - -## Workflow - -1. **User invokes**: `/theme-new corporate` -2. **Agent asks**: Primary color preference? -3. **Agent asks**: Light or dark color scheme? -4. **Agent asks**: Font family preference? -5. **Agent creates**: Theme with `theme_create` -6. **Agent validates**: Theme with `theme_validate` -7. **Agent activates**: New theme is ready to use - -## Theme Properties - -### Colors -- `primary_color`: Main accent color (blue, indigo, violet, etc.) -- `color_scheme`: "light" or "dark" -- `colors`: Custom color palette override - -### Typography -- `font_family`: Body text font -- `heading_font_family`: Optional heading font - -### Spacing -- `border_radius`: Component corner rounding -- `spacing_scale`: Multiply default spacing values - -## Mantine Color Palette - -Available primary colors: -- blue, cyan, teal, green, lime -- yellow, orange, red, pink, grape -- violet, indigo, gray, dark - -## Custom Color Example - -```python -theme_create( - name="brand", - primary_color="custom", - colors={ - "custom": [ - "#e6f7ff", # 0 - lightest - "#bae7ff", # 1 - "#91d5ff", # 2 - "#69c0ff", # 3 - "#40a9ff", # 4 - "#1890ff", # 5 - primary - "#096dd9", # 6 - "#0050b3", # 7 - "#003a8c", # 8 - "#002766" # 9 - darkest - ] - } -) -``` - -## Extending Themes - -To create a theme based on another: - -```python -theme_extend( - base_theme="dark", - name="dark-corporate", - overrides={ - "primary_color": "indigo", - "font_family": "Roboto, sans-serif" - } -) +theme_create(name="corporate", primary_color="indigo", color_scheme="light", font_family="Inter") +theme_validate(theme_name="corporate") ``` ## Related Commands diff --git a/plugins/viz-platform/commands/theme.md b/plugins/viz-platform/commands/theme.md index 86383f5..7ebad84 100644 --- a/plugins/viz-platform/commands/theme.md +++ b/plugins/viz-platform/commands/theme.md @@ -4,18 +4,18 @@ description: Apply an existing theme to the current context # Apply Theme +## Skills to Load +- skills/mcp-tools-reference.md +- skills/theming-system.md + ## Visual Output -When executing this command, display the plugin header: - ``` -┌──────────────────────────────────────────────────────────────────┐ -│ 🎨 VIZ-PLATFORM · Apply Theme │ -└──────────────────────────────────────────────────────────────────┘ ++------------------------------------------------------------------+ +| VIZ-PLATFORM - Apply Theme | ++------------------------------------------------------------------+ ``` -Then proceed with the theme activation. - Apply an existing theme to activate its design tokens. ## Usage @@ -28,52 +28,16 @@ Apply an existing theme to activate its design tokens. - `name` (required): Theme name to activate -## Examples - -``` -/theme dark -/theme corporate-blue -/theme my-custom-theme -``` - ## Tool Mapping -This command uses the `theme_activate` MCP tool: - ```python theme_activate(theme_name="dark") +theme_list() # List available themes ``` -## Workflow - -1. **User invokes**: `/theme dark` -2. **Tool activates**: Theme becomes active for subsequent operations -3. **Charts/layouts**: Automatically use active theme tokens - -## Built-in Themes - -| Theme | Description | -|-------|-------------| -| `light` | Mantine default light mode | -| `dark` | Mantine default dark mode | - -## Listing Available Themes - -To see all available themes: - -```python -theme_list() -``` - -Returns both built-in and custom themes. - ## Theme Effects -When a theme is activated: -- New charts inherit theme colors -- New layouts use theme spacing -- Components use theme typography -- Callbacks can read active theme tokens +When activated, new charts/layouts automatically use theme tokens. ## Related Commands diff --git a/plugins/viz-platform/skills/accessibility-rules.md b/plugins/viz-platform/skills/accessibility-rules.md new file mode 100644 index 0000000..9b97a1f --- /dev/null +++ b/plugins/viz-platform/skills/accessibility-rules.md @@ -0,0 +1,64 @@ +# Accessibility Rules + +## WCAG Contrast Standards + +| Level | Ratio | Use Case | +|-------|-------|----------| +| AA (normal text) | 4.5:1 | Body text, labels | +| AA (large text) | 3:1 | Headings, 14pt+ bold | +| AAA (enhanced) | 7:1 | Highest accessibility | + +## Color Blindness Types + +| Type | Affected Colors | Population | +|------|-----------------|------------| +| **Deuteranopia** | Red-Green (green-blind) | ~6% males, 0.4% females | +| **Protanopia** | Red-Green (red-blind) | ~2.5% males, 0.05% females | +| **Tritanopia** | Blue-Yellow | ~0.01% total | + +## Color-Blind Safe Palettes + +### IBM Design Colors +``` +#648FFF #785EF0 #DC267F #FE6100 #FFB000 +``` + +### Tableau Colorblind 10 +``` +#006BA4 #FF800E #ABABAB #595959 #5F9ED1 +#C85200 #898989 #A2C8EC #FFBC79 #CFCFCF +``` + +### Okabe-Ito +``` +#E69F00 #56B4E9 #009E73 #F0E442 #0072B2 +#D55E00 #CC79A7 #000000 +``` + +### Safe Palette Categories + +```json +{ + "categorical": ["#4477AA", "#EE6677", "#228833", "#CCBB44", "#66CCEE", "#AA3377", "#BBBBBB"], + "sequential": ["#FEE0D2", "#FC9272", "#DE2D26"], + "diverging": ["#4575B4", "#FFFFBF", "#D73027"] +} +``` + +## Best Practices + +1. **Don't rely on color alone** - Use shapes, patterns, or labels +2. **Test with simulation** - View through color blindness simulators +3. **Use sufficient contrast** - Minimum 4.5:1 for text, 3:1 for large elements +4. **Limit color count** - Fewer colors = easier to distinguish +5. **Use semantic colors** - Blue for information, red for errors (with icons) + +## Accessibility Scoring + +| Grade | Description | +|-------|-------------| +| A | Excellent - All WCAG AAA standards met | +| B | Good - WCAG AA standards met with minor warnings | +| C | Acceptable - WCAG AA met but improvements recommended | +| D | Poor - Some WCAG AA failures | +| F | Failing - Major accessibility issues | diff --git a/plugins/viz-platform/skills/chart-types.md b/plugins/viz-platform/skills/chart-types.md new file mode 100644 index 0000000..de1c7b1 --- /dev/null +++ b/plugins/viz-platform/skills/chart-types.md @@ -0,0 +1,59 @@ +# Chart Types Reference + +## Available Chart Types + +| Type | Best For | +|------|----------| +| `line` | Time series, trends | +| `bar` | Comparisons, categories | +| `scatter` | Correlations, distributions | +| `pie` | Part-to-whole relationships | +| `area` | Cumulative trends | +| `histogram` | Frequency distributions | +| `box` | Statistical distributions | +| `heatmap` | Matrix correlations | +| `sunburst` | Hierarchical data | +| `treemap` | Hierarchical proportions | + +## Theme Integration + +Charts automatically inherit from active theme: +- Primary color for main data +- Color palette for multi-series +- Font family and sizes +- Background colors + +Override with explicit theme: +```python +chart_create(chart_type="bar", ..., theme="my-dark-theme") +``` + +## Export Formats + +| Format | Best For | File Size | +|--------|----------|-----------| +| `png` | Web, presentations, general use | Medium | +| `svg` | Scalable graphics, editing | Small | +| `pdf` | Print, documents, archival | Large | + +## Resolution Options + +### Scale Factor +- `1` - Standard resolution (72 DPI) +- `2` - Retina/HiDPI (144 DPI) +- `3` - Print quality (216 DPI) +- `4` - High-quality print (288 DPI) + +## Export Requirements + +Requires `kaleido` package: +```bash +pip install kaleido +``` + +## Output + +Charts return Plotly figure JSON that can be: +- Rendered in a Dash app +- Saved as HTML/PNG/SVG/PDF +- Embedded in a layout component diff --git a/plugins/viz-platform/skills/dmc-components.md b/plugins/viz-platform/skills/dmc-components.md new file mode 100644 index 0000000..7db04a2 --- /dev/null +++ b/plugins/viz-platform/skills/dmc-components.md @@ -0,0 +1,97 @@ +# Dash Mantine Components Reference + +## Component Categories + +| Category | Components | +|----------|------------| +| `inputs` | Button, TextInput, Select, Checkbox, Radio, Switch, Slider, etc. | +| `navigation` | NavLink, Tabs, Breadcrumbs, Pagination, Stepper | +| `feedback` | Alert, Notification, Progress, Loader, Skeleton | +| `overlays` | Modal, Drawer, Tooltip, Popover, Menu | +| `typography` | Text, Title, Code, Blockquote, List | +| `layout` | Container, Grid, Stack, Group, Space, Divider | +| `data` | Table, Badge, Card, Paper, Timeline | + +## Common Props + +Most components share these props: + +| Prop | Type | Description | +|------|------|-------------| +| `size` | xs, sm, md, lg, xl | Component size | +| `radius` | xs, sm, md, lg, xl | Border radius | +| `color` | string | Theme color name | +| `variant` | string | Style variant | +| `disabled` | boolean | Disable interaction | + +## Component Validation + +Why validation matters: +- Prevents hallucinated prop names +- Validates enum values +- Catches typos before runtime +- Documents available options + +### Validation Response + +```json +{ + "valid": true, + "errors": [], + "warnings": [] +} +``` + +With errors: +```json +{ + "valid": false, + "errors": [ + "Invalid prop 'colour' for Button. Did you mean 'color'?", + "Prop 'size' expects one of ['xs', 'sm', 'md', 'lg', 'xl'], got 'huge'" + ], + "warnings": [ + "Prop 'fullwidth' should be 'fullWidth' (camelCase)" + ] +} +``` + +## Grid System + +DMC Grid with responsive spans: + +```python +dmc.Grid( + children=[ + dmc.GridCol( + children=[chart], + span={"base": 12, "sm": 6, "lg": 4} + ) + ], + gutter="md" +) +``` + +## Button Example + +```json +{ + "component": "Button", + "props": { + "variant": { + "type": "string", + "enum": ["filled", "outline", "light", "subtle", "default", "gradient"], + "default": "filled" + }, + "color": { + "type": "string", + "default": "blue" + }, + "size": { + "type": "string", + "enum": ["xs", "sm", "md", "lg", "xl"], + "default": "sm" + } + } +} +``` diff --git a/plugins/viz-platform/skills/layout-templates.md b/plugins/viz-platform/skills/layout-templates.md new file mode 100644 index 0000000..c27a9e5 --- /dev/null +++ b/plugins/viz-platform/skills/layout-templates.md @@ -0,0 +1,70 @@ +# Layout Templates + +## Available Templates + +### Basic +Single-column layout with header and content area. +``` ++-----------------------------+ +| Header | ++-----------------------------+ +| | +| Content | +| | ++-----------------------------+ +``` + +### Sidebar +Layout with collapsible sidebar navigation. +``` ++--------+--------------------+ +| | Header | +| Nav +--------------------+ +| | | +| | Content | +| | | ++--------+--------------------+ +``` + +### Tabs +Tabbed layout for multi-page dashboards. +``` ++-----------------------------+ +| Header | ++------+------+------+--------+ +| Tab1 | Tab2 | Tab3 | | ++------+------+------+--------+ +| | +| Tab Content | +| | ++-----------------------------+ +``` + +### Split +Split-pane layout for comparisons. +``` ++-----------------------------+ +| Header | ++--------------+--------------+ +| | | +| Left | Right | +| Pane | Pane | +| | | ++--------------+--------------+ +``` + +## Filter Types + +Available filter components: +- `dropdown` - Single/multi-select dropdown +- `date_range` - Date range picker +- `slider` - Numeric range slider +- `checkbox` - Checkbox group +- `search` - Text search input + +## Output + +Layout structures can be: +- Used with page tools to create full app +- Rendered as a Dash layout +- Combined with chart components diff --git a/plugins/viz-platform/skills/mcp-tools-reference.md b/plugins/viz-platform/skills/mcp-tools-reference.md new file mode 100644 index 0000000..868315e --- /dev/null +++ b/plugins/viz-platform/skills/mcp-tools-reference.md @@ -0,0 +1,159 @@ +# Viz-Platform MCP Tools Reference + +## Tool Categories + +| Category | Tools | +|----------|-------| +| DMC Validation | `list_components`, `get_component_props`, `validate_component` | +| Charts | `chart_create`, `chart_configure_interaction`, `chart_export` | +| Layouts | `layout_create`, `layout_add_filter`, `layout_set_grid`, `layout_set_breakpoints` | +| Themes | `theme_create`, `theme_extend`, `theme_validate`, `theme_export_css`, `theme_list`, `theme_activate` | +| Pages | `page_create`, `page_add_navbar`, `page_set_auth` | +| Accessibility | `accessibility_validate_colors`, `accessibility_validate_theme`, `accessibility_suggest_alternative` | + +## DMC Validation Tools + +### list_components +```python +list_components(category=None) # All components +list_components(category="inputs") # Filter by category +``` + +### get_component_props +```python +get_component_props(component="Button") +``` + +### validate_component +```python +validate_component( + component="Button", + props={"variant": "filled", "color": "blue"} +) +``` + +## Chart Tools + +### chart_create +```python +chart_create( + chart_type="line", + data_ref="df_sales", + x="date", + y="revenue", + color=None, + title="Sales Over Time", + theme=None +) +``` + +### chart_export +```python +chart_export( + figure=figure_json, + format="png", # png, svg, pdf + width=1200, + height=800, + scale=2, + output_path=None +) +``` + +## Layout Tools + +### layout_create +```python +layout_create( + name="my-dashboard", + template="sidebar" # basic, sidebar, tabs, split +) +``` + +### layout_add_filter +```python +layout_add_filter( + layout_ref="my-dashboard", + filter_type="dropdown", # dropdown, date_range, slider, checkbox, search + options={} +) +``` + +### layout_set_grid +```python +layout_set_grid( + layout_ref="my-dashboard", + cols=12, + spacing="md" +) +``` + +### layout_set_breakpoints +```python +layout_set_breakpoints( + layout_ref="my-dashboard", + breakpoints={ + "xs": {"cols": 1, "spacing": "xs"}, + "sm": {"cols": 2, "spacing": "sm"}, + "md": {"cols": 6, "spacing": "md"}, + "lg": {"cols": 12, "spacing": "md"}, + "xl": {"cols": 12, "spacing": "lg"} + }, + mobile_first=True +) +``` + +## Theme Tools + +### theme_create +```python +theme_create( + name="corporate", + primary_color="indigo", + color_scheme="light", + font_family="Inter, sans-serif", + heading_font_family=None, + border_radius="md", + spacing_scale=1.0, + colors=None +) +``` + +### theme_extend +```python +theme_extend( + base_theme="dark", + name="dark-corporate", + overrides={"primary_color": "indigo"} +) +``` + +### theme_validate +```python +theme_validate(theme_name="corporate") +``` + +### theme_export_css +```python +theme_export_css(theme_name="corporate") +``` + +### theme_activate +```python +theme_activate(theme_name="dark") +``` + +## Accessibility Tools + +### accessibility_validate_colors +```python +accessibility_validate_colors( + colors=["#228be6", "#40c057", "#fa5252"], + check_types=["deuteranopia", "protanopia", "tritanopia"], + min_contrast_ratio=4.5 +) +``` + +### accessibility_validate_theme +```python +accessibility_validate_theme(theme_name="corporate") +``` diff --git a/plugins/viz-platform/skills/responsive-design.md b/plugins/viz-platform/skills/responsive-design.md new file mode 100644 index 0000000..5f60f6c --- /dev/null +++ b/plugins/viz-platform/skills/responsive-design.md @@ -0,0 +1,104 @@ +# Responsive Design + +## Breakpoint Sizes + +| Name | Min Width | Common Devices | +|------|-----------|----------------| +| `xs` | 0px | Small phones (portrait) | +| `sm` | 576px | Large phones, small tablets | +| `md` | 768px | Tablets (portrait) | +| `lg` | 992px | Tablets (landscape), laptops | +| `xl` | 1200px | Desktops, large screens | + +## Mobile-First Approach + +When `mobile_first=True` (default), styles cascade up: +- Define base styles for `xs` (mobile) +- Override only what changes at larger breakpoints +- Smaller CSS footprint, better performance + +```python +{ + "xs": {"cols": 1}, # Stack everything on mobile + "md": {"cols": 6}, # Two-column on tablet + "lg": {"cols": 12} # Full grid on desktop +} +``` + +When `mobile_first=False`, styles cascade down (desktop-first). + +## Grid Configuration + +Each breakpoint can configure: + +| Property | Description | Values | +|----------|-------------|--------| +| `cols` | Grid column count | 1-24 | +| `spacing` | Gap between items | xs, sm, md, lg, xl | +| `gutter` | Outer padding | xs, sm, md, lg, xl | +| `grow` | Items grow to fill | true, false | + +## Common Patterns + +### Dashboard (Charts & Filters) +```python +{ + "xs": {"cols": 1, "spacing": "xs"}, + "sm": {"cols": 2, "spacing": "sm"}, + "md": {"cols": 3, "spacing": "md"}, + "lg": {"cols": 4, "spacing": "md"}, + "xl": {"cols": 6, "spacing": "lg"} +} +``` + +### Data Table +```python +{ + "xs": {"cols": 1, "scroll": true}, + "md": {"cols": 1, "scroll": false}, + "lg": {"cols": 1} +} +``` + +### Form Layout +```python +{ + "xs": {"cols": 1}, + "md": {"cols": 2}, + "lg": {"cols": 3} +} +``` + +### Sidebar Layout +```python +{ + "xs": {"sidebar": "hidden"}, + "md": {"sidebar": "collapsed"}, + "lg": {"sidebar": "expanded"} +} +``` + +## Component Span + +Control how many columns a component spans: + +```python +{ + "component": "sales-chart", + "span": { + "xs": 1, # Full width (1/1) + "md": 3, # Half width (3/6) + "lg": 6 # Half width (6/12) + } +} +``` + +## CSS Media Queries + +Generated for each breakpoint: +```css +@media (min-width: 576px) { ... } +@media (min-width: 768px) { ... } +@media (min-width: 992px) { ... } +@media (min-width: 1200px) { ... } +``` diff --git a/plugins/viz-platform/skills/theming-system.md b/plugins/viz-platform/skills/theming-system.md new file mode 100644 index 0000000..4d3affd --- /dev/null +++ b/plugins/viz-platform/skills/theming-system.md @@ -0,0 +1,104 @@ +# Theming System + +## Design Tokens + +Themes define design tokens for consistent styling across components. + +### Theme Properties + +| Category | Properties | +|----------|------------| +| Colors | `primary_color`, `color_scheme`, `colors` | +| Typography | `font_family`, `heading_font_family` | +| Spacing | `border_radius`, `spacing_scale` | + +### Color Scheme +- `light` - Light background, dark text +- `dark` - Dark background, light text + +### Border Radius Scale +| Size | Value | +|------|-------| +| xs | 0.125rem | +| sm | 0.25rem | +| md | 0.5rem | +| lg | 1rem | +| xl | 2rem | + +## Mantine Color Palette + +Available primary colors: +- blue, cyan, teal, green, lime +- yellow, orange, red, pink, grape +- violet, indigo, gray, dark + +Each color has 10 shades (0-9), where 5 is the primary shade. + +## Custom Color Definition + +```python +colors={ + "custom": [ + "#e6f7ff", # 0 - lightest + "#bae7ff", # 1 + "#91d5ff", # 2 + "#69c0ff", # 3 + "#40a9ff", # 4 + "#1890ff", # 5 - primary + "#096dd9", # 6 + "#0050b3", # 7 + "#003a8c", # 8 + "#002766" # 9 - darkest + ] +} +``` + +## CSS Custom Properties + +Exported themes use Mantine CSS variable naming: + +```css +:root { + /* Colors */ + --mantine-color-scheme: light; + --mantine-primary-color: indigo; + --mantine-color-primary-0: #edf2ff; + --mantine-color-primary-5: #5c7cfa; + --mantine-color-primary-9: #364fc7; + + /* Typography */ + --mantine-font-family: Inter, sans-serif; + --mantine-font-size-xs: 0.75rem; + --mantine-font-size-md: 1rem; + + /* Spacing */ + --mantine-spacing-xs: 0.625rem; + --mantine-spacing-md: 1rem; + + /* Border Radius */ + --mantine-radius-sm: 0.25rem; + --mantine-radius-md: 0.5rem; + + /* Shadows */ + --mantine-shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1); + --mantine-shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1); +} +``` + +## Theme Inheritance + +Create themes based on existing ones: +```python +theme_extend( + base_theme="dark", + name="dark-corporate", + overrides={"primary_color": "indigo"} +) +``` + +## Built-in Themes + +| Theme | Description | +|-------|-------------| +| `light` | Mantine default light mode | +| `dark` | Mantine default dark mode |