Skip to content
Development
Command

/refactor

Unified code, docs, and test optimization -- shape analysis, waste detection, dead code, doc redundancy

From plugin
autonomous-dev
3226 skills16 agents26 commands1 MCP
Install
$ npx -y skills add akaszubski/autonomous-dev --agent claude-code

How it fires

How this command gets triggered: by you, by Claude, or both.

  • Fires itselfClaude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/refactor

Context preview

What this command does when you run it.

Unified code, docs, and test optimization -- shape analysis, waste detection, dead code, doc redundancy

Command definition

refactor.md
name: refactor
description: "Unified code, docs, and test optimization -- shape analysis, waste detection, dead code, doc redundancy"
argument-hint: "[--tests] [--docs] [--code] [--fix] [--quick] [--deep] [--issues] [--batch]"
user-invocable: true
user_facing: true
allowed-tools: [Read, Bash, Grep, Glob, Agent]

Refactor: Unified Code, Docs, and Test Optimization

Deep analysis and optimization of tests (Quality Diamond shape, waste detection), docs (redundancy), and code (dead code, unused libs). Supersedes `/sweep` with deeper analysis. Use `--quick` for the original sweep-style hygiene check.

Implementation

ARGUMENTS: {{ARGUMENTS}}

STEP 0: Parse Arguments

Parse the ARGUMENTS for optional flags:

  • `--tests`: Run test optimization analysis only (shape + waste)
  • `--docs`: Run narrative-doc drift sweep across whole repo. Identifies count drift (e.g., '216 libraries' vs actual 219 files) and enumeration drift via `covers:` frontmatter dereferencing. Idempotent. Default home for periodic-aggregation per PROJECT.md Layer 4.
  • `--docs-redundancy`: Run doc redundancy analysis (semantic similarity between markdown files via SequenceMatcher). This was the prior `--docs` behavior, renamed to free `--docs` for drift detection.
  • `--code`: Run code optimization analysis only (dead code + unused libs)
  • `--fix`: Apply automated fixes after detection (requires findings)
  • `--quick`: Run quick hygiene sweep (delegates to SweepAnalyzer, same as old `/sweep`)
  • `--deep`: Enable GenAI semantic analysis (requires ANTHROPIC_API_KEY). Auto-enabled when ANTHROPIC_API_KEY is set, unless --quick.
  • `--issues`: Pipe findings through /create-issue (HIGH/CRITICAL get individual issues, LOW/MEDIUM aggregated into one)
  • `--batch`: Submit GenAI analysis via Anthropic Batch API (50% cost, async results)

If no mode flags provided (no --tests, --docs, --docs-redundancy, --code, --quick), run **all three deep modes** (tests + docs + code).

**Usage examples:**

/refactor --docs               # Drift sweep: count + enumeration drift via covers: frontmatter
/refactor --docs-redundancy    # Prior --docs behavior: SequenceMatcher redundancy analysis
/refactor --docs --issues      # Drift sweep + file GitHub issues for findings
/refactor --docs-redundancy --fix  # Redundancy analysis with auto-fix applied

If `--fix` is not provided, this is a dry-run (detect only, no changes).

**Note**: `--fix` is deprecated for creating issues. Use `--issues` instead to generate GitHub issues from findings.

STEP 1: Run Analysis

Execute the appropriate analyzer to detect optimization opportunities. If `--deep` is set, or ANTHROPIC_API_KEY is set and `--quick` is NOT set, use GenAIRefactorAnalyzer. If `--deep` is set with no API key, display an error and EXIT. Otherwise fall back to RefactorAnalyzer.

python3 -c "
import sys, json, os
for _p in ('.claude/lib', 'plugins/autonomous-dev/lib', os.path.expanduser('~/.claude/lib')):
    if os.path.isdir(_p):
        sys.path.insert(0, _p)
        break
from pathlib import Path

# Determine whether to use GenAI
use_deep = '--deep' in sys.argv or (os.environ.get('ANTHROPIC_API_KEY') and '--quick' not in sys.argv)

if use_deep:
    from genai_refactor_analyzer import GenAIRefactorAnalyzer
    analyzer = GenAIRefactorAnalyzer(Path('.'), use_batch_api='--batch' in sys.argv)
else:
    from refactor_analyzer import RefactorAnalyzer
    analyzer = RefactorAnalyzer(Path('.'))

# Determine mode based on parsed flags
# For --quick: use quick_sweep() (RefactorAnalyzer only)
# For specific modes: use full_analysis(['tests']), etc.
# For no flags: use full_analysis() (all modes)

# Example for --quick:
# report = analyzer.quick_sweep()

# Example for specific mode:
# report = analyzer.full_analysis(['tests'])

# Example for all modes (with GenAI):
# report = analyzer.full_analysis(deep=True)

print(json.dumps(report.to_dict()))
"

Capture the JSON output and parse it.

STEP 1.5: Findings Self-Critique (--deep mode only)

**Skip if `--quick` mode or if `--deep` was not active.** This step applies only when GenAIRefactorAnalyzer was used.

After obtaining the raw findings from STEP 1, perform one FEEDBACK pass before presenting results to the user. This implements the Self-Refine pattern (GENERATE → FEEDBACK → REFINE).

Audit the findings against these criteria:

1. **False positive audit**: For each DEAD_CODE or UNUSED_LIB finding, verify the symbol is not invoked dynamically (via `subprocess`, `importlib`, `sys.path`, or markdown references). Findings that cannot be confirmed MUST be downgraded to MEDIUM or removed. 2. **Severity calibration**: CRITICAL findings MUST describe a concrete negative outcome (data loss, security exposure, broken tests). Findings without a concrete outcome MUST be downgraded to HIGH or MEDIUM. 3. **Completeness**: If fewer than 3 categories were analyzed in a full-mode run, note the gap as a warning at the top of the findings output.

Revise the findings in memory before passing to STEP 2. Do NOT re-run the analyzer. This step is performed inline by the coordinator.

STEP 2: Present Findings

Display the categorized report. Group findings by category, sort by severity within each group (CRITICAL first, LOW last). Show total counts per category.

**For --tests mode**, also display the test shape distribution table:

## Test Shape Distribution (Quality Diamond)

| Type          | Count | Actual% | Target% | Status |
|---------------|-------|---------|---------|--------|
| Unit          | 120   | 75.0%   | 60%     | Over   |
| Integration   | 20    | 12.5%   | 25%     | Under  |
| Property      | 0     | 0.0%    | 5%      | Under  |
| GenAI         | 20    | 12.5%   | 10%     | OK     |

Format findings:

## Refactor Results

### TEST_SHAPE (N issues)
- [HIGH] tests/: unit tests over-represented: 75% actual vs 60% target
  Suggestion: Reduce unit tests to align with Quality Diamond

### TEST_WASTE (N issues)
- [MEDIUM
Read more
Ships withautonomous-dev

A harness that wraps Claude Code with enforcement, specialist agents, and alignment gates to deliver consistent, production-grade software engineering outcomes.

Get the whole plugin, auto-invoked
Stats
32
Stars
0
Views
5
Forks
Active
Maintenance
Python
Language
2h ago
Last commit
9mo ago
Created

Repo: akaszubski/autonomous-dev