Agent code generation has a measurement problem. Most eval frameworks count pass rates on synthetic benchmarks or rely on majority-vote consensus across model runs. Neither approach answers the question that matters in production: does this agent repeat the same mistakes?
Randal Schwartz built a 375-ticket empirical ledger to track exactly that. The system logs every breakage, categorizes the failure mode, and instruments a 4-layer verification stack to prevent the same regression from shipping twice. The result is a trust metric grounded in actual defects, not simulated tasks.
The Cost Curve Nobody Talks About
Barry Boehm's research from the 1980s established an exponential defect cost curve: fixing a bug in requirements costs $1, in development costs $500, in production costs $25,000. The ratio holds across decades and languages.
Agent-generated code collapses this timeline. An LLM can write 200 lines of Python in 30 seconds, skip the requirements phase entirely, and push code that fails silently in production because the agent never learned that failure mode existed.
The traditional response is more testing. The empirical ledger approach is different: capture every failure as a scar, index it by symptom and root cause, then inject that scar into the agent's context before it writes similar code again.
The 4-Layer Verification Stack
The stack operates at four distinct trust boundaries:
| Layer | Scope | Failure Mode Detected | Instrumentation |
|---|---|---|---|
| Syntax | Parse tree validity | Malformed code, missing imports | Language-specific linter, AST walker |
| Type | Static type correctness | Null derefs, type mismatches | Type checker (mypy, Dart analyzer) |
| Contract | Pre/post conditions | Violated invariants, bad state transitions | Assertion injection, property-based tests |
| Regression | Historical defect patterns | Repeat bugs from the 375-ticket ledger | Scar file matching, cross-language pattern detection |
Each layer runs independently. A failure at any layer blocks the commit and appends a new entry to the ledger. The agent sees the failure, the fix, and the category tag in its next context window.
Cross-Language Regression Detection
The most interesting failure mode came from Dart. The ledger tracked four distinct Dart bugs related to async state management and null safety. When the agent generated Python code for a flight recorder (event logging system), the regression layer flagged a pattern match: the Python code exhibited the same async state race that had broken a Dart service three months earlier.
The Dart scar file contained:
scar_id: dart_async_state_race_001
symptom: Event logger drops messages under concurrent writes
root_cause: Async callback modifies shared state without lock
languages: [dart, python, javascript]
pattern:
- async function writes to shared collection
- no mutex or queue serialization
- high concurrency environment
fix_template: |
Replace direct collection mutation with queue.put()
or asyncio.Lock() guard
The Python agent had never seen this exact bug in Python. But the scar file's languages field triggered a cross-language match. The verification layer rejected the code, injected the Dart scar into context, and the agent rewrote the flight recorder with proper async locking.
Building the Empirical Ledger
The ledger is a Git repository of YAML files. Each ticket gets a unique ID, a timestamp, the language, the symptom, the root cause, and the fix. Tags group related failures (null safety, async, type coercion, off-by-one).
When the agent starts a new task, the orchestrator:
- Parses the task description for keywords (async, database, API, file I/O)
- Queries the ledger for scars matching those keywords and the target language
- Injects the top 5 most relevant scars into the system prompt
- Runs the 4-layer verification stack on the generated code
- If a new failure occurs, appends it to the ledger and retries with the scar in context
The ledger grows monotonically. After 375 tickets, the system has coverage for most common failure modes in Python, Dart, and JavaScript. The regression rate (same bug appearing twice) dropped to near zero after ticket 200.
Why Majority Vote Fails
Some agent frameworks run the same prompt through three models, then pick the code that two out of three agree on. This approach optimizes for consensus, not correctness.
The empirical ledger approach optimizes for defect prevention. If all three models make the same mistake (because they share the same pre-training blind spot), majority vote ships the bug. The scar file catches it.
The difference shows up in production. Majority vote reduces variance but not bias. The ledger reduces both by explicitly teaching the agent about failure modes that don't appear in public training data.
Observability and State Management
The orchestrator maintains a state machine with five phases:
- Parse: Extract task requirements, query ledger for relevant scars
- Generate: Call LLM with scars in context
- Verify: Run 4-layer stack, collect failures
- Repair: If verification fails, inject failure into context and regenerate (max 3 attempts)
- Commit: If verification passes, append code to repo and update ledger metadata
Each phase emits structured logs (JSON) with timing, token count, scar IDs used, and verification results. The logs feed a dashboard that tracks:
- Regression rate over time
- Most common failure categories
- Scar injection effectiveness (how often a scar prevents a repeat bug)
- Cross-language pattern matches
The state machine is idempotent. If the orchestrator crashes mid-task, it resumes from the last completed phase using a checkpoint file.
Deployment Shape
The system runs as three containers:
- Orchestrator: FastAPI service that manages the state machine and calls the LLM
- Verifier: Isolated sandbox (gVisor) that runs the 4-layer stack on untrusted code
- Ledger: Git repository mounted as a volume, with a simple CRUD API for scar queries
The orchestrator and verifier communicate over gRPC. The verifier never sees the LLM API key. The ledger is append-only from the orchestrator's perspective (the verifier has read-only access).
For production deployments, the verifier runs in a separate Kubernetes namespace with network policies that block outbound traffic except to the orchestrator. The LLM calls happen in the orchestrator, which has internet access but never executes untrusted code.
Likely Failure Modes
Scar file bloat: After 1,000 tickets, the ledger becomes too large to fit in the context window. The mitigation is semantic search over scar embeddings, but that introduces latency and requires a vector database.
False positives: The pattern matcher occasionally flags safe code as a regression. The current threshold is tuned for high recall (catch all real regressions) at the cost of precision (some false alarms). Each false positive requires manual review and ledger annotation.
Cross-language drift: A scar written for Python might not apply cleanly to Rust or Go. The languages field helps, but the fix template often needs language-specific adjustments. The system doesn't auto-translate fixes yet.
Adversarial prompts: If the agent's task description contains keywords that trigger irrelevant scars, the context window fills with noise. The query logic needs better semantic filtering, not just keyword matching.
Technical Verdict
Use this approach when:
- You generate code in multiple languages and need cross-language defect tracking
- Your agent ships code to production and you need measurable regression prevention
- You have the infrastructure to run isolated verification sandboxes
- You can tolerate the latency of a 4-layer verification stack (adds 2-5 seconds per generation)
Avoid it when:
- You're prototyping and don't care about repeat bugs yet
- Your agent only writes throwaway scripts
- You don't have the ops capacity to maintain a ledger and verification infrastructure
- Your tasks are so varied that scar reuse is low (the ledger never pays off)
The empirical ledger trades upfront instrumentation cost for long-term defect reduction. It works best when the agent writes similar code repeatedly, so the scar database becomes a high-value asset. For one-off tasks, the overhead isn't worth it.
Top comments (0)