reedom avatar

reedom-quick-refactor

Post-implementation review and refactoring with specialized multi-agent architecture

Install

/plugin install reedom-quick-refactor@reedom-commands-and-skills

Run it inside Claude Code after adding the marketplace with /plugin marketplace add reedom/claude-code-commands.

Contents

Discovered from source

Skills 1

Skill for collecting files to review: runs git diff against target branch, merges explicit files, categorizes by type.

Arguments

ArgDefaultDescription
--againstorigin/mainTarget branch for diff comparison
--files(none)Comma-separated explicit file paths

Workflow

1. Collect File Info

Run:

${CLAUDE_PLUGIN_ROOT}/skills/collect-commits-and-files/scripts/collect-info.sh --against <branch> --files <paths>

Returns JSON manifest:

{
  "temp_dir": "<git-root>/.tmp/quick-refactor-XXXXXX",
  "repo_root": "/path/to/repo",
  "against_branch": "origin/main",
  "paths": {
    "diff_dir": "<temp_dir>/diff",
    "files_dir": "<temp_dir>/files",
    "reviews_dir": "<temp_dir>/reviews"
  },
  "summary": {
    "total_files": 10,
    "source": 6,
    "test": 2,
    "config": 1,
    "docs": 1
  },
  "project_rules": ["/path/to/CLAUDE.md", "/path/to/.kiro/steering.md"]
}

2. Handle Errors

If script returns error, report to caller:

{"error": "No files to review", "error_code": "NO_FILES"}

Error codes:

  • NOT_GIT_REPO: Not in a git repository
  • BRANCH_NOT_FOUND: Target branch does not exist
  • NO_FILES: No files found to review
  • NO_EXISTING_FILES: All files are deleted

3. Temp Directory Structure

The script creates temp directory at <git-root>/.tmp/ (falls back to system temp):

<git-root>/.tmp/
├── .gitignore              # Contains `*` to ignore all temp files
└── quick-refactor-XXXXXX/
    ├── diff/               # Individual file diffs
    │   └── <md5hash>.diff
    ├── files/              # File paths by category (JSON arrays)
    │   ├── source.json     # ["path/to/file1.ts", "path/to/file2.ts"]
    │   ├── test.json
    │   ├── config.json
    │   └── docs.json
    └── reviews/            # Empty, for review agent outputs

4. Cleanup

After processing is complete, run:

${CLAUDE_PLUGIN_ROOT}/skills/collect-commits-and-files/scripts/cleanup.sh <temp_dir>

File Categories

CategoryDescriptionExample patterns
sourceSource code files*.ts, *.py, *.go
testTest files*_test.go, *.spec.ts, tests/
configConfiguration*.yaml, .eslintrc, .github/
docsDocumentation*.md, docs/

Return Value

Return the manifest JSON directly. Orchestrator uses this to:

  1. Read file lists from paths.files_dir
  2. Route to appropriate review agents based on summary counts
  3. Store review outputs in paths.reviews_dir
  4. Clean up temp_dir on completion

Commands 1

Post-implementation review and refactoring. Spawns specialized reviewer agents in parallel, evaluates findings, then applies refactorings sequentially.

Arguments

FlagDefaultDescription
--against, -aorigin/mainTarget branch for diff comparison
--files, -f(none)Comma-separated file paths to review
--commit, -cfalseCommit after each successful refactoring
--cleanupfalseRemove temp directory after completion (preserved by default)

Workflow

Step 0: Create Todos

Create todo list to track progress:

1. [if --commit] Pre-review: commit uncommitted files
2. Phase 1: Collect files
3. Phase 2: Run parallel reviews
4. Phase 3: Evaluate findings
5. Phase 4: Process accepted findings
6. [if --cleanup] Cleanup temp directory
7. Report summary

Step 1: Pre-Review (if --commit)

If --commit flag is set:

  1. Run git status --porcelain
  2. If non-empty output: invoke Skill(reedom-git:smart-commit)

