Skip to content

update_symbolΒΆ

Safely replace a function, class, or method in a source file with new code while preserving surrounding code and creating backups.

Quick ReferenceΒΆ

update_symbol(
    file_path: str,              # Path to file
    target_type: str,            # "function", "class", "method"
    target_name: str,            # Symbol name
    new_code: str,               # New implementation
    create_backup: bool = True,  # Create .bak file
    operation: str = "replace"   # "replace" or "delete"
) -> UpdateResult

User StoriesΒΆ

Persona Story Tool Value
πŸ‘€ Sarah (AI User) "Safely update AI-generated code with automatic backups" Safe code changes
πŸ‘₯ David (Team Lead) "Update functions without breaking surrounding code" Surgical modifications
πŸ”§ Chris (OSS Contributor) "Contribute code changes with confidence" Safe contributions

β†’ See all user stories

ParametersΒΆ

Parameter Type Required Default Description
file_path string Yes - Absolute path to file
target_type string Yes - "function", "class", or "method"
target_name string Yes - Name of symbol to update
new_code string Yes* - New code (required unless operation="delete")
create_backup bool No true Create backup before modifying
operation string No "replace" "replace" or "delete"

Response SchemaΒΆ

{
  "data": {
    "file_path": "string",
    "target_name": "string",
    "target_type": "string",
    "status": "string",
    "backup_path": "string | null",
    "lines_changed": {
      "before": ["integer", "integer"],
      "after": ["integer", "integer"]
    },
    "diff": "string"
  },
  "error": null,
  "tier_applied": "string",
  "duration_ms": "integer"
}

ExamplesΒΆ

Replace a FunctionΒΆ

Update the validate_email function in validators.py to use a more robust regex pattern
{
  "file_path": "/project/src/validators.py",
  "target_type": "function",
  "target_name": "validate_email",
  "new_code": "def validate_email(email: str) -> bool:\n    \"\"\"Validate email format using RFC 5322 pattern.\"\"\"\n    import re\n    pattern = r\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\"\n    return bool(re.match(pattern, email))"
}
codescalpel update-symbol src/validators.py validate_email \
  --function \
  --new-code "$(cat << 'EOF'
def validate_email(email: str) -> bool:
    """Validate email format using RFC 5322 pattern."""
    import re
    pattern = r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@..."
    return bool(re.match(pattern, email))
EOF
)"
{
  "data": {
    "file_path": "/project/src/validators.py",
    "target_name": "validate_email",
    "target_type": "function",
    "status": "updated",
    "backup_path": "/project/src/validators.py.bak",
    "lines_changed": {
      "before": [15, 19],
      "after": [15, 20]
    },
    "diff": "--- before\n+++ after\n@@ -15,5 +15,6 @@\n-def validate_email(email: str) -> bool:\n-    \"\"\"Validate email format.\"\"\"\n-    pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$'\n-    return bool(re.match(pattern, email))\n+def validate_email(email: str) -> bool:\n+    \"\"\"Validate email format using RFC 5322 pattern.\"\"\"\n+    import re\n+    pattern = r\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@...\"\n+    return bool(re.match(pattern, email))"
  },
  "tier_applied": "community",
  "duration_ms": 45
}

Replace a MethodΒΆ

Update the process method in DataProcessor to handle errors gracefully
{
  "file_path": "/project/processor.py",
  "target_type": "method",
  "target_name": "DataProcessor.process",
  "new_code": "def process(self, data: list) -> list:\n    \"\"\"Process data items with error handling.\"\"\"\n    results = []\n    for item in data:\n        try:\n            transformed = self.transform(item)\n            validated = self.validate(transformed)\n            results.append(validated)\n        except ProcessingError as e:\n            self.logger.error(f\"Failed to process item: {e}\")\n            continue\n    return results"
}
codescalpel update-symbol processor.py DataProcessor.process \
  --method \
  --new-code-file new_process.py
{
  "data": {
    "file_path": "/project/processor.py",
    "target_name": "process",
    "target_type": "method",
    "status": "updated",
    "backup_path": "/project/processor.py.bak",
    "lines_changed": {
      "before": [25, 33],
      "after": [25, 37]
    }
  },
  "tier_applied": "community",
  "duration_ms": 52
}

Replace a ClassΒΆ

Replace the entire Config class with a dataclass version
{
  "file_path": "/project/config.py",
  "target_type": "class",
  "target_name": "Config",
  "new_code": "@dataclass\nclass Config:\n    \"\"\"Application configuration.\"\"\"\n    database_url: str\n    debug: bool = False\n    log_level: str = \"INFO\"\n    max_connections: int = 10\n    \n    @classmethod\n    def from_env(cls) -> 'Config':\n        return cls(\n            database_url=os.environ['DATABASE_URL'],\n            debug=os.environ.get('DEBUG', 'false').lower() == 'true',\n            log_level=os.environ.get('LOG_LEVEL', 'INFO'),\n            max_connections=int(os.environ.get('MAX_CONNECTIONS', '10'))\n        )"
}
codescalpel update-symbol config.py Config \
  --class \
  --new-code-file new_config.py

