Catching Code Erosion in an Agent's Own Edit History

When a coding agent built on a large language model extends its own code across a sequence of changing requirements, the code gets worse in ways that tests do not catch. SlopCodeBench measured this directly. Structural erosion, meaning complexity piling into functions that are already complex, rose in 77% of agent trajectories, and verbosity rose in 75.5%. Agent code accumulated verbosity about 7x faster and erosion about 5x faster than human repository histories. The degradation is gradual and test-passing, so neither the agent's tests nor a rollback to "the last version that passed" can see it.

We propose to treat the agent's edit history as a versioned graph. Each version of the program is stored as a graph of its syntax, control flow, and calls, and every node and edge records the versions in which it existed. Over that history we run graph pattern queries that describe harmful edit shapes. One example is "a function added at step $k$ whose body duplicates a function that already existed at step $j<k$." Another is "a guard added at step $k$ that compares input against a literal appearing only in a failing test." A third is "a structure that was rolled back at step $j$ and reappears at step $k$."

When a pattern fires, the agent does not receive a score or a stack trace. It receives a message naming the earlier version and the exact structure involved. Optionally, only the offending piece of the edit is reverted. The bet is that erosion is mostly a small number of recognizable edit shapes, and that feedback which points into the agent's own history fixes them without discarding the new functionality each checkpoint requires.

Core Claim

The specific claim has two parts. First, temporal edit patterns predict later checkpoint failures better than scalar quality metrics computed on the current snapshot. Second, intervening at the level of the matched edit improves both maintainability and downstream functional correctness, and beats both whole-version rollback and metric-threshold gating. Both parts are needed. If a scalar erosion gate does as well, the graph machinery is unnecessary. If maintainability improves but later checkpoints are not passed more often, then erosion is a cosmetic problem and the project's motivation weakens.

The hallucination framing is deliberate. The survey Siren's Song in the AI Ocean separates context-conflicting hallucinations, where output contradicts what the model itself produced earlier, from errors against the input or the world. Several erosion shapes are context-conflicting hallucinations expressed in code. The agent reimplements a helper it already wrote. It bypasses an invariant it established two steps earlier. It re-proposes a patch that was already rejected. Code Hallucination showed related failures in single sessions: "code bloating," where models insert redundant loops that change appearance but not behavior, and drift under multi-turn pressure. That paper exposes these failures but does not detect them automatically. Our patterns can only be written because the history is stored.

How This Differs From What Exists

Four lines of work each supply one piece, and none combines them.

Measurement. SlopCodeBench motivates the project. It establishes the erosion problem and reports that quality-aware prompting reduces initial slop but "doesn't prevent the code from degrading over subsequent iterations," while raising cost and slightly lowering correctness. It diagnoses erosion and offers no intervention.

Rollback. MEIC is the closest intervention. In Verilog debugging, a scorer agent plus simulator feedback trigger a rollback to the previous best file, reaching 78% functional fix rate with GPT-4 against 66% for retrieval or fine-tuning baselines. MEIC's rollback is whole-file and one step deep, and it treats code as text. Its authors report a "new error trap" on dense modules that this rollback cannot untangle. Our proposal replaces whole-file reversion with edit-level diagnosis. It is also built for changing specifications, where reverting a whole version also throws away work the new requirement needs.

Pattern matching. SAT-Based Algorithms for Regular Graph Pattern Matching supplies the method. It defines patterns with wildcard nodes ("any sequence of one or more nodes," "any subgraph") over control-flow graphs of Python code and compiles matching to Boolean satisfiability. On CodeSearchNet its node-merging step cut clauses by 25.7% and timeouts from 34,110 to 26,487 of 946,556 instances. Its patterns are static, matched against isolated snapshots, and never placed in a generation loop. We add version constraints to these patterns. The reported timeouts also constrain our design: we must restrict matching to the region an edit touched rather than the whole program.

Versioned storage. Two systems supply this method. GLENDA stores RDF archives as snapshots plus deltas and answers three kinds of query: reconstruct a version, retrieve the change between two versions, and report which versions a pattern holds in. Transactions Make Debugging Easy records transactional provenance so humans can query execution history and replay fixes against past states. Neither touches an LLM loop. Neither matches structural patterns over code.

We also borrow the bitemporal idea from Jensen. Valid time is when a fact holds in the modeled world; transaction time is when it was recorded. Here, valid time is the set of accepted program versions in which a code element exists. Transaction time is when the agent generated it, including drafts that were rejected. Rejected drafts exist in transaction time but never in valid time, which is exactly what is needed to detect an agent looping back to a patch it already tried.

Research Program

Versioned program graph. Every agent turn is parsed into a graph with syntax nodes, control-flow edges, and call edges. It is aligned to the previous version by a structural diff, so each node and edge gets an identity that persists across versions. The store keeps periodic full snapshots plus deltas in the style of GLENDA. It records each element's valid-time interval and transaction timestamp, together with the test outcomes and the specification text active at that turn.

Temporal pattern language. A temporal pattern is a pair $(P, \tau)$. Here $P$ is a wildcard graph pattern in the ReGaP sense, and $\tau$ assigns each element of $P$ a constraint over versions, such as "present at $v_k$, absent at $v_{k-1}$" or "present only in transaction time." A match at turn $k$ is a mapping $m$ from $P$ into the stored history such that

$$ m \text{ is a ReGaP match of } P \text{ into } \bigcup_{v \le k} G_v \quad\text{and}\quad \text{life}(m(x)) \models \tau(x) \text{ for every element } x \text{ of } P, $$

where $G_v$ is the program graph at version $v$ and $\text{life}(\cdot)$ is the recorded valid/transaction history of a matched element.