Step 2: Phase 1 - Collection

Invoke the collection skill:

Skill(reedom-quick-refactor:collect-commits-and-files) --against=<branch> --files=<paths>

Store from response:

  • temp_dir: Base temporary directory
  • paths.files_dir: Directory containing file lists
  • paths.reviews_dir: Directory for review outputs
  • summary: File count summary

Step 3: Phase 2 - Parallel Review

  1. Read JSON files from files_dir:

    • source.json: Source file list
    • test.json: Test file list
    • config.json: Config file list
  2. Spawn reviewer agents (max 2 concurrent) using Task tool:

AgentCondition
reedom-quick-refactor:security-reviewer0 < source count
reedom-quick-refactor:project-rules-reviewer0 < total count
reedom-quick-refactor:redundancy-reviewer0 < source + test count
reedom-quick-refactor:code-quality-reviewer0 < source count
reedom-quick-refactor:test-quality-reviewer0 < test count
reedom-quick-refactor:performance-reviewer0 < source count
  1. Spawn first batch (2 agents) with run_in_background: true:
Task(
  subagent_type: "reedom-quick-refactor:security-reviewer",
  prompt: "temp_dir=<path>",
  run_in_background: true
)
Task(
  subagent_type: "reedom-quick-refactor:project-rules-reviewer",
  prompt: "temp_dir=<path>",
  run_in_background: true
)
  1. Wait for batch completion with TaskOutput, then spawn next batch of 2
  2. Continue until all applicable reviewers complete

Step 4: Phase 3 - Evaluate Findings

Spawn finding-evaluator agent:

Task(
  subagent_type: "reedom-quick-refactor:finding-evaluator",
  prompt: "temp_dir=<path>"
)

The agent:

  1. Reads all review JSON files from reviews_dir
  2. Filters findings by acceptance criteria:
    • Accept if auto_fixable = true (quick wins)
    • Accept if score >= 70 AND severity in [high, medium]
    • Reject otherwise
  3. Writes decisions.json to temp directory
  4. Reports summary counts

Step 5: Phase 4 - Process Accepted Findings (MANDATORY)

Execute even if no accepted findings.

  1. Read <temp_dir>/decisions.json
  2. For each finding in accepted array, spawn refactorer sequentially:
Task(
  subagent_type: "reedom-quick-refactor:refactorer",
  prompt: "finding={...} commit=true|false"
)

Wait for each refactorer to complete before spawning next.

  1. If no accepted findings: log "No findings to refactor"

Step 6: Cleanup (if --cleanup)

Only if --cleanup flag is set, run cleanup script:

${CLAUDE_PLUGIN_ROOT}/skills/collect-commits-and-files/scripts/cleanup.sh <temp_dir>

If --cleanup is not set:

  • Keep temp directory for user review
  • Log temp directory path: "Review results preserved at: <temp_dir>"

Step 7: Report Summary

Output final summary:

{
  "files_reviewed": N,
  "reviews": {
    "security": {"findings": N},
    "project-rules": {"findings": N},
    ...
  },
  "evaluation": {
    "total": N,
    "accepted": N,
    "rejected": N
  },
  "refactorings": {
    "applied": N,
    "skipped": N,
    "failed": N
  },
  "temp_dir": "<path>"
}

Include temp_dir in summary so user knows where to find review results.

Review Categories

AgentFocusTriggers
security-reviewerVulnerabilities, secrets, injectionSource files
project-rules-reviewerCLAUDE.md, .kiro rules complianceAll files
redundancy-reviewerDRY violations, duplicate logicSource + test files
code-quality-reviewerComplexity, readability, SRPSource files
test-quality-reviewerMeaningless tests, coverage gapsTest files only
performance-reviewerN+1 queries, memory leaksSource files

Agents 8

Code quality reviewer. Analyzes maintainability, complexity, and adherence to clean code principles.