Delete a FunctionΒΆ

Remove the deprecated legacy_handler function from handlers.py
{
  "file_path": "/project/handlers.py",
  "target_type": "function",
  "target_name": "legacy_handler",
  "operation": "delete"
}
codescalpel update-symbol handlers.py legacy_handler \
  --function \
  --operation delete
{
  "data": {
    "file_path": "/project/handlers.py",
    "target_name": "legacy_handler",
    "status": "deleted",
    "backup_path": "/project/handlers.py.bak",
    "lines_removed": [45, 78]
  },
  "tier_applied": "community",
  "duration_ms": 38
}

Update Without BackupΒΆ

{
  "file_path": "/project/src/utils.py",
  "target_type": "function",
  "target_name": "format_date",
  "new_code": "def format_date(dt: datetime) -> str:\n    return dt.isoformat()",
  "create_backup": false
}
codescalpel update-symbol src/utils.py format_date \
  --function \
  --new-code "def format_date(dt: datetime) -> str: return dt.isoformat()" \
  --no-backup

Tier DifferencesΒΆ

This tool is available at all tiers. What differs are the limits and capabilities:

Feature Community Pro Enterprise
Availability βœ… Available βœ… Available βœ… Available
Basic updates βœ… βœ… βœ…
Backup creation βœ… βœ… βœ…
Diff generation βœ… βœ… βœ…
Protected files Not available ⚠️ Warning πŸ›‘οΈ Enforced
Audit logging Not available βœ… βœ…
Approval workflow Not available Not available βœ…

Error HandlingΒΆ

Symbol Not FoundΒΆ

{
  "data": null,
  "error": {
    "code": "SYMBOL_NOT_FOUND",
    "message": "Function 'validat_email' not found in validators.py",
    "suggestions": ["validate_email", "validate_phone"],
    "available_symbols": {
      "functions": ["validate_email", "validate_phone", "validate_url"]
    }
  }
}

Syntax Error in New CodeΒΆ

{
  "data": null,
  "error": {
    "code": "SYNTAX_ERROR",
    "message": "New code has syntax error at line 3: unexpected indent",
    "details": {
      "line": 3,
      "column": 4,
      "context": "    return bool(re.match(pattern, email)"
    }
  }
}

Protected File (Enterprise)ΒΆ

{
  "data": null,
  "error": {
    "code": "PROTECTED_FILE",
    "message": "File 'src/security/auth.py' is protected",
    "policy": "Modifications require approval from security-team",
    "approvers": ["security-team"]
  }
}

Tier LimitsΒΆ

update_symbol capabilities vary by tier:

Feature Community Pro Enterprise
Backup enabled βœ… βœ… βœ…
Validation level Syntax Semantic Full
Max updates per call 10 Unlimited Unlimited
Single file update βœ… βœ… βœ…
Cross-file import updates ❌ βœ… βœ…
Semantic validation ❌ βœ… βœ…
Type checking ❌ βœ… βœ… Full
Protected files ❌ ❌ βœ… Policy-based

Community TierΒΆ

  • βœ… Safely replace functions, classes, methods
  • βœ… Automatic backup creation (.bak files)
  • βœ… Syntax validation before updating
  • βœ… Preserve surrounding code
  • ⚠️ Max 10 updates per call - Small refactorings only
  • ⚠️ Syntax-only validation - May introduce semantic errors
  • ❌ No cross-file import updates
  • ❌ No type checking

Pro TierΒΆ

  • βœ… All Community features
  • βœ… Unlimited updates per call - Large refactorings
  • βœ… Semantic validation - Ensure code makes sense
  • βœ… Cross-file import updates - Update imports automatically
  • βœ… Type checking - Verify types are correct
  • βœ… Reference tracking - See what calls the symbol

Enterprise TierΒΆ

  • βœ… All Pro features
  • βœ… Full validation - Complete correctness checks
  • βœ… Protected files - Policy-based write protection
  • βœ… Approval workflows - Require team approval
  • βœ… Audit trail - Track all symbol changes
  • βœ… Rollback support - Multi-level undo

Key Difference: Validation Depth and Safety - Community: Syntax validation, 10 updates - Basic safety - Pro: Semantic validation, unlimited - Production refactoring - Enterprise: Full validation, protected files - Enterprise safety

β†’ See tier comparison

Best PracticesΒΆ

  1. Extract before updating - Always get current code first
  2. Keep backups enabled - Easy rollback if needed
  3. Test new code separately - Verify syntax before updating
  4. Use simulate_refactor - Verify behavior preservation
graph TD
    A[extract_code] --> B[Modify locally]
    B --> C[simulate_refactor]
    C -->|Safe| D[update_symbol]
    C -->|Unsafe| E[Revise changes]
    E --> B
    D --> F[Verify file]