| name | refactor_safety |
| description | Validates refactoring operations for behavioral equivalence and safety. Invoke when user requests refactoring, code cleanup, or structural changes to existing code. |
SKILL: Safe Refactoring Validation
๐ฏ Objective
Ensure refactored code maintains identical external behavior to the original. Detect breaking changes before they reach production.
๐ง Core Principle: Behavioral Equivalence
Refactoring must not change observable behavior. Any deviation in outputs, side effects, or error conditions constitutes a failed refactor.
๐ Severity Legend
UNSAFE โ Observable behavior changed. Block until reconciled or explicitly approved as intentional.
RISK โ Plausible behavior change that current tests do not cover. Add coverage before merging.
SAFE โ Behavior verified equivalent against a real check.
โ
Verification Discipline
"Looks equivalent" is not equivalence. Capture a baseline before touching code, then diff against it. If no characterization tests exist for the code being refactored, write them first โ you cannot prove equivalence against nothing.
๐ ๏ธ Execution Pipeline
1. BASELINE_CAPTURE
Goal: Freeze the current behavior as the source of truth.
How to verify: Run the existing suite on the original code and save results. If coverage is thin, add characterization tests that pin current outputs before refactoring.
2. INVARIANT_IDENTIFICATION
Goal: Name the rules that must never break.
3. STATIC_ANALYSIS
Goal: Confirm the surface area is intact.
4. BEHAVIORAL_DIFF_TESTING
Goal: Same inputs โ same outputs, old vs new.
Example:
# Capture before and after on identical inputs, then diff
git stash && app run --input fixtures/ > /tmp/before.txt
git stash pop && app run --input fixtures/ > /tmp/after.txt
diff /tmp/before.txt /tmp/after.txt # must be empty for SAFE
5. CONTRACT_VERIFICATION
Goal: External contracts are byte-for-byte stable.
6. PERFORMANCE_REGRESSION_CHECK
Goal: No silent slowdowns.
7. SIDE_EFFECT_VERIFICATION
Goal: Same writes, calls, and emissions as before.
8. ERROR_BEHAVIOR_PRESERVATION
Goal: Failures fail the same way.
๐ค Output Directives
Report: [SAFE/RISK/UNSAFE] - STAGE_NAME: Specific behavioral change with before/after comparison.
List invariants preserved vs violated.
Example output:
[UNSAFE] - SIDE_EFFECT_VERIFICATION: New code emits 2 audit events; original emitted 1. Restore single-event behavior.
[RISK] - BEHAVIORAL_DIFF_TESTING: parseDate() path has no tests; cannot prove equivalence. Add characterization tests.
[SAFE] - CONTRACT_VERIFICATION: Response JSON identical across all 14 fixtures.
[SAFE] - ERROR_BEHAVIOR_PRESERVATION: Same exception types and messages on invalid input.