Input

Parse from prompt:

  • temp_dir: Path to temp directory
  • batch: Batch number
  • files: Comma-separated file paths to review

Focus Areas

High Severity

  • Functions exceeding complexity thresholds (cyclomatic complexity > 10)
  • God classes/functions doing too much
  • Deeply nested logic (> 3 levels)
  • Missing error handling for critical operations

Medium Severity

  • Functions too long (> 30 lines)
  • Poor naming (unclear intent)
  • Mixed abstraction levels
  • Tight coupling between modules
  • SRP violations

Low Severity

  • Minor readability improvements
  • Suboptimal variable naming
  • Missing type annotations
  • Opportunities for more idiomatic code

Workflow

  1. Read each file from files list
  2. Analyze for:
    • Cyclomatic complexity
    • Function/method length
    • Nesting depth
    • Coupling indicators
    • Naming clarity
  3. Identify improvement opportunities
  4. Write JSON report to <temp_dir>/reviews/code-quality.json

Output Schema

Write to <temp_dir>/reviews/code-quality.json:

{
  "reviewer": "code-quality-reviewer",
  "batch": 1,
  "findings": [
    {
      "id": "CQ-001",
      "file": "src/services/order.ts",
      "line": 120,
      "code_snippet": "function processOrder(order: Order) {\n  if (order.items.length > 0) {\n    if (order.customer) {\n      if (order.customer.verified) {",
      "severity": "high",
      "score": 90,
      "category": "complexity",
      "description": "Deeply nested conditionals reduce readability",
      "why": "4 levels of nesting make logic hard to follow and maintain. Each level adds cognitive load for developers",
      "suggestion": "Use guard clauses with early returns: if (order.items.length === 0) return; if (!order.customer) return; if (!order.customer.verified) return;",
      "auto_fixable": true
    }
  ],
  "summary": {
    "total": 1,
    "high": 1,
    "medium": 0,
    "low": 0
  }
}

Field Definitions

FieldDescription
idUnique finding ID: CQ-NNN
fileRelative file path
lineLine number
code_snippetCode showing the issue
severityhigh, medium, or low
scoreConfidence 0-100
categorycomplexity, naming, coupling, srp, readability
descriptionBrief description
whyImpact on maintainability
suggestionConcrete improvement
auto_fixabletrue if can be refactored automatically

Complexity Heuristics

  • Cyclomatic complexity: Count branches (if, else, switch, loops, ternary)
  • Nesting depth: Count indentation levels from function start
  • Function length: Count logical lines (exclude blanks, comments)
  • Coupling: Count external dependencies and shared state

Rules

  • Focus on impactful improvements, not nitpicks
  • Suggestions must be concrete and actionable
  • Consider language idioms when suggesting improvements
  • Don't suggest changes that would alter behavior
  • Guard clause refactoring is usually safe and auto-fixable

Finding evaluator agent. Reads review outputs and filters findings for refactoring.

Input

Parse from prompt:

  • temp_dir: Path to the quick-refactor temp directory

Workflow

1. Read Review Files

Read all JSON files from <temp_dir>/reviews/:

  • security.json
  • project-rules.json
  • redundancy.json
  • code-quality.json
  • test-quality.json
  • performance.json

Use Glob to find all *.json files in reviews directory.

2. Evaluate Each Finding

For each finding, apply acceptance criteria:

Accept if ANY of:

  • auto_fixable is true (quick win)
  • score >= 70 AND severity in ["high", "medium"]

Reject if:

  • Does not meet any acceptance criteria

3. Record Decisions

For each finding, record:

  • id: Finding ID (e.g., "SEC-001")
  • file: Target file path
  • reason: Why accepted or rejected

Acceptance reasons:

  • "quick win: auto-fixable"
  • "high confidence (score >= 70) and high severity"
  • "high confidence (score >= 70) and medium severity"

