Building a Self-Healing Autonomous System
The Problem
When you run autonomous systems 24/7, things break. Files get corrupted, services crash, dependencies conflict, and code has bugs. Without self-healing, you need human intervention to fix every issue.
The Solution: 3-Tier Auto-Repair
I built a 3-tier auto-repair system:
T0: Regex Repair (Fast, Pattern-Based)
Catches common syntax errors:
- Missing colons
- Unclosed brackets
- Indentation errors
- Common typos
def repair_t0(code):
# Fix missing colons after if/for/while/def
code = re.sub(r'(if|for|while|def|class|else|elif|try|except|finally)\s*([^
]*)
', r':
', code)
# Fix unclosed brackets
code = fix_brackets(code)
return code
T1: AST Repair (Structural)
Uses Python AST to detect and fix structural issues:
- Missing imports
- Undefined variables
- Type mismatches
- Broken function signatures
def repair_t1(code):
try:
ast.parse(code)
return code # Already valid
except SyntaxError as e:
# Use AST analysis to fix the issue
tree = ast.parse(code, fix_missing_end=True)
return ast.unparse(tree)
T2: LLM Repair (Complex)
For complex issues that need understanding:
- Logic errors
- API misuse
- Architecture issues
- Semantic bugs
def repair_t2(code, error):
prompt = f"Fix this Python code that has error: {error}\n\nCode:\n{code}"
fixed = llm.generate(prompt)
return fixed
Test Gate (4 Stages)
Every repair goes through 4 test stages:
- Syntax Test - Does the code parse?
- Import Test - Do all imports work?
- Unit Test - Do existing tests pass?
- Integration Test - Does the module work in the system?
def test_gate(code, module_path):
# Stage 1: Syntax
try:
ast.parse(code)
except SyntaxError:
return False, "Syntax error"
# Stage 2: Imports
try:
import importlib
mod = importlib.import_module(module_path)
except ImportError as e:
return False, f"Import error: {e}"
# Stage 3: Unit tests
if not run_unit_tests(module_path):
return False, "Unit tests failed"
# Stage 4: Integration
if not run_integration_tests(module_path):
return False, "Integration tests failed"
return True, "All tests passed"
Self-Modifier (Backup → Fix → Test → Revert)
The self-modifier safely applies changes:
- Backup the original file
- Apply the fix
- Test with the test gate
- Keep if tests pass, Revert if tests fail
def self_modify(file_path, new_code):
backup = backup_file(file_path)
write_file(file_path, new_code)
success, message = test_gate(new_code, file_path)
if success:
return True, "Fix applied successfully"
else:
revert_file(file_path, backup)
return False, f"Fix reverted: {message}"
Results
- T0 fixes 40% of issues instantly
- T1 fixes another 30% with AST analysis
- T2 fixes the remaining 30% with LLM
- Test gate prevents bad fixes from being applied
- Self-modifier ensures safe rollback
Next Steps
- Add more T0 patterns
- Improve T2 with better prompts
- Add performance regression tests
- Add security tests
This is a project from Nexus Intelligence - an autonomous self-healing system.
Top comments (0)