New advertisers: 50% off your first month with code FIRSTMONTHSee slots
laurigates avatar

code-quality-plugin

Broad code-quality toolkit for Claude Code covering review, linting, dead code, and complexity analysis.

version
1.30.4
GitHub stars
60
View on GitHub

What it does

  • Adds /code:review, /code:lint, /code:refactor, /code:dead-code, and /code:complexity commands with five specialist agents
  • Covers anti-pattern scans via /code:antipatterns, dependency CVE and license audits via /code:dep-audit, and test smell detection via /code:test-quality
  • Runs structural matching with ast-grep and flags swallowed errors and silent degradation through /code:hidden-failures
  • Designed for maintainers auditing an existing codebase before a refactor or a release

Code review, refactoring, linting, dependency auditing, dead code detection, test quality, complexity metrics, and static analysis

Add marketplace

/plugin marketplace add laurigates/claude-plugins

Run it inside Claude Code once, then install the plugin below.

Install

/plugin install code-quality-plugin@laurigates-claude-plugins

Run it inside Claude Code after adding the marketplace.

Files

Discovered from source

ast-grep Structural Code Search & Refactoring

Structural code search and refactoring using ast-grep — matches code by its AST (abstract syntax tree) rather than text patterns.

When to Use This Skill

Use this skill when...Use something else instead when...
The pattern depends on AST structure (function shape, call form, argument count)Searching plain text or regex matches → tools-plugin:rg-code-search
Refactoring API call sites across many files while preserving captured variablesRunning a one-shot anti-pattern scan with a report → code-antipatterns
Hand-written structural search/replace for an ad-hoc migrationFunctional refactors of a known file/directory → code-refactor
Building a new ast-grep rule for a codebase-specific smellLooking up agentic flags for an existing linter → code-lint

When to Use ast-grep vs Grep/ripgrep

Use ast-grep when...Use grep/rg when...
Pattern depends on code structureSimple text or regex match
Need to match any number of argumentsSearching logs, docs, config
Refactoring across many filesOne-off literal string search
Finding anti-patterns (empty catch, etc.)Language doesn't matter
Replacing while preserving variablesQuick filename/line check

Decision rule: If your search pattern contains wildcards for "any expression," "any arguments," or "any function name," use ast-grep.

Find References With the Sharpest Instrument

Promoted from ~/.claude/rules/tool-use-patterns.md. Edit refuses on a file unread this session, so "read it first" is already a harness invariant. The uncovered half is checking what else depends on what you're changing, and the reflex there is grep, which cannot tell a call from a comment, a definition from a mention, or foo() from "foo" in a string. Measured across 282 local sessions: ~2,400 code-symbol searches went through grep/rg, against 6 ast-grep calls and 6 LSP calls.

Ladder, sharpest first. Falling back down it is normal; starting at the bottom for a code symbol is the miss.

Reach forWhen
LSP — findReferences, incomingCalls, goToDefinitionA language server is running for that filetype. Exact: no comment/string hits, and it follows imports and re-exports that no text pattern can.
ast-grep -p '$FN($$$ARGS)'No LSP, or the target is a shape rather than a name — a call with a given arity, a decorator, an un-awaited async call. Cross-language, bash included.
rgNon-code: markdown rules, chezmoi templates, config keys, justfile recipes, workflow YAML. The right tool there, not a fallback — most of a dotfiles or plugins repo is prose.

Two things that make the middle rung less automatic than it looks. A bare identifier pattern matches the definition too (ast-grep --lang bash -p 'foo' returns foo() { … } alongside every call), so an unshaped pattern is just grep with extra syntax. And a language server has to be on PATH, not merely installed — bash-language-server sitting in ~/.local/share/nvim/mason/bin is invisible to the LSP tool, which silently drops shell to the middle rung.

Structural tools carry their own empty-result trap: an ast-grep pattern that fails to parse returns no matches and exit 0, indistinguishable from a clean tree. Control-test the negative against a term you know is present, in the tool you are actually using (agent-patterns-plugin:tool-result-traps).

Pattern Syntax