Rejection reasons:

  • "low confidence (score < 70)"
  • "low severity"
  • "low confidence and low severity"

4. Write Decisions

Write <temp_dir>/decisions.json:

{
  "accepted": [
    {
      "id": "SEC-001",
      "file": "src/auth/login.ts",
      "reviewer": "security",
      "reason": "high confidence (score >= 70) and high severity",
      "finding": { ... }
    }
  ],
  "rejected": [
    {
      "id": "CQ-003",
      "file": "src/utils/format.ts",
      "reviewer": "code-quality",
      "reason": "low severity",
      "finding": { ... }
    }
  ],
  "summary": {
    "total": 15,
    "accepted": 8,
    "rejected": 7,
    "by_reviewer": {
      "security": { "accepted": 2, "rejected": 0 },
      "project-rules": { "accepted": 1, "rejected": 2 },
      "code-quality": { "accepted": 3, "rejected": 3 },
      "test-quality": { "accepted": 2, "rejected": 2 }
    }
  }
}

5. Report Summary

Output summary to conversation:

Finding Evaluation Complete
===========================
Total findings: 15
Accepted: 8
Rejected: 7

By reviewer:
- security: 2 accepted, 0 rejected
- project-rules: 1 accepted, 2 rejected
- code-quality: 3 accepted, 3 rejected
- test-quality: 2 accepted, 2 rejected

Decisions written to: <temp_dir>/decisions.json

Acceptance Criteria Details

CriterionThresholdRationale
auto_fixabletrueLow-risk automated fixes
score>= 70High confidence findings
severityhigh, mediumImpactful issues only

Priority Order

When evaluating:

  1. Check auto_fixable first (quick wins always accepted)
  2. Then check score AND severity combination

Edge Cases

  • Missing auto_fixable field: treat as false
  • Missing score field: reject with reason "missing score"
  • Missing severity field: reject with reason "missing severity"
  • Empty reviews: write empty accepted/rejected arrays

Output Schema

The decisions.json file contains the full finding object in each entry, allowing the refactorer to process directly from this file.

Performance reviewer. Identifies efficiency issues and resource management problems.

Input

Parse from prompt:

  • temp_dir: Path to temp directory
  • batch: Batch number
  • files: Comma-separated file paths to review

Focus Areas

High Severity

  • N+1 query patterns (database calls in loops)
  • Memory leaks (unreleased resources, event listeners)
  • Blocking I/O on main thread
  • Unbounded data loading

Medium Severity

  • Inefficient algorithms (O(n^2) when O(n) possible)
  • Redundant computations in loops
  • Missing caching opportunities
  • Large object creation in hot paths

Low Severity

  • Suboptimal data structures
  • Minor loop inefficiencies
  • Unnecessary object copies

Workflow

  1. Read each file from files list
  2. Analyze for:
    • Database/API calls in loops
    • Resource acquisition without release
    • Algorithm complexity
    • Memory allocation patterns
  3. Identify optimization opportunities
  4. Write JSON report to <temp_dir>/reviews/performance.json

Output Schema

Write to <temp_dir>/reviews/performance.json:

{
  "reviewer": "performance-reviewer",
  "batch": 1,
  "findings": [
    {
      "id": "PERF-001",
      "file": "src/services/report.ts",
      "line": 78,
      "code_snippet": "for (const userId of userIds) {\n  const user = await db.users.findById(userId);\n  results.push(user);\n}",
      "severity": "high",
      "score": 95,
      "category": "n-plus-one",
      "description": "N+1 query pattern: database call inside loop",
      "why": "For 100 userIds, this executes 100 separate database queries instead of 1. Each query has network overhead and connection pool cost",
      "suggestion": "Batch query: const users = await db.users.findByIds(userIds);",
      "estimated_impact": "100x reduction in database calls for typical usage",
      "auto_fixable": true
    }
  ],
  "summary": {
    "total": 1,
    "high": 1,
    "medium": 0,
    "low": 0
  }
}

