Skip to content

simulate_refactorΒΆ

Simulate applying a code change and verify that the refactored code preserves the original behavior using symbolic execution.

Quick ReferenceΒΆ

simulate_refactor(
    original_code: str,          # Original code
    new_code: str = None,        # New implementation
    patch: str = None,           # Or provide a patch
    strict_mode: bool = False    # Strict comparison
) -> RefactorSimulation

User StoriesΒΆ

Persona Story Tool Value
πŸ‘€ Sarah (AI User) "Verify my refactor won't break behavior" Safe code changes
πŸ‘₯ David (Team Lead) "Verify refactor is safe before PR approval" Risk mitigation
πŸ”§ Chris (OSS Contributor) "Verify my contribution doesn't break existing behavior" Safe contributions
πŸ›‘οΈ Marcus (Security Engineer) "Ensure refactoring preserves security properties" Security preservation

β†’ See all user stories

ParametersΒΆ

Parameter Type Required Default Description
original_code string Yes - Original code before refactoring
new_code string No* None New code after refactoring
patch string No* None Unified diff patch
strict_mode bool No false Require exact behavior match

*One of new_code or patch is required.

Response SchemaΒΆ

{
  "data": {
    "is_safe": "boolean",
    "behavior_preserved": "boolean",
    "differences": [
      {
        "type": "string",
        "description": "string",
        "original_behavior": "string",
        "new_behavior": "string",
        "inputs": {},
        "severity": "string"
      }
    ],
    "path_comparison": {
      "original_paths": "integer",
      "new_paths": "integer",
      "matching_paths": "integer",
      "divergent_paths": "integer"
    },
    "warnings": ["string"],
    "recommendation": "string"
  },
  "tier_applied": "string",
  "duration_ms": "integer"
}

ExamplesΒΆ

Verify Safe RefactorΒΆ

Check if this refactoring is safe:

Original:
def calculate_total(items):
    total = 0
    for item in items:
        total += item['price'] * item['quantity']
    return total

Refactored:
def calculate_total(items):
    return sum(item['price'] * item['quantity'] for item in items)
{
  "original_code": "def calculate_total(items):\n    total = 0\n    for item in items:\n        total += item['price'] * item['quantity']\n    return total",
  "new_code": "def calculate_total(items):\n    return sum(item['price'] * item['quantity'] for item in items)"
}
codescalpel simulate-refactor \
  --original-code "def calculate_total(items):\n    total = 0\n    for item in items:\n        total += item['price'] * item['quantity']\n    return total" \
  --new-code "def calculate_total(items):\n    return sum(item['price'] * item['quantity'] for item in items)"
{
  "data": {
    "is_safe": true,
    "behavior_preserved": true,
    "differences": [],
    "path_comparison": {
      "original_paths": 3,
      "new_paths": 3,
      "matching_paths": 3,
      "divergent_paths": 0
    },
    "warnings": [],
    "recommendation": "βœ… Refactoring is safe. Behavior is preserved for all analyzed paths."
  },
  "tier_applied": "community",
  "duration_ms": 95
}

Detect Behavior ChangeΒΆ

Check if this change is safe:

Original:
def divide(a, b):
    if b == 0:
        return None
    return a / b

Refactored:
def divide(a, b):
    return a / b
{
  "original_code": "def divide(a, b):\n    if b == 0:\n        return None\n    return a / b",
  "new_code": "def divide(a, b):\n    return a / b"
}
codescalpel simulate-refactor \
  --original-code "def divide(a, b):\n    if b == 0:\n        return None\n    return a / b" \
  --new-code "def divide(a, b):\n    return a / b"
{
  "data": {
    "is_safe": false,
    "behavior_preserved": false,
    "differences": [
      {
        "type": "EXCEPTION_INTRODUCED",
        "description": "New code raises ZeroDivisionError where original returned None",
        "original_behavior": "Returns None",
        "new_behavior": "Raises ZeroDivisionError",
        "inputs": {"a": 10, "b": 0},
        "severity": "HIGH"
      }
    ],
    "path_comparison": {
      "original_paths": 2,
      "new_paths": 1,
      "matching_paths": 1,
      "divergent_paths": 1
    },
    "recommendation": "❌ Refactoring changes behavior. The zero-division check was removed."
  },
  "tier_applied": "community",
  "duration_ms": 78
}

Check Return Type ChangeΒΆ

Verify this type change is safe:

Original:
def get_count(items):
    return len(items)

Refactored:
def get_count(items):
    return str(len(items))
{
  "original_code": "def get_count(items):\n    return len(items)",
  "new_code": "def get_count(items):\n    return str(len(items))",
  "strict_mode": true
}
codescalpel simulate-refactor \
  --original-code "def get_count(items):\n    return len(items)" \
  --new-code "def get_count(items):\n    return str(len(items))" \
  --strict-mode
{
  "data": {
    "is_safe": false,
    "behavior_preserved": false,
    "differences": [
      {
        "type": "RETURN_TYPE_CHANGE",
        "description": "Return type changed from int to str",
        "original_behavior": "Returns int (e.g., 5)",
        "new_behavior": "Returns str (e.g., '5')",
        "inputs": {"items": [1, 2, 3, 4, 5]},
        "severity": "MEDIUM"
      }
    ],
    "recommendation": "❌ Return type changed. This may break callers expecting int."
  }
}

Verify with PatchΒΆ

