Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat: Add 5 commands and dependency-audit skill (capability gap analysis)
Jezf666e1e5c570
diff --git a/skills/deep-debug/SKILL.md b/skills/deep-debug/SKILL.mdindex 1d0f2382..2c0e0a73 100644--- a/skills/deep-debug/SKILL.md+++ b/skills/deep-debug/SKILL.md@@ -8,7 +8,7 @@ user-invocable: true# Deep Debug - Multi-Agent Investigation**Status**: Production Ready-**Last Updated**: 2026-02-02+**Last Updated**: 2026-02-03**Dependencies**: Chrome MCP tools (optional), debugger agent, code-reviewer agent---@@ -20,10 +20,16 @@ user-invocable: true- **Symptoms don't match expectations** - Something deeper is wrong- **Complex state management bugs** - React hooks, closures, race conditions+## Commands++| Command | Purpose |+|---------|---------|+| `/debug` | Guided debugging workflow with evidence gathering and parallel investigation |+## Quick Start```-/deep-debug [description of the bug]+/debug [description of the bug]```Or invoke naturally:diff --git a/skills/deep-debug/commands/debug.md b/skills/deep-debug/commands/debug.mdnew file mode 100644index 00000000..ca27afc3--- /dev/null+++ b/skills/deep-debug/commands/debug.md@@ -0,0 +1,416 @@+# Debug++Systematic debugging workflow for errors, bugs, and unexpected behavior.++---++## Command Usage++`/debug [error-or-symptom]`++- With error: `/debug TypeError: Cannot read property 'map' of undefined`+- With symptom: `/debug API calls are duplicating`+- Interactive: `/debug` (guides you through describing the issue)++---++## Your Task++Guide the user through systematic debugging: gather evidence, form hypotheses, investigate with parallel agents, and verify fixes.++### Step 1: Understand the Problem++If error/symptom not provided as argument, ask:++```+═══════════════════════════════════════════════+ DEBUG SESSION+═══════════════════════════════════════════════++What are you experiencing?++1. Error message - TypeError, ReferenceError, etc.+2. Unexpected behavior - "It does X instead of Y"+3. Performance issue - Slow, hanging, timeouts+4. Intermittent bug - Works sometimes, fails sometimes+5. Production issue - Needs safe investigation++Your choice [1-5]:+```++Then gather details:++```+Describe what's happening:+> [User describes the issue]++When did this start?+> [User: "After my last commit" / "Always" / "Randomly"]++Can you reproduce it?+> [User: "Yes, every time" / "Sometimes" / "No"]+```++### Step 2: Gather Evidence (BEFORE Hypothesizing)++**Critical**: Evidence first, hypotheses second. Don't guess until you have data.++**For browser-related bugs**, use Chrome MCP tools:++```+Gathering evidence from browser...++Network requests:+ mcp__claude-in-chrome__read_network_requests++Console messages:+ mcp__claude-in-chrome__read_console_messages++Page state:+ mcp__claude-in-chrome__read_page+```++Report what you find:++```+═══════════════════════════════════════════════+ EVIDENCE GATHERED+═══════════════════════════════════════════════++Network Tab:+ - 2 duplicate POST requests to /api/messages (suspicious!)+ - Both have same payload, 200ms apart+ - No failed requests++Console:+ - Warning: "Maximum update depth exceeded" (React)+ - No errors++Page State:+ - Component mounted correctly+ - State appears correct++Key finding: Duplicate API calls suggest re-render issue+═══════════════════════════════════════════════+```++**For backend bugs**, examine:++```bash+# Recent error logs+tail -50 logs/error.log++# Check git diff for recent changes+git log --oneline -10+git diff HEAD~1++# Database query logs (if applicable)+# Check for slow queries, deadlocks+```++**For runtime errors**, capture:++- Stack trace (full, not truncated)+- Input values that triggered the error+- Environment (Node version, OS, etc.)+- Recent code changes++### Step 3: Form Hypotheses++Based on evidence, list possible causes:++```+═══════════════════════════════════════════════+ HYPOTHESES (Ranked by Evidence)+═══════════════════════════════════════════════++1. useCallback dependency array includes `state`+ Evidence: Duplicate calls, React update warning+ Confidence: HIGH++2. Component re-mounting on parent state change+ Evidence: Duplicate calls+ Confidence: MEDIUM++3. Event handler attached twice+ Evidence: Duplicate calls (but less likely given pattern)+ Confidence: LOW++Proceeding with parallel investigation...+═══════════════════════════════════════════════+```++### Step 4: Parallel Agent Investigation++Launch 3 agents simultaneously to investigate from different angles:++**Agent 1: Execution Tracer (debugger)**++```+Task(+ subagent_type: "debugger",+ prompt: """+EVIDENCE: [paste gathered evidence]++Trace the execution path that leads to this bug. Find:+1. Where the bug originates+2. What triggers it+3. The exact line/function causing the issue++Focus on TRACING, not guessing. Report the execution flow.+"""+)+```++**Agent 2: Code Pattern Analyzer (code-reviewer)**++```+Task(+ subagent_type: "code-reviewer",+ prompt: """+EVIDENCE: [paste gathered evidence]++Review the relevant code for common bug patterns:+- React useCallback/useMemo dependency issues+- Stale closures+- Race conditions+- State update ordering+- Missing error handling++Find patterns that EXPLAIN the evidence.+"""+)+```++**Agent 3: Entry Point Mapper (Explore)**++```+Task(+ subagent_type: "Explore",+ prompt: """+EVIDENCE: [paste gathered evidence]++Map all entry points that could trigger this behavior:+- All places [function] is called+- All event handlers involved+- All state updates that affect this++Find if something is being called MULTIPLE TIMES or from UNEXPECTED places.+"""+)+```++Tell the user:++```+═══════════════════════════════════════════════+ INVESTIGATING+═══════════════════════════════════════════════++Launched 3 parallel investigation agents:++[1] Execution Tracer - Tracing code path to bug+[2] Pattern Analyzer - Checking for known bug patterns+[3] Entry Point Mapper - Finding all trigger points++This typically takes 30-60 seconds...+═══════════════════════════════════════════════+```++### Step 5: Cross-Reference Findings++When agents return, synthesize:++| Signal | Action |+|--------|--------|+| All 3 agree | High confidence - proceed to fix |+| 2 agree, 1 different | Investigate the difference |+| All 3 different | Need more evidence - gather more |++```+═══════════════════════════════════════════════+ INVESTIGATION RESULTS+═══════════════════════════════════════════════++Agent 1 (Execution Tracer):+ Root cause: `state.messages` in useCallback deps+ Location: src/components/Chat.tsx:45++Agent 2 (Pattern Analyzer):+ Root cause: useCallback dependency causing recreation+ Pattern: React re-render loop (documented pattern)++Agent 3 (Entry Point Mapper):+ Found: sendMessage called from 2 places+ But both are legitimate (button + enter key)+ Ruled out: Double-mounting, duplicate handlers++═══════════════════════════════════════════════+ CONSENSUS: useCallback dependency issue+═══════════════════════════════════════════════++Confidence: HIGH (3/3 agents agree)++Root Cause:+ `sendMessage` useCallback has `state.messages` in deps.+ Every state update recreates the callback.+ During React re-render, duplicate calls occur.++Location: src/components/Chat.tsx:45++Fix:+ Use ref to access current state without dependency:++ const stateRef = useRef(state);+ stateRef.current = state;++ const sendMessage = useCallback(async (text) => {+ const messages = stateRef.current.messages;+ // ...+ }, []); // Remove state.messages from deps++Would you like me to apply this fix? [Y/n]+═══════════════════════════════════════════════+```++### Step 6: Apply and Verify Fix++If user approves:++1. **Apply the fix**+2. **Re-gather the same evidence** to confirm:+ - Network tab: No more duplicates+ - Console: Warning gone+ - User action: Works correctly++```+═══════════════════════════════════════════════+ FIX APPLIED+═══════════════════════════════════════════════++Changes made:+ - src/components/Chat.tsx (lines 43-55)++Verification:+ ✅ Network: Single API call (was: 2 duplicate)+ ✅ Console: No React warnings+ ✅ Behavior: Message sent once++The bug is fixed!++Would you like to:+1. Commit this fix+2. Add a regression test+3. Document the root cause+4. Done++Your choice [1-4]:+═══════════════════════════════════════════════+```++---++## Evidence Gathering Quick Reference++| Bug Type | Primary Evidence Source | Tools |+|----------|------------------------|-------|+| Browser/UI | Network tab, Console | `read_network_requests`, `read_console_messages` |+| API/Backend | Error logs, Request payloads | `Bash`, `Read` |+| Database | Query logs, Deadlocks | `Bash`, `Read` |+| Performance | Profiler, Timing | `read_network_requests`, Bash profilers |+| State/React | Console warnings, Re-renders | `read_console_messages`, DevTools |++---++## Common Bug Patterns++### React Hook Issues+- `state` in useCallback dependencies → callback recreation → duplicate calls+- Missing dependencies → stale closures → wrong values+- useEffect running multiple times → check deps array++### API/Network Issues+- Duplicate requests → check re-renders, event handlers+- Race conditions → check async handling, AbortController+- CORS failures → check server headers, credentials mode++### State Management Issues+- State not updating → check immutability, spread operators+- Stale state in callbacks → use refs or functional updates+- Multiple sources of truth → consolidate state++---++## Error Handling++**If no evidence can be gathered:**+```+⚠️ Unable to gather evidence automatically.++Please provide:+1. Full error message and stack trace+2. Steps to reproduce+3. Code snippet where error occurs++Paste the error here:+>+```++**If agents return conflicting results:**+```+⚠️ Agents returned different conclusions.++Agent 1: [result]+Agent 2: [result]+Agent 3: [result]++This suggests:+- The bug may have multiple contributing factors+- Need more evidence to narrow down++Options:+1. Gather more evidence (specify what)+2. Investigate each hypothesis separately+3. Add logging to isolate the issue++Your choice [1-3]:+```++**If fix doesn't resolve the issue:**+```+⚠️ Verification failed - issue persists.++Evidence after fix:+ - [still seeing problem]++This suggests:+- Root cause was misidentified+- There may be multiple bugs+- Fix was incomplete++Re-running investigation with new evidence...+```++---++## Important Notes++- **Evidence first**: Never guess before gathering data+- **Parallel investigation**: 3 perspectives faster than 1 sequential+- **Verify fixes**: Always confirm with same evidence that found the bug+- **Document learnings**: Good bugs become regression tests+- **Chrome tools**: Most powerful for frontend bugs (Network, Console, DOM)++---++## Related Resources++- `templates/parallel-agent-prompts.md` - Agent prompt templates+- `templates/investigation-report.md` - Report format+- `rules/evidence-first.md` - Why evidence matters+- `rules/chrome-evidence-tools.md` - Browser evidence gathering++---++**Version**: 1.0.0+**Last Updated**: 2026-02-03diff --git a/skills/dependency-audit/.claude-plugin/plugin.json b/skills/dependency-audit/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..0264795a--- /dev/null+++ b/skills/dependency-audit/.claude-plugin/plugin.json@@ -0,0 +1,13 @@+{+ "name": "dependency-audit",+ "description": "Comprehensive dependency health auditing for JavaScript/TypeScript projects. Run npm audit, detect outdated packages, check for security advisories, and verify license compliance. Prioritises vulnerabilities by severity and provides actionable fix recommendations. Use when: auditing project dependencies, checking for vulnerabilities, updating packages, preparing for release, or investigating npm audit warnings.",+ "version": "1.0.0",+ "author": {+ "name": "Jeremy Dawes",+ "email": "[email protected]"+ },+ "license": "MIT",+ "repository": "https://github.com/jezweb/claude-skills",+ "keywords": ["audit","vulnerabilities","outdated","security","npm audit","pnpm audit","CVE","GHSA","license."],+ "agents": ["dep-auditor"]+}diff --git a/skills/dependency-audit/README.md b/skills/dependency-audit/README.mdnew file mode 100644index 00000000..c837b79c--- /dev/null+++ b/skills/dependency-audit/README.md@@ -0,0 +1,25 @@+# Dependency Audit++Comprehensive dependency health auditing for JavaScript/TypeScript projects.++## Keywords++dependency audit, npm audit, pnpm audit, yarn audit, security vulnerabilities, CVE, GHSA, outdated packages, license compliance, dependency health, vulnerable dependencies, security advisory, package updates, npm outdated, supply chain security++## When to Use++- Running security audits before release+- Checking for vulnerabilities after `npm install`+- Updating dependencies safely+- Investigating npm audit warnings+- Checking license compliance for commercial projects+- Maintaining dependency hygiene++## Features++- Security vulnerability scanning (npm audit)+- Outdated package detection+- License compliance checking+- Prioritised fix recommendations+- Auto-fix for safe updates+- CI integration guidancediff --git a/skills/dependency-audit/SKILL.md b/skills/dependency-audit/SKILL.mdnew file mode 100644index 00000000..c61da784--- /dev/null+++ b/skills/dependency-audit/SKILL.md@@ -0,0 +1,222 @@+---+name: dependency-audit+description: |+ Comprehensive dependency health auditing for JavaScript/TypeScript projects. Run npm audit, detect outdated packages, check for security advisories, and verify license compliance. Prioritises vulnerabilities by severity and provides actionable fix recommendations.++ Use when: auditing project dependencies, checking for vulnerabilities, updating packages, preparing for release, or investigating "npm audit" warnings. Keywords: audit, vulnerabilities, outdated, security, npm audit, pnpm audit, CVE, GHSA, license.+license: MIT+---++# Dependency Audit++**Status**: Production Ready+**Last Updated**: 2026-02-03+**Scope**: npm, pnpm, yarn projects++---++## Commands++| Command | Purpose |+|---------|---------|+| `/audit-deps` | Run comprehensive dependency audit with prioritised findings |++## Quick Start++```+/audit-deps # Full audit+/audit-deps --security-only # Only security vulnerabilities+/audit-deps --outdated # Only outdated packages+/audit-deps --fix # Auto-fix compatible updates+```++---++## What This Skill Audits++### 1. Security Vulnerabilities++```+npm audit / pnpm audit+```++- **Critical** (CVSS 9.0-10.0): Remote code execution, auth bypass+- **High** (CVSS 7.0-8.9): Data exposure, privilege escalation+- **Moderate** (CVSS 4.0-6.9): DoS, info disclosure+- **Low** (CVSS 0.1-3.9): Minor issues++### 2. Outdated Packages++```+npm outdated / pnpm outdated+```++Categories:+- **Major updates**: Breaking changes likely (review changelog)+- **Minor updates**: New features, backwards compatible+- **Patch updates**: Bug fixes, safe to update++### 3. License Compliance++Checks for:+- GPL licenses in commercial projects (copyleft risk)+- Unknown/missing licenses+- License conflicts++### 4. Dependency Health++- Deprecated packages+- Abandoned packages (no updates in 2+ years)+- Packages with open security issues++---++## Output Format++```+═══════════════════════════════════════════════+ DEPENDENCY AUDIT REPORT+═══════════════════════════════════════════════++Project: my-app+Package Manager: pnpm+Total Dependencies: 847 (142 direct, 705 transitive)++───────────────────────────────────────────────+ SECURITY+───────────────────────────────────────────────++🔴 CRITICAL (1)+ └─ CVE-2021-23337: Command injection via template()+ └─ Fix: npm update [email protected]+ └─ Affects: direct dependency++🟠 HIGH (2)+ └─ CVE-2021-44906: Prototype pollution+ └─ Fix: Transitive via mkdirp, update parent+ └─ Path: mkdirp → minimist++ └─ CVE-2022-0235: Exposure of sensitive headers+ └─ Fix: npm update [email protected]++🟡 MODERATE (3)+ [details...]++───────────────────────────────────────────────+ OUTDATED PACKAGES+───────────────────────────────────────────────++Major Updates (review breaking changes):+ react 18.2.0 → 19.1.0 (1 major)+ typescript 5.3.0 → 5.8.0 (5 minor)+ drizzle-orm 0.44.0 → 0.50.0 (6 minor)++Minor Updates (safe, new features):+ @types/node 20.11.0 → 20.14.0+ vitest 1.2.0 → 1.6.0++Patch Updates (recommended):+ [15 packages with patch updates]++───────────────────────────────────────────────+ LICENSE CHECK+───────────────────────────────────────────────++✅ All licenses compatible with MIT++Note: 3 packages use ISC (compatible)++───────────────────────────────────────────────+ SUMMARY+───────────────────────────────────────────────++Security Issues: 6 (1 critical, 2 high, 3 moderate)+Outdated: 23 (3 major, 5 minor, 15 patch)+License Issues: 0++Recommended Actions:+1. Fix critical: npm update lodash+2. Fix high: npm audit fix+3. Review major updates before upgrading++═══════════════════════════════════════════════+```++---++## Agent++The `dep-auditor` agent can:++- Parse npm/pnpm audit JSON output+- Cross-reference CVE databases+- Generate detailed fix recommendations+- Auto-fix safe updates (with confirmation)++---++## CI Integration++### GitHub Actions++```yaml+- name: Audit dependencies+ run: npm audit --audit-level=high+ continue-on-error: true++- name: Check for critical vulnerabilities+ run: |+ CRITICAL=$(npm audit --json | jq '.metadata.vulnerabilities.critical')+ if [ "$CRITICAL" -gt 0 ]; then+ echo "Critical vulnerabilities found!"+ exit 1+ fi+```++### Pre-commit Hook++```bash+#!/bin/sh+npm audit --audit-level=critical || {+ echo "Critical vulnerabilities found. Run 'npm audit fix' or '/audit-deps'"+ exit 1+}+```++---++## Package Manager Commands++| Task | npm | pnpm | yarn |+|------|-----|------|------|+| Audit | `npm audit` | `pnpm audit` | `yarn audit` |+| Audit JSON | `npm audit --json` | `pnpm audit --json` | `yarn audit --json` |+| Fix auto | `npm audit fix` | `pnpm audit --fix` | `yarn audit --fix` |+| Fix force | `npm audit fix --force` | N/A | N/A |+| Outdated | `npm outdated` | `pnpm outdated` | `yarn outdated` |+| Why | `npm explain <pkg>` | `pnpm why <pkg>` | `yarn why <pkg>` |++---++## Known Limitations++- **npm audit fix --force**: May introduce breaking changes (major version bumps)+- **Transitive dependencies**: Some vulnerabilities require updating parent packages+- **False positives**: Some advisories may not apply to your usage+- **Private registries**: May need auth configuration for auditing++---++## Related Skills++- **cloudflare-worker-base**: For Workers projects+- **testing-patterns**: Run tests after updates+- **developer-toolbox**: For commit-helper after fixes++---++**Version**: 1.0.0+**Last Updated**: 2026-02-03diff --git a/skills/dependency-audit/agents/dep-auditor.md b/skills/dependency-audit/agents/dep-auditor.mdnew file mode 100644index 00000000..b904418a--- /dev/null+++ b/skills/dependency-audit/agents/dep-auditor.md@@ -0,0 +1,133 @@+---+name: dep-auditor+description: |+ Dependency auditing specialist. MUST BE USED when: auditing npm/pnpm dependencies, checking for vulnerabilities, investigating security advisories, or updating packages safely. Use PROACTIVELY when user mentions npm audit, outdated packages, or CVE.++ Keywords: audit, vulnerabilities, CVE, GHSA, outdated, security, npm audit, pnpm audit, dependency update+tools: Read, Bash, Grep, Glob+model: sonnet+---++# Dependency Auditor Agent++You are a dependency security and health specialist. Your job is to audit project dependencies, identify vulnerabilities, and provide actionable fix recommendations.++## When Invoked++Execute this audit workflow:++### 1. Detect Package Manager++```bash+# Check lock files+ls package-lock.json pnpm-lock.yaml yarn.lock bun.lockb 2>/dev/null+```++### 2. Run Security Audit++```bash+# For npm+npm audit --json 2>&1 | head -1000++# For pnpm+pnpm audit --json 2>&1 | head -1000+```++### 3. Parse Vulnerabilities++Extract from JSON:+- Severity (critical, high, moderate, low)+- Package name and version+- Advisory ID (CVE or GHSA)+- Fix version or action++### 4. Check Outdated++```bash+npm outdated --json 2>/dev/null || pnpm outdated --json 2>/dev/null+```++### 5. Analyze Dependency Paths++For transitive vulnerabilities, find the path:++```bash+# npm+npm explain [package-name]++# pnpm+pnpm why [package-name]+```++### 6. Generate Report++Prioritise findings by:+1. **Critical/High security** - Fix immediately+2. **Moderate security** - Fix soon+3. **Major outdated** - Plan upgrade+4. **Minor/patch outdated** - Safe to update++### 7. Provide Fix Commands++For each issue, provide the specific fix:++```bash+# Direct dependency fix+npm update [package]@[version]++# Transitive dependency (override)+# Add to package.json:+"overrides": {+ "[package]": "^[safe-version]"+}++# For pnpm, use pnpm.overrides in package.json+```++## Report Format++```markdown+## Dependency Audit Report++**Date**: [timestamp]+**Package Manager**: [npm/pnpm/yarn]+**Total Dependencies**: [count]++### Critical Vulnerabilities (X)++| Package | Version | Advisory | Fix |+|---------|---------|----------|-----|+| [name] | [ver] | [CVE/GHSA] | [command] |++### High Vulnerabilities (X)+[same format]++### Outdated Packages++**Major Updates** (breaking changes likely):+- [package]: [current] → [latest]++**Safe Updates** (minor + patch):+- [package]: [current] → [latest]++### Recommended Actions++1. [Prioritised fix command]+2. [Next fix]+3. [etc]+```++## Do NOT++- Run `npm audit fix --force` without explicit user confirmation+- Update major versions automatically (breaking changes)+- Ignore transitive dependency paths+- Skip verification after fixes++## Do++- Prioritise by severity+- Explain what each vulnerability means+- Provide copy-paste fix commands+- Verify fixes worked (re-run audit)+- Mention if vulnerability may not apply to usagediff --git a/skills/dependency-audit/commands/audit-deps.md b/skills/dependency-audit/commands/audit-deps.mdnew file mode 100644index 00000000..4bd7d44c--- /dev/null+++ b/skills/dependency-audit/commands/audit-deps.md@@ -0,0 +1,334 @@+# Audit Dependencies++Run comprehensive dependency audit and provide prioritised findings.++---++## Command Usage++`/audit-deps [options]`++- Full audit: `/audit-deps`+- Security only: `/audit-deps --security`+- Outdated only: `/audit-deps --outdated`+- With auto-fix: `/audit-deps --fix`+- Specific path: `/audit-deps ./packages/api`++---++## Your Task++Run a comprehensive dependency audit, parse results, and present prioritised findings with actionable recommendations.++### Step 1: Detect Package Manager++```bash+# Check for lock files+ls package-lock.json pnpm-lock.yaml yarn.lock bun.lockb 2>/dev/null+```++| Found | Package Manager |+|-------|-----------------|+| `pnpm-lock.yaml` | pnpm |+| `package-lock.json` | npm |+| `yarn.lock` | yarn |+| `bun.lockb` | bun |++If multiple found, prefer in order: pnpm > npm > yarn > bun++### Step 2: Run Security Audit++```bash+# npm+npm audit --json 2>/dev/null | head -500++# pnpm+pnpm audit --json 2>/dev/null | head -500++# yarn+yarn audit --json 2>/dev/null | head -500+```++Parse the JSON output and categorise by severity.++### Step 3: Check Outdated Packages++```bash+# npm+npm outdated --json 2>/dev/null++# pnpm+pnpm outdated --json 2>/dev/null+```++Categorise updates:+- **Major**: First version number changed (breaking changes likely)+- **Minor**: Second version number changed (new features, backwards compatible)+- **Patch**: Third version number changed (bug fixes)++### Step 4: Check Licenses (if --license flag)++```bash+# Using license-checker+npx license-checker --json --production 2>/dev/null | head -200+```++Flag problematic licenses:+- **GPL-3.0, AGPL-3.0**: Copyleft, may require open-sourcing your code+- **UNLICENSED**: No license, cannot legally use+- **Unknown**: Needs manual review++### Step 5: Present Findings++```+═══════════════════════════════════════════════+ DEPENDENCY AUDIT REPORT+═══════════════════════════════════════════════++Project: [package.json name]+Package Manager: [detected]+Scanned: [date/time]++───────────────────────────────────────────────+ SECURITY VULNERABILITIES+───────────────────────────────────────────────+```++**For each vulnerability:**++```+🔴 CRITICAL: [package]@[version]+ │+ ├─ Advisory: [CVE-XXXX-XXXXX or GHSA-XXXX-XXXX-XXXX]+ ├─ Title: [vulnerability title]+ ├─ Severity: Critical (CVSS: 9.8)+ ├─ Path: [dependency path if transitive]+ │+ └─ Fix: [npm update package@version] or [manual steps]+```++Group by severity: Critical > High > Moderate > Low++### Step 6: Outdated Packages Summary++```+───────────────────────────────────────────────+ OUTDATED PACKAGES+───────────────────────────────────────────────++Major Updates (3) - Review breaking changes:+ ┌────────────────┬───────────┬───────────┬─────────────┐+ │ Package │ Current │ Latest │ Type │+ ├────────────────┼───────────┼───────────┼─────────────┤+ │ react │ 18.2.0 │ 19.1.0 │ dependency │+ │ typescript │ 5.3.0 │ 6.0.0 │ devDep │+ │ drizzle-orm │ 0.44.0 │ 1.0.0 │ dependency │+ └────────────────┴───────────┴───────────┴─────────────┘++Minor Updates (5) - Safe, new features+Patch Updates (12) - Recommended++Total outdated: 20 packages+```++### Step 7: Summary and Recommendations++```+───────────────────────────────────────────────+ SUMMARY+───────────────────────────────────────────────++Security:+ 🔴 Critical: 1+ 🟠 High: 2+ 🟡 Moderate: 3+ 🔵 Low: 5++Outdated:+ Major: 3 (review before update)+ Minor: 5 (safe to update)+ Patch: 12 (recommended)++═══════════════════════════════════════════════+ RECOMMENDED ACTIONS+═══════════════════════════════════════════════++1. [URGENT] Fix critical vulnerability:+ npm update [email protected]++2. [HIGH] Run audit fix for compatible updates:+ npm audit fix++3. [MODERATE] Update minor versions:+ npm update++4. [REVIEW] Major updates require manual review:+ - react 18→19: https://react.dev/blog/2024/04/25/react-19+ - typescript 5→6: Check breaking changes++Would you like to:+1. Auto-fix safe updates (minor + patch)+2. View detailed vulnerability info+3. Generate update plan+4. Done++Your choice [1-4]:+```++### Step 8: Auto-Fix Mode (if --fix)++```+═══════════════════════════════════════════════+ AUTO-FIX MODE+═══════════════════════════════════════════════++Will update:+ ✅ 12 patch updates (safe)+ ✅ 5 minor updates (backwards compatible)+ ⏭️ 3 major updates (skipped - breaking changes)++Proceed? [Y/n]+```++If confirmed:+```bash+# npm+npm update++# pnpm+pnpm update++# For security fixes+npm audit fix+```++Then verify:+```bash+# Re-run audit to confirm fixes+npm audit+```++---++## Error Handling++**If audit fails:**+```+⚠️ Audit command failed++Error: [error message]++Common causes:+- No package-lock.json (run npm install first)+- Network issues (check connectivity)+- Private registry auth (check .npmrc)++Would you like to:+1. Run npm install first+2. Skip audit and check outdated only+3. Cancel++Your choice [1-3]:+```++**If no vulnerabilities found:**+```+═══════════════════════════════════════════════+ ✅ NO VULNERABILITIES FOUND+═══════════════════════════════════════════════++Security: 0 vulnerabilities+Outdated: [X] packages have updates available++Your dependencies are secure!++Would you like to check for outdated packages? [Y/n]+```++**If fix introduces breaking changes:**+```+⚠️ npm audit fix --force would:++- Update react from 18.2.0 to 19.1.0 (BREAKING)+- Update @types/node from 18.x to 22.x (BREAKING)++This may break your application.++Options:+1. Fix only safe updates (recommended)+2. Force all updates (may break build)+3. Cancel and review manually++Your choice [1-3]:+```++---++## Dependency Path Analysis++For transitive vulnerabilities:++```+Vulnerability in: [email protected]++Dependency path:+ your-project+ └─ [email protected]+ └─ [email protected] (vulnerable)++To fix:+ Option 1: Update mkdirp to latest+ npm update mkdirp++ Option 2: Override transitive dependency+ Add to package.json:+ "overrides": {+ "minimist": "^1.2.8"+ }+```++---++## CI Integration Snippets++**For GitHub Actions:**+```yaml+- name: Audit dependencies+ run: |+ npm audit --audit-level=moderate+ echo "audit_exit_code=$?" >> $GITHUB_OUTPUT+```++**For pre-commit hook:**+```bash+#!/bin/sh+npm audit --audit-level=critical+```++---++## Options Reference++| Option | Description |+|--------|-------------|+| `--security` | Only check security vulnerabilities |+| `--outdated` | Only check outdated packages |+| `--license` | Include license compliance check |+| `--fix` | Auto-fix safe updates |+| `--json` | Output JSON format |+| `--ci` | CI-friendly output (exit codes) |++---++## Important Notes++- **Run after npm install**: Audit needs lock file+- **Transitive deps**: Some fixes require updating parent packages+- **Major updates**: Always review changelogs before updating+- **npm audit fix --force**: Can break your app (use with caution)+- **Private packages**: May need registry auth for full audit++---++**Version**: 1.0.0+**Last Updated**: 2026-02-03diff --git a/skills/drizzle-orm-d1/SKILL.md b/skills/drizzle-orm-d1/SKILL.mdindex 0c6881cb..d37bac02 100644--- a/skills/drizzle-orm-d1/SKILL.md+++ b/skills/drizzle-orm-d1/SKILL.md@@ -10,7 +10,15 @@ user-invocable: true# Drizzle ORM for Cloudflare D1**Status**: Production Ready ✅-**Last Updated**: 2026-01-20+**Last Updated**: 2026-02-03++## Commands++| Command | Purpose |+|---------|---------|+| `/db-init` | Set up Drizzle ORM with D1 (schema, config, migrations) |+| `/migrate` | Generate and apply database migrations |+| `/seed` | Seed database with initial or test data |**Dependencies**: cloudflare-d1, cloudflare-worker-basediff --git a/skills/drizzle-orm-d1/commands/init.md b/skills/drizzle-orm-d1/commands/db-init.mdsimilarity index 100%rename from skills/drizzle-orm-d1/commands/init.mdrename to skills/drizzle-orm-d1/commands/db-init.mddiff --git a/skills/drizzle-orm-d1/commands/migrate.md b/skills/drizzle-orm-d1/commands/migrate.mdnew file mode 100644index 00000000..c105d6d8--- /dev/null+++ b/skills/drizzle-orm-d1/commands/migrate.md@@ -0,0 +1,324 @@+# Migrate++Run Drizzle ORM migrations for D1 database.++---++## Command Usage++`/migrate [options]`++- Generate & apply: `/migrate` (interactive)+- Generate only: `/migrate --generate`+- Apply local: `/migrate --local`+- Apply remote: `/migrate --remote`+- Check status: `/migrate --status`++---++## Your Task++Manage D1 database migrations through Drizzle Kit. Guide the user through a safe migration workflow.++### Step 1: Discover Project State++Check for Drizzle configuration:++```bash+# Find Drizzle config+ls drizzle.config.ts drizzle.config.js 2>/dev/null++# Find schema location+grep -l "sqliteTable\|integer\|text" src/**/*.ts 2>/dev/null | head -3++# Check existing migrations+ls -la migrations/ drizzle/ 2>/dev/null | head -10+```++If no config found:+```+⚠️ Drizzle not configured in this project.++Run /db-init first to set up Drizzle ORM with D1.+```++### Step 2: Check for Schema Changes++```bash+# Check what migrations would be generated+npx drizzle-kit generate --dry-run 2>&1+```++Report the status:++```+═══════════════════════════════════════════════+ MIGRATION STATUS+═══════════════════════════════════════════════++Schema file: src/db/schema.ts+Migrations directory: ./migrations++Pending changes detected:+ + CREATE TABLE posts (id, title, content, authorId, createdAt)+ + CREATE INDEX idx_posts_author ON posts(authorId)+ ~ ALTER TABLE users ADD COLUMN avatarUrl TEXT++Existing migrations:+ ✅ 0001_init.sql (applied)+ ✅ 0002_add_comments.sql (applied)++What would you like to do?++1. Generate new migration+2. Apply pending migrations (local)+3. Apply pending migrations (remote)+4. View migration details+5. Cancel++Your choice [1-5]:+```++### Step 3: Generate Migration++If user chooses to generate:++```bash+# Generate migration with timestamp+npx drizzle-kit generate --name=$(date +%Y%m%d_%H%M%S)+```++Show the generated SQL:++```+═══════════════════════════════════════════════+ MIGRATION GENERATED+═══════════════════════════════════════════════++File: migrations/0003_20260203_143022.sql++┌──────────────────────────────────────────────┐+│ -- Migration: 0003_20260203_143022 │+│ │+│ CREATE TABLE posts ( │+│ id INTEGER PRIMARY KEY AUTOINCREMENT, │+│ title TEXT NOT NULL, │+│ content TEXT, │+│ authorId INTEGER REFERENCES users(id), │+│ createdAt INTEGER DEFAULT (unixepoch()) │+│ ); │+│ │+│ CREATE INDEX idx_posts_author ON posts(authorId);│+└──────────────────────────────────────────────┘++⚠️ REVIEW CAREFULLY before applying:+ - No destructive changes detected ✅+ - Foreign key constraint on authorId++Apply this migration? [Y/n]+```++### Step 4: Check for Dangerous Changes++**Before applying, scan for destructive operations:**++```bash+grep -iE "DROP|DELETE|TRUNCATE|ALTER.*DROP" migrations/*.sql+```++If destructive changes found:+```+⚠️ DESTRUCTIVE CHANGES DETECTED++The following operations will cause data loss:++🔴 DROP TABLE comments;+🔴 ALTER TABLE users DROP COLUMN legacyId;++This will permanently delete:+ - All rows in 'comments' table+ - Data in 'legacyId' column for all users++Are you SURE you want to proceed? Type "yes I understand" to continue:+```++### Step 5: Apply Migrations - Local First++**Always test locally before production:**++```bash+# Apply to local D1+npx wrangler d1 migrations apply <database-name> --local+```++Report results:++```+═══════════════════════════════════════════════+ LOCAL MIGRATION+═══════════════════════════════════════════════++Database: my-database (local)+Migration: 0003_20260203_143022.sql++Applying... ✅ Success!++Verification:+ Tables: users, posts, comments (3 total)+ New table 'posts': ✅ Created+ Index 'idx_posts_author': ✅ Created++Local database is up to date.++Apply to remote database? [Y/n]+```++### Step 6: Apply Migrations - Remote++```bash+# Apply to production D1+npx wrangler d1 migrations apply <database-name> --remote+```++Report results:++```+═══════════════════════════════════════════════+ REMOTE MIGRATION+═══════════════════════════════════════════════++Database: my-database (remote)+Migration: 0003_20260203_143022.sql++Applying... ✅ Success!++Verification:+ Tables: users, posts, comments (3 total)+ Rows affected: 0 (schema-only change)++✅ Production database updated successfully!++═══════════════════════════════════════════════+ MIGRATION COMPLETE+═══════════════════════════════════════════════++Applied: 0003_20260203_143022.sql++Local: ✅ Applied+Remote: ✅ Applied++Your database schema is now in sync.+```++---++## Status Check Mode++When `/migrate --status`:++```+═══════════════════════════════════════════════+ DATABASE MIGRATION STATUS+═══════════════════════════════════════════════++Schema: src/db/schema.ts+Config: drizzle.config.ts++Local Database:+ Name: my-database+ Tables: users, posts, comments (3)+ Migrations applied: 3++Remote Database:+ Name: my-database+ Tables: users, posts, comments (3)+ Migrations applied: 3++Migration Files:+ ✅ 0001_init.sql+ ✅ 0002_add_comments.sql+ ✅ 0003_20260203_143022.sql++Status: ✅ Schema in sync (no pending changes)+```++---++## Error Handling++**If migration fails locally:**+```+❌ Local migration failed++Error: UNIQUE constraint failed: users.email++This usually means:+ - Duplicate data exists that violates the new constraint+ - Schema drift between code and database++Options:+1. Fix the data and retry+2. Roll back the migration+3. View detailed error++Your choice [1-3]:+```++**If remote fails but local succeeded:**+```+⚠️ Remote migration failed (local succeeded)++Error: table "posts" already exists++Databases are now out of sync!++Options:+1. Check remote table schema (may be from manual changes)+2. Force apply (dangerous - may lose data)+3. Abort and investigate++Your choice [1-3]:+```++**If Drizzle 1.0 nested migration issue detected:**+```+⚠️ Nested migration folders detected++Drizzle 1.0 generates migrations in subfolders:+ migrations/0003_random/migration.sql++But wrangler expects flat structure:+ migrations/0003_random.sql++Flattening migrations automatically...+```++Then run the flatten script from Issue #18.++---++## Quick Reference++| Command | Description |+|---------|-------------|+| `/migrate` | Interactive migration workflow |+| `/migrate --generate` | Generate migration only, don't apply |+| `/migrate --local` | Apply pending migrations to local D1 |+| `/migrate --remote` | Apply pending migrations to remote D1 |+| `/migrate --status` | Show migration status |+| `/migrate --rollback` | Show rollback guidance (manual) |++---++## Important Notes++- **Local first**: Always apply to local before remote+- **Review SQL**: Always review generated migrations before applying+- **No auto-rollback**: D1/SQLite doesn't support transactional DDL - migrations are atomic+- **Backup production**: For destructive changes, backup data first+- **Drizzle Kit vs Wrangler**: Use `drizzle-kit generate` then `wrangler d1 migrations apply`++---++**Version**: 1.0.0+**Last Updated**: 2026-02-03diff --git a/skills/drizzle-orm-d1/commands/seed.md b/skills/drizzle-orm-d1/commands/seed.mdnew file mode 100644index 00000000..4456680b--- /dev/null+++ b/skills/drizzle-orm-d1/commands/seed.md@@ -0,0 +1,341 @@+# Seed++Seed D1 database with initial or test data using Drizzle ORM.++---++## Command Usage++`/seed [options]`++- Run seed: `/seed` (runs default seed file)+- Create seed file: `/seed --init`+- Run with truncate: `/seed --reset` (clears tables first)+- Specific file: `/seed scripts/seed-users.ts`++---++## Your Task++Help the user seed their D1 database. Create seed files if they don't exist, run seeds safely, and handle D1's parameter limits.++### Step 1: Check for Existing Seed File++```bash+# Common seed file locations+ls src/db/seed.ts db/seed.ts scripts/seed.ts seed.ts 2>/dev/null+```++If no seed file exists:+```+═══════════════════════════════════════════════+ DATABASE SEEDING+═══════════════════════════════════════════════++No seed file found.++Would you like me to create one?++1. Create seed file with example data+2. Create empty seed template+3. Specify custom location++Your choice [1-3]:+```++### Step 2: Create Seed File (if needed)++Create `src/db/seed.ts`:++```typescript+import { drizzle } from 'drizzle-orm/d1';+import * as schema from './schema';++// D1 has a 100-parameter limit per query+// Chunk large inserts to avoid "too many SQL variables" error+const D1_CHUNK_SIZE = 30; // Safe for 3-column tables (30 * 3 = 90 params)++async function chunkInsert<T>(+ db: ReturnType<typeof drizzle>,+ table: any,+ items: T[],+ chunkSize = D1_CHUNK_SIZE+) {+ for (let i = 0; i < items.length; i += chunkSize) {+ const chunk = items.slice(i, i + chunkSize);+ await db.insert(table).values(chunk);+ console.log(`Inserted ${Math.min(i + chunkSize, items.length)}/${items.length}`);+ }+}++export async function seed(db: ReturnType<typeof drizzle>) {+ console.log('🌱 Seeding database...');++ // Example: Seed users+ const users = [+ { email: '[email protected]', name: 'Admin User' },+ { email: '[email protected]', name: 'Test User 1' },+ { email: '[email protected]', name: 'Test User 2' },+ ];++ await chunkInsert(db, schema.users, users);+ console.log(`✅ Seeded ${users.length} users`);++ // Add more seed data here...++ console.log('🌱 Seeding complete!');+}++// Run seed directly (for local dev)+// npx wrangler d1 execute <db-name> --local --file=src/db/seed.ts+```++### Step 3: Create Seed Runner Script++Create `scripts/run-seed.ts`:++```typescript+import { drizzle } from 'drizzle-orm/better-sqlite3';+import Database from 'better-sqlite3';+import { seed } from '../src/db/seed';+import * as schema from '../src/db/schema';++// For local development using SQLite directly+async function main() {+ // Path to local D1 database+ const dbPath = '.wrangler/state/v3/d1/<database-id>/db.sqlite';++ const sqlite = new Database(dbPath);+ const db = drizzle(sqlite, { schema });++ try {+ await seed(db);+ console.log('✅ Seed complete');+ } catch (error) {+ console.error('❌ Seed failed:', error);+ process.exit(1);+ } finally {+ sqlite.close();+ }+}++main();+```++Add to `package.json`:+```json+{+ "scripts": {+ "db:seed": "tsx scripts/run-seed.ts",+ "db:seed:reset": "npm run db:seed -- --reset"+ }+}+```++### Step 4: Run Seed++```+═══════════════════════════════════════════════+ RUNNING SEED+═══════════════════════════════════════════════++Seed file: src/db/seed.ts+Target: Local D1 database++Running seed...++🌱 Seeding database...+ Inserted 3/3 users+ Inserted 10/10 posts+ Inserted 25/25 comments+🌱 Seeding complete!++═══════════════════════════════════════════════+ SEED COMPLETE+═══════════════════════════════════════════════++Records created:+ - users: 3+ - posts: 10+ - comments: 25++Total: 38 records++Would you like to:+1. View seeded data+2. Seed remote database+3. Done++Your choice [1-3]:+```++### Step 5: Seed Remote (with confirmation)++```+⚠️ Seeding PRODUCTION database++This will insert data into your remote D1 database.++Tables to seed:+ - users (3 records)+ - posts (10 records)+ - comments (25 records)++Continue? [y/N]:+```++---++## Reset Mode++When `/seed --reset`:++```+⚠️ RESET MODE++This will:+1. TRUNCATE all seeded tables+2. Re-insert seed data++Data in these tables will be DELETED:+ - users+ - posts+ - comments++Type "reset" to confirm:+```++Then run:+```typescript+// Truncate in correct order (respect foreign keys)+await db.delete(schema.comments);+await db.delete(schema.posts);+await db.delete(schema.users);++// Re-seed+await seed(db);+```++---++## D1 Parameter Limit Handling++**Critical**: D1 has a 100-parameter limit per query. The seed template includes chunking.++```+⚠️ D1 Parameter Limit++Your seed has 150 records × 3 columns = 450 parameters++This exceeds D1's 100-parameter limit.++Automatically chunking into batches of 30 records...+ Batch 1/5: Inserted 30 records+ Batch 2/5: Inserted 30 records+ Batch 3/5: Inserted 30 records+ Batch 4/5: Inserted 30 records+ Batch 5/5: Inserted 30 records++✅ All 150 records inserted successfully+```++---++## Error Handling++**If foreign key constraint fails:**+```+❌ Seed failed++Error: FOREIGN KEY constraint failed++This usually means:+ - Referenced record doesn't exist+ - Seed order is wrong (insert parent before child)++Fix: Ensure parent tables are seeded before child tables.+```++**If unique constraint fails:**+```+❌ Seed failed++Error: UNIQUE constraint failed: users.email++This usually means:+ - Seed data already exists+ - Running seed multiple times++Fix: Use /seed --reset to clear existing data first.+```++**If parameter limit exceeded:**+```+❌ Seed failed++Error: too many SQL variables++Your seed exceeds D1's 100-parameter limit.+Use the chunkInsert helper from the seed template.+```++---++## Seed Data Patterns++### Factory Pattern (for large datasets)++```typescript+function createUser(index: number) {+ return {+ email: `user${index}@example.com`,+ name: `User ${index}`,+ createdAt: new Date(),+ };+}++const users = Array.from({ length: 100 }, (_, i) => createUser(i + 1));+await chunkInsert(db, schema.users, users);+```++### Realistic Fake Data++```typescript+// Using faker (npm install @faker-js/faker)+import { faker } from '@faker-js/faker';++const users = Array.from({ length: 50 }, () => ({+ email: faker.internet.email(),+ name: faker.person.fullName(),+ createdAt: faker.date.past(),+}));+```++### Environment-Specific Seeds++```typescript+const environment = process.env.NODE_ENV || 'development';++if (environment === 'development') {+ // Seed with test data+ await seedTestUsers(db);+} else if (environment === 'production') {+ // Seed only essential data (admin user, etc.)+ await seedAdminUser(db);+}+```++---++## Important Notes++- **Chunk large inserts**: D1 has 100-parameter limit+- **Order matters**: Seed parent tables before child tables+- **Idempotency**: Use upsert or check existence before insert+- **Local first**: Test seeds locally before running on remote+- **Don't seed production carelessly**: Confirm before inserting into remote++---++**Version**: 1.0.0+**Last Updated**: 2026-02-03diff --git a/skills/testing-patterns/.claude-plugin/plugin.json b/skills/testing-patterns/.claude-plugin/plugin.jsonindex d16ca254..715fc2a7 100644--- a/skills/testing-patterns/.claude-plugin/plugin.json+++ b/skills/testing-patterns/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "testing-patterns",- "description": "Agent-based declarative testing with YAML test specs. Tests run in sub-agents to preserve main context while executing many tests. Supports MCP servers, APIs, and browser automation. Use when: testing MCP servers, running integration tests, validating tool behavior after changes, or creating regression test suites.",+ "description": "What these tests validate","version": "1.0.0","author": {"name": "Jeremy Dawes",@@ -8,6 +8,6 @@},"license": "MIT","repository": "https://github.com/jezweb/claude-skills",- "keywords": ["yaml tests", "agent testing", "mcp test", "integration tests", "test runner"],+ "keywords": [],"agents": []}diff --git a/skills/testing-patterns/SKILL.md b/skills/testing-patterns/SKILL.mdindex 27f9d6c9..f86ed5a0 100644--- a/skills/testing-patterns/SKILL.md+++ b/skills/testing-patterns/SKILL.md@@ -41,6 +41,7 @@ Running 50 tests in the main conversation would consume your entire context wind|---------|---------|| `/create-tests` | Discover project, generate test specs + testing agent || `/run-tests` | Execute tests via agent(s), report results |+| `/coverage` | Generate coverage report and identify uncovered code paths |**Quick workflow:**```@@ -48,6 +49,8 @@ Running 50 tests in the main conversation would consume your entire context wind/run-tests → Spawns agent, runs all tests, saves results/run-tests api → Run only specs matching "api"/run-tests --failed → Re-run only failed tests+/coverage → Run tests with coverage, analyse gaps+/coverage --threshold 80 → Fail if below 80%```## Getting Started in a New Projectdiff --git a/skills/testing-patterns/commands/coverage.md b/skills/testing-patterns/commands/coverage.mdnew file mode 100644index 00000000..a68c54f9--- /dev/null+++ b/skills/testing-patterns/commands/coverage.md@@ -0,0 +1,458 @@+# Coverage++Generate test coverage report and identify uncovered code paths.++---++## Command Usage++`/coverage [options]`++- Basic: `/coverage` (run with defaults)+- With threshold: `/coverage --threshold 80`+- Specific path: `/coverage src/components/`+- Report only: `/coverage --report-only` (show last report without running tests)++---++## Your Task++Detect the test runner, run tests with coverage enabled, parse the report, and highlight critical uncovered paths.++### Step 1: Detect Test Runner++```bash+# Check for test configs+ls vitest.config.* vite.config.* jest.config.* c8.config.* nyc.config.* .nycrc* pytest.ini pyproject.toml 2>/dev/null+```++Determine the test runner:++| Found | Runner | Coverage Tool |+|-------|--------|---------------|+| `vitest.config.*` or `vite.config.*` with vitest | Vitest | Built-in (v8 or c8) |+| `jest.config.*` | Jest | Built-in or `--coverage` |+| `.nycrc*` or `nyc.config.*` | NYC/Istanbul | NYC |+| `c8.config.*` | c8 | c8 |+| `pytest.ini` or pyproject with pytest | pytest | pytest-cov |++If no test runner found:+```+⚠️ No test runner configuration found.++This project doesn't appear to have a test framework set up.++Options:+1. Set up Vitest (recommended for Vite projects)+2. Set up Jest+3. Specify test command manually++Your choice [1-3]:+```++### Step 2: Check Coverage Configuration++**For Vitest**, check vite.config.ts or vitest.config.ts:++```typescript+// Should have coverage configured+export default defineConfig({+ test: {+ coverage: {+ provider: 'v8', // or 'istanbul'+ reporter: ['text', 'json', 'html'],+ reportsDirectory: './coverage'+ }+ }+})+```++If missing:+```+⚠️ Coverage not configured in Vitest.++Add to vite.config.ts:++ test: {+ coverage: {+ provider: 'v8',+ reporter: ['text', 'json', 'html'],+ reportsDirectory: './coverage'+ }+ }++Would you like me to add this configuration? [Y/n]+```++**For Jest**, check jest.config.*:++```javascript+// Should have coverage configured+module.exports = {+ collectCoverage: true,+ coverageDirectory: 'coverage',+ coverageReporters: ['text', 'json', 'html']+}+```++### Step 3: Run Coverage++```+═══════════════════════════════════════════════+ RUNNING COVERAGE+═══════════════════════════════════════════════++Test Runner: Vitest+Coverage Provider: v8+Output Directory: ./coverage++Running: npm run test -- --coverage+```++Execute the coverage command:++```bash+# Vitest+npm run test -- --coverage 2>&1++# Jest+npm run test -- --coverage 2>&1++# pytest+pytest --cov=src --cov-report=term-missing --cov-report=json 2>&1+```++### Step 4: Parse Coverage Report++Read the coverage summary from JSON or terminal output:++**Vitest/Jest (coverage/coverage-summary.json)**:+```bash+cat coverage/coverage-summary.json 2>/dev/null+```++**pytest (coverage.json)**:+```bash+cat coverage.json 2>/dev/null+```++Extract key metrics:++```+═══════════════════════════════════════════════+ COVERAGE REPORT+═══════════════════════════════════════════════++Overall Coverage: 73.5%++╭──────────────────┬────────────┬─────────────╮+│ Metric │ Covered │ Percentage │+├──────────────────┼────────────┼─────────────┤+│ Statements │ 1,245/1,695│ 73.5% │+│ Branches │ 312/485 │ 64.3% │+│ Functions │ 156/198 │ 78.8% │+│ Lines │ 1,189/1,620│ 73.4% │+╰──────────────────┴────────────┴─────────────╯+```++### Step 5: Identify Critical Uncovered Paths++Analyze uncovered code and prioritise by importance:++**Priority 1 (Critical)** - Business logic, security, data handling:+- Authentication/authorization code+- Payment/transaction processing+- Data validation+- Error handlers that could fail silently++**Priority 2 (Important)** - Core features:+- Main user flows+- API endpoints+- State management+- Utility functions used widely++**Priority 3 (Low)** - Edge cases, UI:+- Rarely-used features+- Cosmetic UI code+- Development-only code++```+═══════════════════════════════════════════════+ UNCOVERED CODE ANALYSIS+═══════════════════════════════════════════════++🔴 CRITICAL (needs immediate attention):++ src/auth/middleware.ts (42% covered)+ ├─ Lines 45-67: Token validation logic+ ├─ Lines 89-102: Role-based access check+ └─ Impact: Security vulnerability if these paths fail++ src/api/payments.ts (38% covered)+ ├─ Lines 112-145: Refund processing+ └─ Impact: Financial transactions untested++🟡 IMPORTANT (should be covered):++ src/components/UserForm.tsx (55% covered)+ ├─ Lines 78-92: Form validation+ └─ Impact: User experience issues++ src/utils/dataTransform.ts (61% covered)+ ├─ Lines 34-56: Edge case handling+ └─ Impact: Data corruption risk++🟢 LOW PRIORITY (nice to have):++ src/components/LoadingSpinner.tsx (25% covered)+ └─ Reason: UI-only, no logic++ src/dev/debugTools.ts (0% covered)+ └─ Reason: Development-only code+```++### Step 6: Check Against Threshold++If threshold specified (or project has one configured):++```+═══════════════════════════════════════════════+ THRESHOLD CHECK+═══════════════════════════════════════════════++Required: 80%+Actual: 73.5%+Status: ❌ BELOW THRESHOLD++Gap: 6.5% (approximately 110 lines)++Fastest path to 80%:+1. src/auth/middleware.ts (+15 lines = +0.9%)+2. src/api/payments.ts (+45 lines = +2.7%)+3. src/components/UserForm.tsx (+20 lines = +1.2%)+4. src/utils/dataTransform.ts (+30 lines = +1.8%)++Total: +110 lines to reach 80%+```++If threshold met:+```+═══════════════════════════════════════════════+ ✅ THRESHOLD MET+═══════════════════════════════════════════════++Required: 80%+Actual: 82.3%+Status: ✅ PASSING++Margin: +2.3% above threshold+```++### Step 7: Output Summary++```+═══════════════════════════════════════════════+ COVERAGE SUMMARY+═══════════════════════════════════════════════++Overall: 73.5% (1,245/1,695 statements)++By Category:+ Statements: 73.5%+ Branches: 64.3% ← Lowest+ Functions: 78.8%+ Lines: 73.4%++Critical Gaps:+ 🔴 src/auth/middleware.ts (42%)+ 🔴 src/api/payments.ts (38%)++Reports:+ HTML: coverage/index.html+ JSON: coverage/coverage-summary.json+ Text: (shown above)++═══════════════════════════════════════════════+ NEXT STEPS+═══════════════════════════════════════════════++1. Open HTML report - Detailed line-by-line view+2. Focus on critical - Write tests for 🔴 items+3. Generate test stubs - Scaffold tests for uncovered+4. Set threshold - Add to CI pipeline+5. Done for now++Your choice [1-5]:+```++---++## Coverage Configuration Templates++### Vitest (vite.config.ts)++```typescript+import { defineConfig } from 'vite'++export default defineConfig({+ test: {+ coverage: {+ provider: 'v8',+ reporter: ['text', 'text-summary', 'json', 'html'],+ reportsDirectory: './coverage',+ include: ['src/**/*.{ts,tsx}'],+ exclude: [+ 'src/**/*.d.ts',+ 'src/**/*.test.{ts,tsx}',+ 'src/test/**/*'+ ],+ thresholds: {+ statements: 80,+ branches: 70,+ functions: 80,+ lines: 80+ }+ }+ }+})+```++### Jest (jest.config.js)++```javascript+module.exports = {+ collectCoverage: true,+ coverageDirectory: 'coverage',+ coverageReporters: ['text', 'text-summary', 'json', 'html'],+ collectCoverageFrom: [+ 'src/**/*.{js,jsx,ts,tsx}',+ '!src/**/*.d.ts',+ '!src/**/*.test.{js,jsx,ts,tsx}'+ ],+ coverageThreshold: {+ global: {+ statements: 80,+ branches: 70,+ functions: 80,+ lines: 80+ }+ }+}+```++### pytest (pyproject.toml)++```toml+[tool.pytest.ini_options]+addopts = "--cov=src --cov-report=term-missing --cov-report=html --cov-report=json"++[tool.coverage.run]+source = ["src"]+omit = ["**/test_*.py", "**/conftest.py"]++[tool.coverage.report]+fail_under = 80+exclude_lines = [+ "pragma: no cover",+ "if __name__ == .__main__.:",+ "raise NotImplementedError"+]+```++---++## Error Handling++**If tests fail:**+```+❌ Tests failed - coverage incomplete.++Failed tests: 3++Please fix failing tests first, then re-run coverage.++Would you like to:+1. See failed test details+2. Run coverage anyway (--ignore-failures)+3. Cancel++Your choice [1-3]:+```++**If coverage tool not installed:**+```+❌ Coverage tool not found.++For Vitest: npm install -D @vitest/coverage-v8+For Jest: npm install -D jest (coverage built-in)+For pytest: pip install pytest-cov++Would you like me to install the coverage tool? [Y/n]+```++**If coverage report not generated:**+```+⚠️ Coverage report not generated.++Check:+1. Coverage is enabled in config+2. Tests actually ran+3. Output directory is writable++Last command output:+[show relevant error output]+```++---++## Options Reference++| Option | Description | Example |+|--------|-------------|---------|+| `--threshold N` | Fail if below N% | `--threshold 80` |+| `--report-only` | Show last report | `--report-only` |+| `--include PATH` | Only cover path | `--include src/api/` |+| `--exclude PATH` | Exclude from coverage | `--exclude src/test/` |+| `--json` | Output JSON summary | `--json` |+| `--open` | Open HTML report in browser | `--open` |++---++## CI Integration++**GitHub Actions:**++```yaml+- name: Run tests with coverage+ run: npm run test -- --coverage++- name: Check coverage threshold+ run: |+ COVERAGE=$(jq '.total.statements.pct' coverage/coverage-summary.json)+ if (( $(echo "$COVERAGE < 80" | bc -l) )); then+ echo "Coverage $COVERAGE% is below 80% threshold"+ exit 1+ fi+```++**Pre-commit hook:**++```bash+#!/bin/sh+npm run test -- --coverage --threshold 80 || exit 1+```++---++## Important Notes++- **Vitest v8 provider**: Fastest, works with most projects+- **Jest coverage**: Built-in, no extra install needed+- **Branch coverage**: Often lower than line coverage - focus here+- **Critical paths**: Prioritise security and business logic+- **Thresholds**: Set realistic goals, improve incrementally++---++**Version**: 1.0.0+**Last Updated**: 2026-02-03