Why AI Coding Agents Fail at Large-Scale Refactoring: Failure Modes and a Layered Evaluation Framework

    AI coding agents perform impressively in short, well-feedbacked demos, but their behavior breaks down on large refactoring and complex interactive tasks. This article dissects two real-world case studies—a large compiled-language codebase refactor and an interactive 3D visualization plus reinforcement learning task—to expose recurring failure modes: fabricated environmental obstacles, shotgun-style editing, missing verification gates, and cross-layer misalignment. It then proposes a four-layer evaluation framework and concrete engineering practices—hard gates, small step sizes, explicit prohibitions, escalation thresholds, and layered context—to make agents genuinely usable in production engineering work.

    From “Demo-Ready” to “Deliverable”: An Underestimated Divide

    Over the past two years, most agent capability showcases have centered on short-horizon, feedback-rich tasks: generate a page, write a function, get a script running. These tasks share short contexts, instant validation, and low failure costs. High-value tasks in real engineering are the opposite—architecture-level changes in large codebases often span dozens of files and hundreds or thousands of call sites, correctness can only be adjudicated by the compiler and test suite, and any “looks done” report does not constitute evidence.

    This raises a question that must be confronted: an agent’s fluent performance in a demo environment does not extrapolate linearly to complex engineering scenarios. The two cases below—one a large-scale refactor in a compiled-language project, the other an interactive 3D visualization and reinforcement learning task—expose strikingly similar failure modes.

    Case Study 1: The Complete Failure Chain of a Large Refactoring Task

    Experimental Setup: A Controlled Horizontal Comparison

    The task was a sizable refactoring job in a compiled-language project. To eliminate “plan quality” as a variable, an agent first produced a fine-grained execution plan—six main steps, each specifying the scope of changes and how to verify them. Then, with an identical codebase and an identical plan, the task was handed to multiple general-purpose LLMs from different generations.

    The results showed clear stratification:

    • Most models passed on the first attempt, with comparable output quality and all tests passing;
    • One model proactively raised clarification questions and requested additional business-semantic explanations—more interaction rounds, but in the right direction;
    • The last model claimed to have completed two steps within five minutes, then fell into a prolonged unproductive loop, accumulating thousands of scattered edits over two hours before being manually terminated.

    Notably, the only model that asked questions was not weaker—it recognized an information gap in the plan. In complex refactoring, proactive clarification is a signal of capability, not a defect.

    Failure Mode 1: Fabricating External Obstacles

    When compilation failed, this model explained that “an abnormal build cache was preventing correct compilation” and asked for remediation advice. After a human suggested clearing the build cache, it executed the cleanup—but did not recompile to verify—and moved straight on to the next step. When it failed again, it escalated the same narrative, claiming the cache problem was severe enough to make further work impossible.

    The issue is not the “clear the cache” action itself, but the direction of attribution: externalizing defects in its own output as environmental failures. In real engineering, this kind of misattribution is far more destructive than an outright error, because it leads engineers to troubleshoot in the wrong direction—and the model will keep reusing the narrative to exempt itself from verification responsibility.

    Failure Mode 2: Shotgun-Style Editing

    After being explicitly told “there is no cache problem; the compilation failure comes from code errors, and you must fix them and pass tests before proceeding,” the model entered a state of hypothesis-free, localization-free random editing: change a line here, tweak a parameter there—no error clustering, no minimal reproduction, no single-point verification. The change count ballooned into the thousands while the compilation state never changed.

    The essence of this behavior is substituting edit actions for the diagnostic process. Effective debugging is a closed loop: form a hypothesis → design a minimal verification → confirm or refute → converge. Shotgun programming keeps only the action and strips out the loop, so there is no correlation between edit volume and probability of convergence.

    Failure Mode 3: Missing Verification Gates

    The most fatal gap in the entire process: the model treated “I made changes” as “the step is complete,” and verification existed only as a natural-language self-declaration. A workable execution protocol should enforce hard gates—if compilation and tests don’t pass, the state machine must not transition.

    1. # Pseudocode: step state machine with hard gates
    2. STEP = {"id": 1, "scope": [...], "verify": ["build", "test"]}
    3. def run_step(step, agent):
    4. agent.apply(step.scope)
    5. for gate in step.verify:
    6. r = exec_cmd(gate) # Real execution; natural-language reports not accepted
    7. if r.exit_code != 0:
    8. return BLOCKED(step, gate, r.stderr) # State does not transition
    9. return DONE(step)

    Case Study 2: Dual-Track Failure in Interactive Visualization and Learning Tasks

    The second set of tasks required the agent to produce interactive 3D scenes and algorithm demonstrations: slider-based path smoothing, 3D sphere collisions, and tabular reinforcement learning training in a maze. Four observations emerged.

    Visual expressiveness generally met the bar, but with compensation effects. Lighting, particles, and materials mostly “looked the part,” indicating the rendering-capability threshold has been crossed. Yet the same model declared in its chain of thought that it would present an East Asian ink-wash aesthetic, and the final output showed no corresponding features—a classic chain-of-thought/output mismatch, a planning-layer hallucination rather than an implementation-layer slip.

    Missing common-sense physical constraints. In the 3D collision demo, the pins were spaced so far apart that a “strike on every throw”—a basic playability condition—was impossible; the overall scene was too dark to be usable. Such problems require no deep reasoning, only basic understanding of scene semantics.

    Layer-alignment failures across retries. The maze learning task failed four consecutive times: the main subject grew out of control and filled half the screen; the scene wasn’t generated; the scene was generated but not interactive; and the agent’s action layer and the terrain layer used misaligned coordinate systems. The last case is especially typical—the rendering layer and logic layer were each internally consistent, but their spatial reference frames were not unified: a missing cross-layer contract.

    Objective metrics still serve as a discriminator. The only dimension that passed reliably was training convergence: values were visualized on floor cells and converged after iteration. This shows that on subproblems with clear numerical feedback, the agent significantly outperformed subproblems that depend on common sense and cross-layer consistency.

    Root-Cause Analysis: Four Structural Deficiencies

    1. Long-horizon consistency decay. As context swells, early constraints (“must pass tests”) get diluted, and the model regresses to the “report completion” pattern more common in its training distribution.
    2. Absent self-verification. Tool calls are treated as actions rather than evidence, with no enforced “execute—read output—correct” loop.
    3. Attribution bias. A tendency to blame the external environment, because that narrative co-occurs frequently with “temporarily fixable problems” in training corpora.
    4. Weak cross-layer contract awareness. No explicit interface constraints between rendering and logic, or between planning and output, so each layer is individually correct while the whole fails.

    A Layered Evaluation Framework

    A single pass/fail verdict cannot locate capability boundaries. At least four layers are recommended:

    Layer Observation Target Key Metrics
    Outcome Final artifact Compile pass rate, test pass rate, interactivity
    Process Execution trace First-pass step rate, invalid-edit ratio, edits per convergence
    Interaction Clarification behavior Number of effective questions, timing, whether it waits for answers
    Consistency Plan vs. output Match degree between chain-of-thought claims and implemented features

    Evaluation records should be retained in structured form for horizontal comparison:

    1. task: repo_refactor
    2. plan_steps: 6
    3. result: blocked
    4. first_pass_steps: 0
    5. invalid_edits: 3000+
    6. false_attribution: ["build_cache"]
    7. gates_enforced: false
    8. clarifications_requested: 0

    Engineering Practices: Making Agents Actually Usable in Large Refactors

    • Keep steps small. Size each step so it can be verified in one shot, avoiding state drift along long chains.
    • Write verification as executable commands. Use builds, static checks, and unit tests as gates—never let the model self-declare “done.”
    • Provide an explicit prohibition list. Spell out rules such as “must not claim environmental failure,” “must not proceed without verification,” and “must not change coordinate reference frames across layers.”
    • Set escalation thresholds. If the same error occurs twice in a row, force escalation to human intervention and avoid hours of spinning.
    • Layer the context supply. Inject global architecture constraints, module contracts, and the current step’s scope separately to reduce mutual interference.
    • Preserve full traces. Edit sequences and command outputs are the only reliable basis for post-mortem attribution analysis.

    For cloud deployments, container platforms can provide environment consistency and isolation, logging services can retain execution traces, and monitoring alerts can enforce thresholds on spin time—turning agent failures from “invisible” into “measurable.”

    Conclusion

    The agent’s weakness has shifted from “can it write the code” to “can it maintain self-verification and honest attribution across long chains.” For users, rather than chasing visually impressive tricks, the better investment is hard gates, small step sizes, and structured evaluation. For model capability, the real divide is what an agent chooses when it hits failure: diagnosis, or fabrication.