PatternMatchesExample
$VARSingle AST nodeconsole.log($MSG)
$$$ARGSZero or more nodesfunc($$$ARGS)
$_Single node (no capture)$_ == $_
$A == $ASame node repeatedFinds x == x (not x == y)

Essential Commands

Search for Patterns

# Find structural patterns
ast-grep -p 'console.log($$$)' --lang js
ast-grep -p 'def $FUNC($$$): $$$' --lang py
ast-grep -p 'fn $NAME($$$) -> $RET { $$$ }' --lang rs

# Search in specific directory
ast-grep -p 'import $PKG' --lang js src/

# JSON output for parsing
ast-grep -p 'pattern' --lang js --json=compact

Search and Replace

# Preview changes (default - shows matches)
ast-grep -p 'var $V = $X' -r 'const $V = $X' --lang js

# Apply changes to all files
ast-grep -p 'var $V = $X' -r 'const $V = $X' --lang js -U

# Interactive review
ast-grep -p 'oldAPI($$$ARGS)' -r 'newAPI($$$ARGS)' --lang py -i

# Convert function syntax
ast-grep -p 'function($$$ARGS) { return $EXPR }' \
         -r '($$$ARGS) => $EXPR' --lang js -U

# Update import paths
ast-grep -p "import $NAME from '@old/$PATH'" \
         -r "import $NAME from '@new/$PATH'" --lang ts -U

Language Codes

CodeLanguageCodeLanguage
jsJavaScriptpyPython
tsTypeScriptrsRust
jsxJSXgoGo
tsxTSXjavaJava
cppC++rbRuby
cCphpPHP

Common Patterns by Language

JavaScript/TypeScript

# Find React hooks
ast-grep -p 'const [$STATE, $SETTER] = useState($INIT)' --lang jsx

# Find async functions
ast-grep -p 'async function $NAME($$$) { $$$ }' --lang js

# Find type assertions
ast-grep -p '$EXPR as $TYPE' --lang ts

# Find empty catch blocks
ast-grep -p 'try { $$$ } catch ($E) { }' --lang js

# Find eval usage (security)
ast-grep -p 'eval($$$)' --lang js

# Find innerHTML (XSS risk)
ast-grep -p '$ELEM.innerHTML = $$$' --lang js

# Find specific imports
ast-grep -p "import { $$$IMPORTS } from '$PKG'" --lang js

Python

# Find class definitions
ast-grep -p 'class $NAME($$$BASES): $$$' --lang py

# Find decorated functions
ast-grep -p '@$DECORATOR\ndef $FUNC($$$): $$$' --lang py

# Find dangerous shell calls
ast-grep -p 'os.system($$$)' --lang py

# Find SQL concatenation (injection risk)
ast-grep -p '"SELECT * FROM " + $VAR' --lang py

Rust

# Find unsafe blocks
ast-grep -p 'unsafe { $$$ }' --lang rs

# Find impl blocks
ast-grep -p 'impl $TRAIT for $TYPE { $$$ }' --lang rs

# Find public functions
ast-grep -p 'pub fn $NAME($$$) { $$$ }' --lang rs

Go

# Find goroutines
ast-grep -p 'go $FUNC($$$)' --lang go

# Find defer statements
ast-grep -p 'defer $FUNC($$$)' --lang go

# Find error handling
ast-grep -p 'if err != nil { $$$ }' --lang go

Common Refactoring Recipes

# Replace deprecated API calls
ast-grep -p 'oldAPI.$METHOD($$$)' -r 'newAPI.$METHOD($$$)' --lang js -U

# Rename a function across files
ast-grep -p 'oldName($$$ARGS)' -r 'newName($$$ARGS)' --lang py -U

# Remove console.log statements
ast-grep -p 'console.log($$$)' -r '' --lang js -U

# Convert require to import
ast-grep -p 'const $NAME = require($PKG)' \
         -r 'import $NAME from $PKG' --lang js -i

# Add error handling wrapper
ast-grep -p 'await $EXPR' \
         -r 'await $EXPR.catch(handleError)' --lang ts -i

Command-Line Flags

FlagPurpose
-p, --patternSearch pattern
-r, --rewriteReplacement pattern
-l, --langTarget language
-i, --interactiveReview changes one by one
-U, --update-allApply all changes
--jsonJSON output (compact, stream, pretty)
-A NLines after match
-B NLines before match
-C NLines around match
--debug-queryDebug pattern parsing

