1. Why Single-Shot Code Generation Fails
In standard conversational AI interfaces, code generation operates as an open-loop (single-shot) system: the developer provides a prompt, the LLM emits a block of code, and execution is left entirely to the developer.
In production codebases, single-shot generation fails frequently due to:
- Missing Context & Hallucinated Imports: LLMs guess function signatures or import non-existent helper modules when file context is missing.
- Subtle Type and Interface Inconsistencies: Code that appears syntactically correct fails during compilation or runtime unit tests due to mismatched return types.
- No Runtime Feedback: Without the ability to inspect stack traces, compiler diagnostics, and test exit codes, an AI agent cannot iterate toward a verified solution.
A Self-Healing Coding Agent converts code generation into a closed-loop control system. The agent generates a candidate diff, executes the relevant test or build command, captures diagnostic failures, and iteratively refines its patch until verification succeeds.
2. The 5-Stage Self-Healing Loop
In proxima-agent/proxima_agent/agent.py, self-healing
execution is structured into five deterministic stages:
smart-slicer.js)memory.db & skills.db)patch_file
toolinsights.db | Failed: Increment Retry (Max: 5)3. AST Symbol Slicing (smart-slicer.js)
Dumping entire $5,000$-line source files into an LLM context window exhausts token limits and
degrades attention. Proxima employs an Abstract Syntax Tree (AST) slicer located at
proxima/src/utils/smart-slicer.js to extract only the relevant scope enclosing the
error line number.
import * as parser from '@babel/parser';
import traverse from '@babel/traverse';
export function extractTargetSymbolScope(sourceCode, targetLine) {
const ast = parser.parse(sourceCode, {
sourceType: "module",
plugins: ["typescript", "jsx", "classProperties"]
});
let matchedScope = null;
traverse(ast, {
FunctionDeclaration(path) {
const { start, end } = path.node.loc;
if (targetLine >= start.line && targetLine <= end.line) {
matchedScope = {
name: path.node.id?.name || "anonymous",
type: "FunctionDeclaration",
startLine: start.line,
endLine: end.line,
content: sourceCode.split('\n').slice(start.line - 1, end.line).join('\n')
};
}
},
ClassMethod(path) {
const { start, end } = path.node.loc;
if (targetLine >= start.line && targetLine <= end.line) {
matchedScope = {
name: path.node.key?.name || "method",
type: "ClassMethod",
startLine: start.line,
endLine: end.line,
content: sourceCode.split('\n').slice(start.line - 1, end.line).join('\n')
};
}
}
});
return matchedScope;
}
4. The 4 SQLite Memory Vaults
A self-healing agent must not repeat errors it has already diagnosed. Proxima maintains four
independent SQLite databases under ~/.proxima-agent/ and ~/.proxima/:
| Database File | Source Module | Schema Role |
|---|---|---|
vault.db |
recall/vault.py |
Stores conversation threads, sub-agent fork branches, and task checkpoint state. |
insights.db |
recall/insights.py |
Stores cross-session user preferences, framework conventions, and persistent repository facts. |
memory.db |
brain/memory.py |
Stores historical error signatures, stack traces, and the successful diffs that resolved them. |
skills.db |
prompt/skills.py |
Stores dynamic procedural Python skills scored by Bayesian success smoothing and EMA. |
import sqlite3
import hashlib
from typing import Optional, Dict
class ErrorMemoryVault:
def __init__(self, db_path: str = "~/.proxima-agent/memory.db"):
self.conn = sqlite3.connect(db_path)
self._init_schema()
def _init_schema(self):
with self.conn:
self.conn.execute("""
CREATE TABLE IF NOT EXISTS error_patches (
id INTEGER PRIMARY KEY AUTOINCREMENT,
error_hash TEXT UNIQUE,
error_signature TEXT,
failed_code TEXT,
resolved_patch TEXT,
success_count INTEGER DEFAULT 1,
last_observed TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
def find_historical_patch(self, error_signature: str) -> Optional[str]:
sig_hash = hashlib.sha256(error_signature.strip().encode()).hexdigest()
cursor = self.conn.execute(
"SELECT resolved_patch FROM error_patches WHERE error_hash = ?", (sig_hash,)
)
row = cursor.fetchone()
return row[0] if row else None
5. Bayesian Skill Scoring & Exponential Moving Average (EMA)
When the agent discovers a reusable script or procedural skill (e.g. "How to regenerate
Tailwind tokens"), it persists the skill in skills.db. In proxima-agent/proxima_agent/prompt/skills.py, skills are
dynamically ranked using an Exponential Moving Average with $\alpha = 0.3$ and Bayesian prior
smoothing.
EMA_ALPHA = 0.3
PRIOR_SUCCESSES = 3.0
PRIOR_FAILURES = 1.0
def calculate_bayesian_skill_score(successes: int, total_attempts: int, historical_ema: float) -> float:
"""
Computes smoothed skill score combining Bayesian prior with Exponential Moving Average.
Prevents newly learned skills with 1 attempt from skewing execution priority.
"""
bayesian_smoothed = (successes + PRIOR_SUCCESSES) / (total_attempts + PRIOR_SUCCESSES + PRIOR_FAILURES)
combined_score = (EMA_ALPHA * bayesian_smoothed) + ((1.0 - EMA_ALPHA) * historical_ema)
return round(combined_score, 4)
6. Safety Boundaries & Execution Permissions
Autonomous execution without safeguards risks unintended destructive changes (e.g., recursive
directory deletion or rogue git pushes). In proxima_agent/permissions.py, execution
is governed by three strict permission modes:
| Permission Mode | Behavior | Risk Policy |
|---|---|---|
| Full Auto | Executes shell commands and file patches autonomously within configured retry limits. | Restricted to safe developer sandbox directories. |
| Smart (Default) | Risk-scores commands. Read-only operations and non-destructive tests run automatically; destructive operations prompt for user approval. | Scores commands based on AST analysis and keyword risk heuristics. |
| Suggest | The agent acts as an advisor, emitting candidate diffs without modifying files until the user clicks approve. | Zero autonomous file modifications. |
7. Failure Analysis & Loop Halting
| Symptom | Root Cause | Diagnosis | Fix |
|---|---|---|---|
Loop halted: MAX_RETRY_LIMIT_EXCEEDED |
The agent attempted 5 iterative patches without passing verification tests. | Check agent log in ~/.proxima-agent/logs/ for oscillating diffs. |
The agent automatically halts and escalates the stack trace to the user. |
AST Smart Slicer syntax error |
Target file contains non-standard proprietary syntax extensions unparseable by Babel. | Inspect smart-slicer.js debug output. |
The slicer falls back to fixed line-window extraction ($\pm 25$ lines). |
database disk image is malformed |
Abrupt system power loss corrupted local SQLite write-ahead log (WAL). | Run sqlite3 ~/.proxima-agent/memory.db "PRAGMA integrity_check;". |
Delete corrupted WAL index; Proxima will recreate cleanly. |
8. Architectural Takeaways
Self-healing agents succeed by combining deterministic AST analysis, structured diagnostic capture, persistent experience recall, and rigorous verification gates.