At turn $k$ we require at least one pattern element to map into the delta between $v_{k-1}$ and $v_k$. This locality condition is the main engineering lever against the wildcard blowup the ReGaP paper reports. We will measure whether it keeps per-turn matching cost small relative to the agent's own inference time.

Pattern library. We will not rely only on hand-written patterns. We seed the library with shapes taken from SlopCodeBench's erosion and verbosity definitions and from HallTrigger's bloating and drift case studies. We then mine contrastive edit patterns: subgraph-plus-time shapes that are frequent in agent trajectories and rare in human repository histories, and that precede failures on later checkpoints. Mining uses only training folds of problems, so pattern design never sees the evaluation problems.

Intervention. When a pattern fires, the agent receives a short structured message, such as "the function parse_row you added now duplicates load_record from step 2; reuse or merge it." In the surgical variant, the matched delta subgraph is reverted while the rest of the turn's edit is kept, and tests are re-run. If tests regress, the full edit is restored and only the message is kept.

Baselines

Unaided agent (reference point). The naive reference is the same agent, with the same model, turn budget, and token budget, running SlopCodeBench with no intervention. The published reference is SlopCodeBench's own result: the best agents pass about 14.8% of checkpoints, with erosion increasing in 77% and verbosity in 75.5% of trajectories. We rerun this with our model rather than relying only on the paper.

Scalar-metric gate (strongest simple competitor). At each turn, SlopCodeBench's erosion and verbosity scores are computed on the new snapshot. If either rises beyond a threshold, the edit is rejected and regenerated with a message stating which score rose. This is the strongest competitor because it uses the benchmark's own definition of degradation, needs no graph store, and is what a reviewer would build first. Its threshold and retry count get the same tuning budget, on the same training folds, as our pattern thresholds. No reported result for this gate was found on Lacuna; we implement it. Beating it means two things on held-out folds: higher downstream checkpoint pass rate at equal or lower erosion, and fewer total tokens per checkpoint.

MEIC-style rollback (strongest existing method). This is MEIC's mechanism transplanted to Python: a scorer agent plus tests decide acceptance, and rejection reverts to the previous best version. MEIC's reported 78% functional fix rate is on Verilog debugging, not iterative extension, so it is not directly comparable. We reimplement it on SlopCodeBench under identical budgets.

LLM reviewer. A developer–QA review loop in the style of MAGIS checks for duplication and erosion, and is given the full diff history in context.

Ablations. Three ablations isolate the key ingredients. Static patterns matched on the current snapshot only isolate the temporal constraints. Temporal patterns triggering whole-version rollback, rather than surgical reversion, isolate localization. Pattern-triggered messages with the history references stripped out isolate the "point into your own past" component.

Why not just…?

Why not just gate on SlopCodeBench's erosion and verbosity scores? This is the real threat, and the proposal is built around testing it. A scalar gate knows that the code got worse but not which edit did it or what earlier element it conflicts with. It can only reject or regenerate the whole turn, which under changing specifications also discards required functionality. Our prediction is that the gate reduces measured erosion about as well as we do but loses on downstream pass rate and token cost. If the gate matches us on both, we will report that temporal graph patterns are unnecessary and that the contribution reduces to "gate on erosion."

Why not just prompt the agent to write clean code and review its history? SlopCodeBench already tested quality-aware prompting. It reduced initial slop but did not stop progressive degradation, and it cost more and slightly lowered correctness. Code Hallucination shows models drifting under multi-turn pressure and failing to recognize seeded bugs in their own context. We include the prompted variant as a baseline rather than assume it fails.

Why not just keep a git history and roll back to the best passing version? MEIC's own "new error trap" on dense modules shows the limit of one-step rollback. Under evolving specifications, the "best passing version" usually predates the new requirement. The whole-version-rollback ablation measures exactly how much is lost compared with surgical reversion.

Why not just feed the tests and tracebacks back, as most refinement loops do? DebugBench found that tracebacks help on syntax and reference errors but hurt on logic errors, and that GPT-4's pass rate fell from 75% overall to 55.9% on four-bug instances. Erosion is test-passing by definition, so traceback feedback has nothing to say about it. Our structural messages are a different feedback channel. We test directly whether they avoid the paradox on logic bugs.

Why not just use a bigger model? Scale is orthogonal. We run the main comparison at two model sizes. The intervention is only interesting if its gain does not vanish at the larger size.

Proposed Experiments

Main comparison. The primary benchmark is SlopCodeBench: 36 problems and 196 checkpoints. We evaluate with problem-level cross-validation, using six folds, with pattern mining and threshold tuning restricted to training folds. We report three outcomes: checkpoint pass rate, the benchmark's erosion and verbosity trajectories, and tokens per checkpoint.

First decisive check: does erosion cause failure? Because our patterns were mined against the same notion of degradation used for evaluation, lower erosion alone could be Goodhart's law at work. We therefore make downstream functional correctness the primary outcome. Specifically, we test whether intervening at checkpoint $k$ raises the pass rate at checkpoints $k+1$ onward. We complement this with blind human maintainability ratings on a sampled subset of final programs.

Second decisive check: does history help predict failure? We train a simple classifier to predict whether a trajectory will fail its next checkpoint. One version uses features from matched temporal patterns; the other uses current-snapshot scalar metrics. If temporal features add nothing, the history half of the claim fails.

Feedback channel on logic bugs. We build a multi-turn variant of DebugBench's logic-bug subset. Each round, the agent sees either tracebacks or pattern messages computed over its own repair history. We report whether the latter avoids the degradation DebugBench documents.

Cost and stress tests. We report per-turn matching time and SAT timeouts under the locality restriction, and compare them with the timeout rates the ReGaP paper reports for unrestricted matching. As a qualitative stress test, we replay HallTrigger's bloating and drift scenarios and check whether the corresponding patterns fire.