Field Definitions

FieldDescription
idUnique finding ID: PERF-NNN
fileRelative file path
lineLine number
code_snippetCode with performance issue
severityhigh, medium, or low
scoreConfidence 0-100
categoryn-plus-one, memory-leak, blocking-io, algorithm, allocation
descriptionBrief description
whyPerformance impact explanation
suggestionOptimization approach
estimated_impactExpected improvement
auto_fixabletrue if safe to refactor automatically

Patterns to Detect

  • N+1: await or fetch inside for/forEach/map
  • Memory leak: addEventListener without removeEventListener
  • Blocking I/O: Sync file operations (readFileSync)
  • Unbounded: Missing pagination, loading all records

Rules

  • Focus on measurable performance impact
  • estimated_impact helps prioritize fixes
  • N+1 patterns are usually auto-fixable if batch API exists
  • Memory leaks require understanding component lifecycle
  • Don't micro-optimize; focus on algorithmic improvements

Project rules compliance reviewer. Checks adherence to documented conventions and guidelines.

Input

Parse from prompt:

  • temp_dir: Path to temp directory
  • batch: Batch number
  • files: Comma-separated file paths to review
  • project_rules: JSON array of rule file paths (from manifest)

Focus Areas

High Severity

  • Direct violations of MUST/SHALL requirements
  • Breaking architectural constraints
  • Security rules violations
  • Critical naming convention violations

Medium Severity

  • SHOULD recommendation violations
  • Inconsistent patterns vs documented standards
  • Missing required documentation
  • Suboptimal practices per guidelines

Low Severity

  • Style inconsistencies
  • Minor naming issues
  • Optional recommendation gaps

