safe-refactor

A command for changing existing code while checking that its behavior remains intact. It uses code review, an isolated Git branch, tests, baseline measurements, performance comparisons, and approval gates.

In plain words
What is it for?
Use it for behavior-preserving changes such as extracting methods or introducing parameter objects, with interactive or automatic workflows.
Why use it?
It makes large code changes easier to inspect and reverse if tests, performance, or quality checks reveal a problem.

Command

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add commands/paulduvall/ai-development-patterns/safe-refactor
Clone the repo
git clone --depth 1 https://github.com/PaulDuvall/ai-development-patterns
Per session 12 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 1,230 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00012 $0.01230
Opus 5 $0.00006 $0.00615
Sonnet 5 $0.00002 $0.00246
Haiku 4.5 $0.00001 $0.00123

Measured 3d ago against content hash 93101a3c80f9, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

safe-refactor scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 3d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

examples/custom-commands/commands/safe-refactor.md · 195 lines

How it starts

The opening of the file, as written. The whole thing — 195 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Safe Refactor

You are helping a developer perform safe refactoring with comprehensive safety checks. Combine built-in review commands with custom safety workflows: baseline analysis, isolated branching, full test execution, performance comparison, and automated quality gates.

Usage

/safe-refactor                    # Interactive refactoring with safety checks
/safe-refactor --auto             # Automatic refactoring with approval gates

Process

1. Pre-Refactoring Analysis

Run built-in review command to analyze current code state:

/review

Capture baseline metrics:

  • Current test coverage percentage
  • Cyclomatic complexity scores
  • Performance benchmarks (if available)
  • Code quality metrics

2. Create Safety Branch

Create isolated git branch for refactoring:

git checkout -b refactor-$(date +%Y%m%d-%H%M%S)

Branch naming convention:

  • refactor-YYYYMMDD-HHMMSS for timestamp-based tracking
  • Example: refactor-20250110-143022

3. Perform Refactoring Changes

Execute refactoring based on analysis:

  • Apply specific refactoring patterns (Extract Method, Introduce Parameter Object, etc.)
  • Maintain existing functionality (behavior-preserving changes only)
  • Update related tests if necessary
  • Add inline comments explaining complex refactoring decisions

4. Run Existing Test Suite

Verify all existing tests still pass:

# Run full test suite
npm test  # or pytest, go test, etc.

Requirements:

  • 100% of existing tests must pass
  • No test modifications allowed unless absolutely necessary
  • If tests fail, explain failure and provide fix options

5. Generate New Tests for Refactored Code

Create additional tests for refactored code:

  • Test new methods created during refactoring
  • Verify edge cases for extracted functions
  • Add integration tests if refactoring spans multiple modules
  • Ensure code coverage remains at or above baseline

6. Compare Performance Before/After

Run performance benchmarks (if applicable):

# Example for Node.js
npm run benchmark

# Example for Python
python -m pytest tests/benchmarks/ --benchmark-only

Read the full file on GitHub · 195 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 3d ago First seen · 195 lines · 12 tokens per session scan A 93101a3c80f9

Subscribe to this mod's changes

safe-refactor is a command published in the GitHub repository PaulDuvall/ai-development-patterns (645 stars, last pushed 4d ago), licensed MIT. It adds 12 tokens to every session and 1,230 once invoked, about $0.0001 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.