Related Code Files:
text_operation_history.py- Core undo tracking systemtext_undo.py- CLI interface for undo operationsreplace_text_v9.py- Text replacement with undoreplace_text_ast_v3.py- AST refactoring with undounified_refactor_v2.py- Universal refactoring with undorefactor_rename_v2.py- Batch renaming with undosafe_file_manager_undo_wrapper.py- File operations wrapper with undo
The Code Intelligence Toolkit multi-level undo system provides SafeGIT-style protection for all text editing operations. Every modification is tracked, backed up, and reversible through a unified interface.
┌─────────────────────────────────────────────────────────────────┐
│ User/AI Agent │
│ (Executes editing tools) │
└─────────────────────────────┬───────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Editing Tools Layer │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌──────────┐ │
│ │replace_text │ │replace_text │ │unified │ │refactor │ │
│ │_v9.py │ │_ast_v3.py │ │_refactor_v2 │ │_rename_v2│ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └─────┬────┘ │
│ │ │ │ │ │
│ └────────────────┴────────────────┴──────────────┘ │
│ │ │
│ Undo Integration │
│ (Tracks all operations) │
└─────────────────────────────┬───────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ TextOperationHistory (Core) │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ • Singleton instance per process │ │
│ │ • Thread-safe with file locking │ │
│ │ • Atomic operation recording │ │
│ │ • Automatic backup creation │ │
│ │ • Compression for files >1KB │ │
│ │ • Recovery script generation │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────┬───────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Storage Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ operations │ │ backups/ │ │ recovery │ │
│ │ .jsonl │ │ (gzipped) │ │ _scripts/ │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ ~/.text_operation_history/ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ text_undo.py (CLI) │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Commands: │ │
│ │ • history - View operation history │ │
│ │ • undo - Restore previous state │ │
│ │ • show - Display operation details │ │
│ │ • stats - System statistics │ │
│ │ • clean - Remove old operations │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
The heart of the undo system, providing:
class TextOperationHistory:
"""Manages undo history for text operations with atomic guarantees"""
def record_operation(
self,
operation_type: OperationType,
file_path: Path,
tool_name: str,
command_args: List[str],
old_content: Optional[str] = None,
new_content: Optional[str] = None,
changes_count: int = 0,
description: str = ""
) -> Optional[TextOperation]Key Features:
- Singleton pattern ensures single history instance
- Thread-safe with exclusive file locking
- Atomic writes to prevent corruption
- Automatic compression for storage efficiency
class OperationType(Enum):
REPLACE_TEXT = "replace_text"
REPLACE_AST = "replace_ast"
UNIFIED_REFACTOR = "unified_refactor"
MULTI_EDIT = "multi_edit"
WRITE_FILE = "write_file"
DELETE_FILE = "delete_file"Each operation type has specific handling and recovery strategies.
Operations are stored in JSONL format for streaming processing:
{
"operation_id": "1753732740927_91513",
"timestamp": 1753732740.927,
"operation_type": "replace_text",
"file_path": "/path/to/file.py",
"tool_name": "replace_text_v9",
"command_args": ["old", "new", "file.py"],
"changes_count": 3,
"description": "Replace 'old' with 'new'",
"backup_path": "backups/1753732740927_91513_file.py.gz",
"metadata": {
"original_size": 1024,
"new_size": 1027,
"compressed": true
}
}# Import undo system
from text_operation_history import (
TextOperationHistory, OperationType, get_history_instance
)
# In your write operation
def write_file(path, content):
# Get original content if exists
old_content = path.read_text() if path.exists() else None
# Record operation BEFORE making changes
history = get_history_instance()
operation = history.record_operation(
operation_type=OperationType.WRITE_FILE,
file_path=path,
tool_name="my_tool",
command_args=sys.argv[1:],
old_content=old_content,
new_content=content,
description="My operation description"
)
# Perform the actual write
path.write_text(content)
# Notify user
if operation:
print(f"[Undo ID: {operation.operation_id}]")Minimal modification approach used in v9/v3/v2 tools:
- Add imports at top
- Add global tracking variables
- Modify atomic write function
- Add argument parsing for --no-undo
- Add summary display at end
- All operations use file locking
- Backup created before any modification
- Operations logged only after backup succeeds
- Exclusive locks prevent race conditions
- Timeout handling for stuck locks
- Process-safe operation IDs
- Multiple recovery paths:
- CLI undo command
- Recovery scripts
- Manual backup restoration
- Operation replay from log
- Automatic gzip compression for files >1KB
- Typically 60-90% space savings
- Streaming decompression for large files
- ~5-10ms overhead per operation
- Parallel backup creation
- Lazy loading of operation history
- Append-only log scales to millions of operations
- Automatic cleanup of old operations
- No memory issues with streaming
TEXT_UNDO_MAX_HISTORY=10000 # Max operations (default: 5000)
TEXT_UNDO_MAX_AGE_DAYS=60 # Retention days (default: 30)
TEXT_UNDO_COMPRESSION=0 # Disable compression
TEXT_UNDO_STORAGE_PATH=/custom # Custom storage location# Disable for specific operation
--no-undo
# Custom description
--undo-description "Fix critical security bug"- Backups inherit source file permissions
- Storage directory is user-only (700)
- No sensitive data logging
- No encryption (use disk encryption)
- Local storage only
- No network operations
- Selective Undo - Undo specific changes within a file
- Undo Groups - Group related operations
- Remote Sync - Sync undo history across machines
- Git Integration - Hybrid version control
- Web UI - Visual history browser
- Custom operation types
- Plugin architecture for tools
- Alternative storage backends
- Encryption support
- Always track operations before modifying files
- Provide meaningful descriptions
- Use appropriate operation types
- Handle undo system failures gracefully
- Review history before major operations
- Use custom descriptions for clarity
- Clean old operations periodically
- Backup the undo directory itself
The multi-level undo system brings enterprise-grade safety to all text operations in the Code Intelligence Toolkit. By following SafeGIT's proven patterns and extending them to all file modifications, we provide developers and AI agents with the confidence to experiment freely, knowing that any change can be reversed.
The architecture prioritizes safety, performance, and ease of integration, making it a foundational component for reliable automated code modification.