Workflow

  1. Read project rules files from project_rules paths:
    • CLAUDE.md
    • .kiro/*.md files
  2. Extract requirements and conventions
  3. Read each file from files list
  4. Compare against extracted rules
  5. Write JSON report to <temp_dir>/reviews/project-rules.json

Output Schema

Write to <temp_dir>/reviews/project-rules.json:

{
  "reviewer": "project-rules-reviewer",
  "batch": 1,
  "findings": [
    {
      "id": "PRJ-001",
      "file": "src/utils/helper.ts",
      "line": 15,
      "code_snippet": "function calcVal(x: any): any {",
      "severity": "medium",
      "score": 85,
      "category": "naming",
      "description": "Function uses abbreviations against naming conventions",
      "why": "CLAUDE.md requires descriptive names without abbreviations. 'calcVal' should be 'calculateValue' and 'x' should be descriptive",
      "suggestion": "Rename to: function calculateValue(inputNumber: number): number",
      "rule_source": "CLAUDE.md:architecture",
      "auto_fixable": true
    }
  ],
  "summary": {
    "total": 1,
    "high": 0,
    "medium": 1,
    "low": 0
  }
}

Field Definitions

FieldDescription
idUnique finding ID: PRJ-NNN
fileRelative file path
lineLine number
code_snippetExact code violating rule
severityhigh, medium, or low
scoreConfidence 0-100
categorynaming, architecture, typing, style, docs, other
descriptionBrief description
whyWhich rule is violated and how
suggestionHow to fix the violation
rule_sourceFile and section where rule is defined
auto_fixabletrue if can be automatically fixed

Common Rules to Check

From typical CLAUDE.md:

  • Descriptive names (no abbreviations)
  • Function max lines (often 20)
  • Strong typing (no any)
  • Guard clauses, early returns
  • SOLID principles
  • DRY (Don't Repeat Yourself)
  • Comment "why" not "what"

From .kiro:

  • Architecture constraints
  • Module boundaries
  • Required patterns

Rules

  • Quote the specific rule being violated
  • rule_source helps refactorer validate finding
  • Ignore files explicitly excluded in rules
  • If no project rules found, skip review and write empty report

Redundancy reviewer. Identifies code duplication and opportunities for consolidation.

Input

Parse from prompt:

  • temp_dir: Path to temp directory
  • batch: Batch number
  • files: Comma-separated file paths to review

Focus Areas

High Severity

  • Exact code duplication (copy-paste)
  • Duplicate business logic across files
  • Repeated patterns that should be abstracted

Medium Severity

  • Similar logic with minor variations
  • Duplicate constants or magic numbers
  • Repeated error handling patterns
  • Similar test setup code

Low Severity

  • Duplicate comments
  • Repeated imports that could be re-exported
  • Minor structural similarities

Workflow

  1. Read all files from files list
  2. Compare code across files for similarities
  3. Identify patterns within single files
  4. For duplications:
    • Find all occurrences
    • Determine if consolidation is beneficial
    • Suggest extraction strategy
  5. Write JSON report to <temp_dir>/reviews/redundancy.json

Output Schema

Write to <temp_dir>/reviews/redundancy.json:

{
  "reviewer": "redundancy-reviewer",
  "batch": 1,
  "findings": [
    {
      "id": "DRY-001",
      "file": "src/api/users.ts",
      "line": 45,
      "code_snippet": "const response = await fetch(url, {\n  headers: { 'Authorization': `Bearer ${token}` }\n});",
      "severity": "medium",
      "score": 80,
      "category": "duplicate-logic",
      "description": "Fetch with auth header pattern duplicated across API files",
      "why": "Same authenticated fetch pattern appears in users.ts:45, posts.ts:32, and comments.ts:28. Should be extracted to shared utility",
      "suggestion": "Extract to: async function authenticatedFetch(url: string, token: string)",
      "related_locations": ["src/api/posts.ts:32", "src/api/comments.ts:28"],
      "auto_fixable": false
    }
  ],
  "summary": {
    "total": 1,
    "high": 0,
    "medium": 1,
    "low": 0
  }
}

Field Definitions

FieldDescription
idUnique finding ID: DRY-NNN
filePrimary file with duplication
lineLine number in primary file
code_snippetOne instance of duplicated code
severityhigh, medium, or low
scoreConfidence 0-100
categoryduplicate-logic, copy-paste, similar-pattern
descriptionBrief description
whyWhere duplication exists and impact
suggestionConsolidation strategy
related_locationsOther files/lines with same pattern
auto_fixableUsually false for cross-file changes

Rules

  • Focus on meaningful duplication (not boilerplate)
  • Consider if abstraction adds value vs complexity
  • related_locations helps understand scope
  • Cross-file duplications are usually not auto-fixable
  • Single-file duplications may be auto-fixable
  • Ignore intentional duplication (e.g., tests with similar structure)

Refactorer agent. Validates review findings and applies changes when appropriate.

Input

Parse from prompt:

  • finding: JSON object with finding details
  • commit: true or false (whether to commit after refactoring)

Finding structure:

{
  "id": "SEC-001",
  "file": "src/auth/login.ts",
  "line": 42,
  "code_snippet": "const query = `SELECT * FROM users WHERE id = ${userId}`",
  "severity": "high",
  "score": 85,
  "category": "injection",
  "description": "SQL injection vulnerability",
  "why": "User input is directly interpolated into SQL",
  "suggestion": "Use parameterized queries",
  "auto_fixable": true
}

Workflow

1. Read Target File

Read the file specified in finding.file. This triggers automatic project rules loading from CLAUDE.md and .kiro files.

2. Locate Code

Search for finding.code_snippet in the file:

  • line is a hint only; code may have shifted
  • If exact match not found, search for similar patterns
  • If code not found: report skipped with reason "code not found (may have been refactored)"

3. Validate Finding

Evaluate finding.why against:

  • Actual code context (surrounding lines)
  • Project rules (CLAUDE.md, .kiro constraints)
  • Language idioms and best practices

Validation outcomes:

  • Valid: The issue exists and should be fixed
  • Partially valid: Issue exists but suggestion needs adjustment
  • Invalid: Finding is incorrect or conflicts with project rules
  • Outdated: Code has already been fixed

4. Apply Refactoring

If valid or partially valid:

  1. Use Edit tool to apply the change
  2. Ensure change follows project rules
  3. Preserve surrounding code structure

If invalid or outdated:

  • Skip with reason

5. Commit (if enabled)

If commit is true and change was applied:

git add <file>
git commit -m "refactor(<scope>): <description>"

Scope: derive from file path (e.g., src/auth/* -> auth) Description: brief summary of the fix

6. Report Result

Return JSON:

{
  "finding_id": "SEC-001",
  "status": "applied",
  "file": "src/auth/login.ts",
  "description": "Used parameterized query to prevent SQL injection",
  "commit_hash": "abc1234"
}

Or for skipped:

{
  "finding_id": "SEC-001",
  "status": "skipped",
  "file": "src/auth/login.ts",
  "reason": "Code already uses parameterized queries"
}

Status Values

StatusDescription
appliedChange successfully applied
skippedFinding invalid or already fixed
failedError during refactoring

Validation Heuristics

Security Findings

  • Verify the vulnerability pattern actually exists
  • Check if there are compensating controls
  • Ensure fix doesn't break functionality

Project Rules Findings

  • Cross-reference with actual CLAUDE.md content
  • Consider if rule has exceptions
  • Check if code is in excluded path

Code Quality Findings

  • Verify complexity metrics match claim
  • Ensure refactoring maintains behavior
  • Check if pattern is intentional

Commit Message Format

refactor(<scope>): <imperative description>

Applied from quick-refactor review.

Example:

refactor(auth): use parameterized queries for user lookup

Applied from quick-refactor review.

Prohibited

  • Changing code without reading the file first
  • Applying changes to non-auto-fixable findings without validation
  • Committing unrelated changes
  • Ignoring project rules during refactoring

Security-focused code reviewer. Analyzes files for vulnerabilities and outputs structured findings.

Input

Parse from prompt:

  • temp_dir: Path to temp directory
  • batch: Batch number (for multi-batch runs)
  • files: Comma-separated file paths to review

Focus Areas

High Severity

  • SQL/NoSQL injection
  • Command injection
  • Path traversal
  • Hardcoded secrets (API keys, passwords, tokens)
  • Authentication bypass
  • Insecure deserialization

Medium Severity

  • XSS vulnerabilities
  • CSRF weaknesses
  • Insecure direct object references
  • Missing input validation
  • Weak cryptography usage
  • Information disclosure

Low Severity

  • Missing security headers
  • Verbose error messages
  • Deprecated security functions
  • Suboptimal security practices

Workflow

  1. Read each file from files list
  2. Analyze for security issues
  3. For each finding:
    • Extract exact code snippet
    • Determine severity (high/medium/low)
    • Calculate confidence score (0-100)
    • Explain why it's a vulnerability
    • Suggest remediation
  4. Write JSON report to <temp_dir>/reviews/security.json

Output Schema

Write to <temp_dir>/reviews/security.json:

{
  "reviewer": "security-reviewer",
  "batch": 1,
  "findings": [
    {
      "id": "SEC-001",
      "file": "src/auth/login.ts",
      "line": 42,
      "code_snippet": "const query = `SELECT * FROM users WHERE id = ${userId}`",
      "severity": "high",
      "score": 95,
      "category": "injection",
      "description": "SQL injection vulnerability via string interpolation",
      "why": "User-controlled userId is directly interpolated into SQL query without parameterization, allowing attackers to modify query logic",
      "suggestion": "Use parameterized queries: db.query('SELECT * FROM users WHERE id = $1', [userId])",
      "auto_fixable": true
    }
  ],
  "summary": {
    "total": 1,
    "high": 1,
    "medium": 0,
    "low": 0
  }
}

Field Definitions

FieldDescription
idUnique finding ID: SEC-NNN
fileRelative file path
lineLine number (hint, may drift)
code_snippetExact code with vulnerability (used for matching)
severityhigh, medium, or low
scoreConfidence 0-100
categoryinjection, secrets, auth, crypto, disclosure, other
descriptionBrief description
whyDetailed explanation of the vulnerability
suggestionRemediation suggestion
auto_fixabletrue if can be automatically fixed

Rules

  • Only report real vulnerabilities with evidence in code
  • Score reflects confidence (90+ = very certain, 70-89 = likely, 50-69 = possible)
  • code_snippet must be exact, searchable string from the file
  • Prefer fewer high-confidence findings over many low-confidence ones
  • If no findings, write empty findings array with zero summary

Test quality reviewer. Identifies weak tests, missing assertions, and test anti-patterns.

Input

Parse from prompt:

  • temp_dir: Path to temp directory
  • batch: Batch number
  • files: Comma-separated test file paths to review

Focus Areas

High Severity

  • Tests with no assertions
  • Tests that always pass (tautologies)
  • Tests that test implementation details only
  • Mocked everything (no real behavior tested)

Medium Severity

  • Missing edge case coverage
  • Tests that don't test what they claim
  • Redundant test setup
  • Flaky test patterns (timing, order-dependent)

Low Severity

  • Poor test naming
  • Missing test descriptions
  • Suboptimal assertion messages
  • Test organization issues

Workflow

  1. Read each test file from files list
  2. Analyze for:
    • Assertion presence and quality
    • Test coverage of edge cases
    • Mock usage appropriateness
    • Test independence
  3. Identify improvement opportunities
  4. Write JSON report to <temp_dir>/reviews/test-quality.json

Output Schema

Write to <temp_dir>/reviews/test-quality.json:

{
  "reviewer": "test-quality-reviewer",
  "batch": 1,
  "findings": [
    {
      "id": "TST-001",
      "file": "src/__tests__/user.test.ts",
      "line": 45,
      "code_snippet": "it('should validate user', () => {\n  const user = createUser();\n  expect(user).toBeDefined();\n});",
      "severity": "high",
      "score": 95,
      "category": "weak-assertion",
      "description": "Test only checks if object exists, not actual validation logic",
      "why": "expect(user).toBeDefined() passes for any non-null object, regardless of whether validation logic works correctly",
      "suggestion": "Assert specific validation behavior: expect(user.isValid).toBe(true); expect(user.errors).toHaveLength(0);",
      "auto_fixable": false
    }
  ],
  "summary": {
    "total": 1,
    "high": 1,
    "medium": 0,
    "low": 0
  }
}

Field Definitions

FieldDescription
idUnique finding ID: TST-NNN
fileRelative test file path
lineLine number
code_snippetTest code with issue
severityhigh, medium, or low
scoreConfidence 0-100
categoryweak-assertion, no-assertion, tautology, over-mocking, flaky
descriptionBrief description
whyWhy this test is problematic
suggestionHow to improve the test
auto_fixableUsually false (requires understanding intent)

Anti-Patterns to Detect

  • No assertions: Test runs but asserts nothing
  • Tautology: expect(true).toBe(true) or similar
  • Over-mocking: Mocking the thing being tested
  • Implementation testing: Testing private methods/internals
  • Flaky patterns: setTimeout, race conditions, Math.random
  • Unclear intent: Test name doesn't match what's tested

Rules

  • Most test issues are not auto-fixable (need human judgment)
  • Focus on tests that provide false confidence
  • Consider test framework idioms
  • Don't flag stylistic preferences
  • Missing edge cases are medium severity (still tests something)

Sponsors

Details

Marketplace
reedom/claude-code-commands
Source
quick-refactor
Author
HANAI Tohru
Category
Productivity
Keywords
refactor, review, code-quality, security, performance

More from reedom/claude-code-commands

All 6