YAML Rules (Scan Mode)

For reusable rules, use ast-grep scan with YAML configuration:

# Scan with config
ast-grep scan -c sgconfig.yml

# Run specific rule
ast-grep scan -r rule-name

# Initialize a rules project
ast-grep new project my-linter
ast-grep new rule no-console-log

Minimal rule file:

id: no-empty-catch
language: JavaScript
severity: warning
message: Empty catch block hides errors
rule:
  pattern: try { $$$ } catch ($E) { }
fix: |
  try { $$$ } catch ($E) { console.error($E) }

For comprehensive YAML rule syntax, constraints, transformations, and testing, see REFERENCE.md.

Agentic Optimizations

ContextCommand
Quick structural searchast-grep -p 'pattern' --lang js --json=compact
Count matchesast-grep -p 'pattern' --lang js --json=stream | wc -l
File list onlyast-grep -p 'pattern' --json=stream | jq -r '.file' | sort -u
Batch refactorast-grep -p 'old' -r 'new' --lang js -U
Scan with rulesast-grep scan --json
Debug patternast-grep -p 'pattern' --debug-query --lang js

Quick Reference

# 1. Search for pattern
ast-grep -p 'pattern' --lang js src/

# 2. Preview rewrite
ast-grep -p 'old' -r 'new' --lang js

# 3. Apply rewrite
ast-grep -p 'old' -r 'new' --lang js -U

# 4. Scan with rules
ast-grep scan -c sgconfig.yml

# 5. Debug pattern
ast-grep -p 'pattern' --debug-query --lang js

Readme

Code Quality Plugin

Code review, refactoring, linting, anti-pattern detection, and static analysis for Claude Code.

Overview

This plugin provides comprehensive code quality tools including automated code review, refactoring assistance, linting, anti-pattern detection, dependency auditing, test quality analysis, and complexity metrics using ast-grep for structural analysis.

Skills

SkillDescription
/code:reviewComprehensive code review with automated fixes
/code:refactorRefactor code applying functional programming principles - pure functions, immutability, and composition
/code:antipatternsAnalyze codebase for anti-patterns and code smells using ast-grep
/code:lintRun the project's linters and formatters - auto-detects ruff/eslint/clippy/gofmt (--fix to autofix)
/code:dry-consolidationFind and extract duplicated code into shared, tested abstractions
/code:scaffold-backportBack-port an instance fix into the generator that produced it — cookiecutter/copier template, justfile new-* recipe, scaffolding skill — so the next generation isn't born with the same bug
/code:docs-qualityAnalyze documentation quality - PRDs, ADRs, PRPs, CLAUDE.md, and .claude/rules/
/code:hidden-failuresDetect hidden failures — swallowed errors (empty catch, || true, 2>/dev/null, floating promises, ignored Go/Rust errors) and silent degradation (ops succeed with zero results); --track errors|degradation|both
code-derived-factsCode facts from execution, not text — a mention is not a caller, a derived fact belongs in its consumer, a registry gaining a second kind, scripted multi-anchor source edits
/code:dead-codeDetect dead code, unused exports, unreachable branches, and orphaned files
/code:dep-auditAudit dependencies for security vulnerabilities, outdated packages, and license compliance
code-license-positionCheck a vendor's licence FAQ, discussion threads, and commit authors before calling a LICENSE restriction a blocker
/code:test-qualityAnalyze test suite quality — detect test smells, empty assertions, flaky patterns
/code:complexityAnalyze code complexity metrics — cyclomatic, cognitive, function length, coupling
/code-quality:code-context-leakageAudit a repo for names and defaults tied to one person's setup — home paths, personal channels, dated run tags, time-of-day recipe names, OS-only commands, stale self-references — classify each, then rename the approved ones behind a --name … --strict gate
/code-quality:bulk-sweep-classifyRoute a bulk sweep by target: code renames go through ast-grep-search structurally; prose/docs sweeps use the four-category classify-then-transform discipline with allowlist-aware verification; parallel sweeps resolve a central rename map before dispatch and brief auditors with the artifact's purpose
ast-grep-searchAST-based code search for structural pattern matching, and the LSP → ast-grep → rg ladder for finding references before a change
code-review-checklistChecklist for security, correctness, and performance review — secrets/injection, error handling, N+1 queries
debugging-methodologySystematic debugging for memory, performance, and system-level issues — leaks, strace/eBPF, profiling, races; diagnosing at the failure point (sentinel ids in errors, reading the resource for exhaustion symptoms); finding where threads block (off-CPU waits, kernel lock queues)