Check if this diff is safe to apply
{
  "original_code": "def validate(data):\n    if data is None:\n        return False\n    if len(data) == 0:\n        return False\n    return True",
  "patch": "--- a/validators.py\n+++ b/validators.py\n@@ -1,6 +1,3 @@\n def validate(data):\n-    if data is None:\n-        return False\n-    if len(data) == 0:\n-        return False\n-    return True\n+    return bool(data)"
}

```bash codescalpel simulate-refactor \ --original-code "def validate(data):\n if data is None:\n return False\n if len(data) == 0:\n return False\n return True" \ --patch "--- a/validators.py

+++ b/validators.py @@ -1,6 +1,3 @@ def validate(data): - if data is None: - return False - if len(data) == 0: - return False - return True + return bool(data)" ```

{
  "data": {
    "is_safe": true,
    "behavior_preserved": true,
    "differences": [],
    "path_comparison": {
      "original_paths": 3,
      "new_paths": 2,
      "matching_paths": 3,
      "divergent_paths": 0
    },
    "warnings": [
      "New code has fewer explicit paths but equivalent behavior"
    ],
    "recommendation": "βœ… Refactoring is safe. `bool(data)` is equivalent to the original checks."
  }
}

Complex RefactoringΒΆ

Verify this optimization is behavior-preserving
{
  "original_code": "def find_max(numbers):\n    if not numbers:\n        return None\n    max_val = numbers[0]\n    for num in numbers[1:]:\n        if num > max_val:\n            max_val = num\n    return max_val",
  "new_code": "def find_max(numbers):\n    return max(numbers) if numbers else None"
}
codescalpel simulate-refactor \
  --original-code "def find_max(numbers):\n    if not numbers:\n        return None\n    max_val = numbers[0]\n    for num in numbers[1:]:\n        if num > max_val:\n            max_val = num\n    return max_val" \
  --new-code "def find_max(numbers):\n    return max(numbers) if numbers else None"
{
  "data": {
    "is_safe": true,
    "behavior_preserved": true,
    "differences": [],
    "path_comparison": {
      "original_paths": 4,
      "new_paths": 2,
      "matching_paths": 4,
      "divergent_paths": 0
    },
    "recommendation": "βœ… Refactoring is safe. Built-in max() provides equivalent behavior."
  }
}

Difference TypesΒΆ

Type Description Severity
EXCEPTION_INTRODUCED New code raises exception where original didn't HIGH
EXCEPTION_REMOVED Original raised exception, new doesn't MEDIUM
RETURN_VALUE_CHANGE Different return value for same input HIGH
RETURN_TYPE_CHANGE Return type changed MEDIUM
PATH_REMOVED Execution path no longer exists MEDIUM
PATH_ADDED New execution path introduced LOW
SIDE_EFFECT_CHANGE Different side effects HIGH

Tier LimitsΒΆ

simulate_refactor capabilities vary by tier:

Feature Community Pro Enterprise
Max file size 1 MB 10 MB 100 MB
Analysis depth Basic Advanced Deep
Basic simulation βœ… βœ… βœ…
Path comparison βœ… βœ… βœ…
Strict mode βœ… βœ… βœ…
Max paths analyzed 20 100 Unlimited
Side effect detection ❌ βœ… βœ… Comprehensive
Type preservation check ❌ βœ… βœ… Full
Performance impact ❌ ❌ βœ…

Community TierΒΆ

  • βœ… Simulate basic refactoring changes
  • βœ… Path comparison (original vs new)
  • βœ… Strict mode for exact behavior matching
  • βœ… Detect exception changes
  • ⚠️ Max 20 paths - Simple functions only
  • ⚠️ Limited to 1 MB files - Small files only
  • ⚠️ Basic analysis - May miss subtle issues
  • ❌ No side effect detection

Pro TierΒΆ

  • βœ… All Community features
  • βœ… Max 100 paths analyzed - Complex functions
  • βœ… Max 10 MB files - Larger modules
  • βœ… Advanced analysis - Better issue detection
  • βœ… Side effect detection - Track state changes
  • βœ… Type preservation - Ensure types stay consistent
  • βœ… Return value tracking - Verify outputs

Enterprise TierΒΆ

  • βœ… All Pro features
  • βœ… Unlimited paths - Any function complexity
  • βœ… Max 100 MB files - Very large modules
  • βœ… Deep analysis - Complete behavior verification
  • βœ… Comprehensive side effects - All state changes
  • βœ… Full type checking - Complete type preservation
  • βœ… Performance impact - Before/after performance comparison

Key Difference: Analysis Depth and Scale - Community: 20 paths, 1 MB, basic - Simple refactorings - Pro: 100 paths, 10 MB, advanced - Production refactorings - Enterprise: Unlimited, 100 MB, deep - Complex refactorings

β†’ See tier comparison

Best PracticesΒΆ

  1. Test before and after - Don't rely solely on simulation
  2. Use strict mode - When exact behavior matters
  3. Review differences - Understand why behavior changed
  4. Check edge cases - Simulation may not cover all
  5. Combine with tests - Run existing tests after refactor

WorkflowΒΆ

graph TD
    A[Plan Refactoring] --> B[simulate_refactor]
    B -->|Safe| C[Apply Change]
    B -->|Unsafe| D[Review Differences]
    D --> E[Adjust Refactoring]
    E --> B
    C --> F[Run Tests]
    F -->|Pass| G[Complete]
    F -->|Fail| H[Investigate]