Agents

AgentDescription
code-reviewCode quality, architecture, and performance analysis
code-refactoringFunctional refactoring - pure functions, immutability, and composition
code-analysisStructural code analysis and pattern detection
linter-fixerAutomatic linting and code formatting
security-auditSecurity analysis and vulnerability assessment

Usage Examples

Code Review

/code:review src/

Performs comprehensive code review including:

  • Code quality analysis
  • Security assessment
  • Performance evaluation
  • Maintainability review

Anti-Pattern Detection

/code:antipatterns --focus security --severity high

Scans for anti-patterns using ast-grep structural matching:

  • Code smells
  • Security vulnerabilities
  • Performance issues
  • Maintainability problems

Refactoring

/code:refactor src/components/

Refactors code applying functional programming principles:

  • Pure functions (separate computation from side effects)
  • Immutability (transform data, don't mutate it)
  • Composition (build from small, focused functions)
  • Higher-order functions (map/filter/reduce over loops)
  • Explicit effects (push I/O to the boundary)

DRY Consolidation

/code:dry-consolidation src/components/

Finds and extracts duplicated code into shared abstractions:

  • Discovers clones deterministically with jscpd (token-based, 150+ languages) plus ast-grep shape confirmation, falling back to Grep when npx/jscpd is unavailable
  • Utility functions (string helpers, formatters, validators)
  • UI components (dialogs, pagination, error states)
  • Custom hooks (delete confirmation, form state, mutations)
  • Runs tests and verification after all extractions

Universal Linting

/code:lint --fix

Auto-detects project type and runs appropriate linters:

  • Biome/ESLint for JavaScript/TypeScript
  • Ruff for Python
  • Clippy for Rust

Documentation Quality Check

/code:docs-quality

Analyzes documentation quality and standards:

  • CLAUDE.md structure and completeness
  • .claude/rules/ organization
  • ADRs (Architecture Decision Records)
  • PRDs (Product Requirements Documents)
  • PRPs (Product Requirement Prompts)
  • Freshness and git history alignment
  • Generates comprehensive quality report with actionable recommendations

Hidden-Failure Scan

/code:hidden-failures src/

Detects code that fails without saying so, across two tracks:

errors (syntactic error suppression) — empty catch {}, || true, 2>/dev/null, floating promises, ignored Go/Rust results — across shell, JS/TS, Python, Go, and Rust. Recommends a surfacing channel based on detected app context (CLI stderr, web toast + console.error, structured log, Result propagation) and applies a privacy redaction policy to any generated user-facing strings. Use --emit-patch for a reviewable diff.

degradation (logical silent failure) — missing config causing features to skip without warning, success banners when nothing ran, multi-step operations that silently skip steps, missing precondition validation, degraded mode without notification. Use --fix to add precondition checks, warning messages, and status indicators.

/code:hidden-failures src/ --track errors --severity high
/code:hidden-failures src/ --track degradation --fix

Select a single track with --track errors|degradation (default both).

Dead Code Detection

/code:dead-code src/

Detects dead code across languages:

  • Unused exports and files (Knip for JS/TS)
  • Unused functions and variables (Vulture for Python)
  • Unused dependencies (cargo-machete for Rust)

Dependency Audit

/code:dep-audit --type all

Audits dependencies for:

  • Known CVEs and security vulnerabilities
  • Outdated packages
  • License compliance issues

Test Quality Analysis

/code:test-quality tests/

Analyzes test suite health:

  • Empty tests with no assertions
  • Weak/tautological assertions
  • Flaky patterns (setTimeout, hardcoded ports)
  • Missing edge case coverage

Complexity Analysis

/code:complexity src/ --threshold 10

Measures and reports:

  • Cyclomatic and cognitive complexity
  • Function length distribution
  • Nesting depth hotspots
  • File-level coupling indicators

ast-grep Patterns

The plugin includes ast-grep patterns for common issues:

# Find console.log statements
ast-grep -p 'console.log($$$)'

# Find empty catch blocks
ast-grep -p 'catch ($ERR) { }'

# Find TODO comments
ast-grep -p '// TODO: $MSG'

Configure Plugin Pairing

This plugin works reactively (analyze and fix). The configure-plugin works proactively (set up tooling). They complement each other:

code-quality-plugin (reactive)configure-plugin (proactive)
/code:lint — run linters/configure:linting — set up linters
/code:lint --fix — autofix lint issues/configure:formatting — set up formatters
/code:dead-code — find dead code/configure:dead-code — set up detection tools
/code:dep-audit — audit dependencies/configure:security — set up security scanning
/code:test-quality — analyze test quality/configure:tests + /configure:coverage — set up frameworks
/code:docs-quality — check doc quality/configure:docs — set up doc generators

Companion Plugins

Works well with:

  • configure-plugin - Proactive tool setup (see pairing table above)
  • testing-plugin - For test coverage analysis
  • git-plugin - For pre-commit quality checks
  • python-plugin / typescript-plugin - Language-specific linting

Installation

/plugin install code-quality-plugin@laurigates-claude-plugins

PostToolUse Pre-flight Cue

The plugin ships a PostToolUse behavioral cue hook (ADR-0017) that fires once per session when an Edit or Write touches a file with structural signals. When it fires, it feeds back a short reminder to run /code-quality-plugin:code-lint once the current edit sequence is complete — and, only when a skill file under a skills/ tree changed, to also run /evaluate-plugin:evaluate-skill.

The cue deliberately does not ask for a lint right now. A PostToolUse hook cannot tell edit 1 of 4 from a finished change, and linting a knowingly half-applied refactor produces actively-wrong findings — e.g. "inline is unused, rename to _inline" for a symbol whose four uses land three edits later (issue #2272).

Which layer covers which case. The rewording above is what addresses the scenario issue #2272 actually filed: edit 1 of a 4-edit sequence still fires, because the sequence debounce is backward-looking — it can only see edits that already happened, so it can never suppress the first edit of anything. Only the instruction changed, from "lint before continuing" to "lint once the sequence settles". The debounce's narrower job is to make sure the session's single cue lands on a settled edit instead of a mid-burst one.

Cue skill IDs are plugin-qualified

The cue is emitted at runtime and the agent pastes the slash command straight into the Skill tool, so every skill the cue names is written in the plugin-qualified form <plugin-name>:<skill-name> (/code-quality-plugin:code-lint, /evaluate-plugin:evaluate-skill) — never the /<ns>:<name> shorthand this repo's README tables use. There is no plugin named code-quality, so the short form returned Unknown skill: code-quality:code-lint and cost a tool call (issue #2682). The cue also names the action ("or this repo's own linter/formatter if that skill is unavailable") so it stays followable in a session where the plugin is not installed.

scripts/check-hook-cue-skill-refs.sh enforces this for every emitted line of this plugin's hooks and resolves each ID against the skills/agents on disk.

How it works

  • Fires on: Edit and Write tool completions
  • Structural signals (any one is enough to fire):
    • The diff contains a public-symbol line: export, export default, module.exports, pub, public, def, class, func — for shell scripts (.sh/.bash/.zsh), export is excluded since export FOO=bar is a builtin assignment, not a public-API symbol (issue #1766)
    • The edited file is a manifest: plugin.json, marketplace.json, package.json, Cargo.toml, pyproject.toml. An Edit whose old and new strings differ only in version tokens (a two- or three-part dotted number with an optional -prerelease tail; a bare number after ^, ~, <, >, ==, >=, <=, !=, ~= or "=; or a quoted number of at most three digits) does not count, so a pin or constraint bump such as =1.1.5 to =1.1.6, >=3.9 to >=3.12 or serde = "1" to "2" is silent, while "port": "3000" to "30001", --port=3000 to --port=30001 and "127.0.0.1" to "0.0.0.0" still fire (issues #3627, #3642)
    • The payload (new_string + content) is >= 50 lines
  • /evaluate-plugin:evaluate-skill reminder: appended only for paths under a skills/ tree, so the cue points at a real action rather than a no-op on ordinary code edits (issue #1766)
  • Silenced for: .md/.txt files, CHANGELOG.md, test/spec files (paths under test/, tests/, spec/ or __tests__/, absolute or relative; basenames test-*, test_*, *_test.*, *.test.*, *.spec.*), lockfiles, docs under docs/adrs/ or docs/prds/
  • Sequence debounce (issue #2272): the cue stays silent when another Edit/Write to the same file landed within the last CODE_QUALITY_PREFLIGHT_CUE_DEBOUNCE_TTL seconds (default 120) — a burst of edits to one file means a sequence is still in flight. A debounced edit does not consume the once-per-session budget, so the session's one cue lands on a settled edit rather than on the noisiest mid-burst one. Recency is recorded for every non-excluded Edit/Write (structural or not) in ~/.cache/code-quality-preflight-cue/.edits/<session_id>/<file-key>, and re-arms once the file goes quiet. Keying is session-scoped so concurrent sessions editing the same path never debounce each other.
    • Accepted true-positive loss: in a session that edits one file repeatedly at sub-TTL intervals and never returns to it after a quiet period, the cue can never fire for that file — every edit refreshes the recency marker, and PostToolUse only runs when an edit happens, so no invocation ever observes the quiet gap. Issue #2272's shape (1) takes this trade knowingly.
    • Cache hygiene: the debounce writes one marker per (session, file touched) plus a directory per session, so a sweep prunes markers untouched for CODE_QUALITY_PREFLIGHT_CUE_MARKER_TTL minutes (default 1440) and the emptied session directories. A .last-sweep sentinel gates it to at most hourly, so the hot path costs one find on the sentinel (~3ms) rather than the three prune passes. CODE_QUALITY_PREFLIGHT_CUE_MARKER_TTL=0 is rejected rather than honoured — unlike …_DEBOUNCE_TTL, where 0 disables, 0 here would mean "prune anything a minute old" and disarm live debounces, so it falls back to the default.
  • Once per session: after firing, a marker file under ~/.cache/code-quality-preflight-cue/<session_id> prevents re-firing in the same session
  • ADR-0017 compliance: uses {"decision":"block","reason":"..."} with continueOnBlock: true — the reason is fed back to the model and the turn continues

Bypass

Set CODE_QUALITY_SKIP_HOOKS=1 in your environment to disable the hook entirely for that session.

Tuning and test seams

VariableDefaultEffect
CODE_QUALITY_SKIP_HOOKSunset1 disables the hook entirely
CODE_QUALITY_PREFLIGHT_CUE_CACHE_DIR~/.cache/code-quality-preflight-cueRedirects both the session dedup marker and the .edits/ recency markers (used by the regression tests under hooks/test-code-quality-preflight-cue.sh)
CODE_QUALITY_PREFLIGHT_CUE_DEBOUNCE_TTL120 (seconds)Sequence-debounce window. 0 disables the debounce, restoring per-edit evaluation. A non-numeric value falls back to the default
CODE_QUALITY_PREFLIGHT_CUE_MARKER_TTL1440 (minutes)Age at which a .edits/ recency marker is swept. A non-numeric value falls back to the default

Both suppression layers fail open, and so does the cache-path resolution: a broken clock, an unwritable cache dir, or an unset HOME (which falls back to ${TMPDIR:-/tmp}) lets the cue fire rather than silencing it or aborting the tool call. Regression tests (o) and (p) in hooks/test-code-quality-preflight-cue.sh pin the HOME-unset and sweep behaviours.

License

MIT

Details

Marketplace
laurigates/claude-plugins
Source
code-quality-plugin
Author
Lauri Gates
Category
Quality
License
MIT
Keywords
code-review, refactoring, linting, analysis, dead-code, dependency-audit, test-quality, complexity
Listed since
Apr 7, 2026

More from laurigates/claude-plugins

All 52

Similar to code-quality-plugin

More Code Review & Quality