AI for Legacy Code: A Practical Guide to Debugging and Refactoring with LLMs
This article explores how large language models (LLMs) can take over legacy code that was generated by other tools but never ran successfully. Using a UEFI Tetris case study, it breaks the workflow into two rounds: first getting the code to compile, boot, and reach a reproducible failure point, then refining graphics, input, game logic, and maintainability. It covers structured code review, turning vague issues into actionable defect lists, fixing lifecycle and graphics protocol bugs, context management, small-step verification, and validation loops. It also outlines what LLMs do well, what still requires human judgment, and why code repairability is becoming a key metric in the AI-assisted development era.
AI for Legacy Code: A Practical Guide to Debugging and Refactoring with LLMs
1. Why “AI Cleaning Up After AI” Is Worth Taking Seriously
As AI-assisted programming moves into real engineering work, an increasingly common but often overlooked scenario is taking over code that was generated by another tool or person and never actually ran.
The original practice behind this article is representative. One AI coding tool generated an initial Tetris implementation for a UEFI environment: seven source files, modular separation, and naming and directory structures that all looked reasonable. Yet the full chain never ran, and the build environment was never set up. Around the same time, another LLM completed a Chinese brick-breaker game in a BIOS environment; it compiled on the first try and ran successfully on the first launch.
It is tempting to reduce this contrast to “one model is simply better.” But the more useful engineering question is how repairable the legacy code is, and how well an LLM performs in code review, defect localization, and iterative optimization.
A fair objection is that the two models were given different tasks, so the comparison is not apples to apples. That objection holds. The more interesting extension is this: if the code structure is reasonable and only has defects, can another LLM take it over and finish the debugging and refinement? That is much closer to real development work than generating new code from scratch. In practice, a large share of engineering time is spent understanding, diagnosing, and modifying existing code rather than writing it from zero.
So the test moved into a more meaningful phase: hand legacy code to an LLM, get it running first, then refine and optimize.
2. Test Design: Two Rounds That Mirror Real Maintenance
To avoid judging “by feel,” this kind of practice works best in two rounds.
Round 1: From non-runnable to basically runnable
The goal is to bring the program into an observable state:
- It compiles;
- It boots;
- It reaches the main loop;
- It prints key debug information;
- It narrows down to a minimal reproducible failure point.
Round 2: From runnable to playable and maintainable
The goal is to turn “it runs” into “it is deliverable”:
- The graphical interface displays correctly;
- Input handling is stable;
- Game logic forms a closed loop;
- Resource release and error paths are under control;
- Key modules are testable and extensible.
These two rounds map directly to “bug fixing” and “quality improvement” in real development. They also let you break LLM capability into verifiable indicators instead of a vague “good or bad code” judgment.
3. Round 1: Key Steps From Dead Code to Runnable
1. Code review: build global understanding before changing anything
When taking over legacy code, the first step is not to edit. It is to have the LLM perform a structured review. The first instruction in the original practice was simple: review the code and find likely problems.
A mature LLM typically scans in this order:
- Entry point and startup chain: module initialization order and whether dependencies are complete;
- Main loop: whether event handling, rendering, and input polling form a closed loop;
- Game logic: whether the state machine is complete and boundary values are handled;
- Rendering module: whether graphics protocols, frame buffers, and mode settings match;
- Input handling: whether key mapping, scan code parsing, focus, and the event loop are consistent;
- Error handling: whether return values are checked and whether failure paths exit directly.
The value here is turning black-box code into a verifiable list of problems. Every later fix can proceed around that list instead of being dragged around by error messages.
2. Turn problems into a list: make the AI output executable tasks
Good output is not “there might be a problem.” It is an actionable defect list, for example:
- Module initialization order during startup may cause a null pointer;
- Frame buffer information becomes invalid after a mode switch;
- The way the graphics protocol is located is unstable;
- The event loop lacks a timeout and exit condition;
- Input scan codes do not match the logical key mapping;
- The resource release path is missing, so leaks may occur on errors.
Once problems are broken into items, the LLM can fix them one by one, and the developer can verify them one by one. This is the first step in moving AI programming from demo to engineering.
3. Typical failure one: the program crashes immediately
In the original practice, the program printed “Starting Game Loop” and then exited right away. This is very typical in low-level graphics programs: on the surface it looks like a crash, but it is usually an unhandled failure branch in the initialization chain.
After adding serial debug output, the problem was narrowed to the point after the graphics protocol call. Further analysis showed that the struct pointer returned by the mode query was no longer reliable after the mode set call completed. In other words, querying first, setting the mode, and then still reusing the old pointer is a classic lifetime error.
The fix is not just adding a null check. It requires correcting when the data is obtained:
- Re-fetch the current frame buffer information after the mode is set;
- Make all later logic that depends on that information use the new data;
- Add return value checks at the entry point to avoid silent failures.
// Fix approach: re-fetch frame buffer info after setting the modeif (set_mode(...) != SUCCESS) {return FAILURE;}// Re-fetch to avoid using an invalid pointerframe_info = get_frame_buffer_info();if (frame_info == NULL || frame_info->buffer == NULL) {return FAILURE;}
The point of this kind of fix is that it turns “random exit” into “explainable failure.” As long as the failure path is explainable, later debugging has something to grab onto.
4. Typical failure two: the graphical interface does not appear
Once the program ran, a new problem appeared: nothing was displayed. The original practice fed the symptom back to the LLM and started a second round of localization.
This kind of problem is usually not “the code is completely wrong” but “the protocol or descriptor does not match.” In a UEFI environment, graphics output often involves protocol location, device handle selection, and mode matching. Common failures include:
- The protocol GUID in use does not match the current environment;
- When locating a protocol by handle, the target device is not the preferred output device;
- The mode number does not match what the current display device supports;
- The frame buffer address or pixel format is misunderstood;
- Drawing logic does not match the screen resolution or stride.
The key to fixing these issues is not blind guessing. It is having the LLM output verifiable diagnostic steps: list the objects to check, the values to print, and the return values to verify, then confirm them one by one.
4. From “It Runs” to “It’s Playable”: The Core of Round 2
1. Closing the graphics and input loop
Once the screen finally appears, the focus shifts to the interaction loop:
- Whether key presses trigger reliably;
- Whether long press and auto-repeat are controllable;
- Whether block rotation, left/right movement, and soft drop are consistent;
- Whether input latency is acceptable;
- Whether focus loss or abnormal input can freeze the main loop.
At this stage, the LLM’s value is not only writing features but proposing observable indicators based on symptoms, such as adding state logs, drawing debug information, and outputting frame counts and input event counts.
2. Boundary handling in game logic
Tetris looks simple, but boundary handling really tests engineering quality:
- Block-to-wall collision;
- Block-to-settled-block collision;
- Row shifting after line clears;
- Level progression and falling speed changes;
- State transitions for pause, resume, and restart;
- Resource release and exit paths on game over.
If these are not sorted out early, later defects like “occasionally freezes,” “sometimes passes through,” and “abnormal speed” become hard to reproduce.
3. Maintainability improvements
Once the program runs, the real engineering value shows up in maintainability:
- Decouple input, logic, and rendering;
- Add return value conventions to key functions;
- Add comments and enums to the state machine;
- Replace magic numbers with constants;
- Add minimal logging and assertion mechanisms.
LLMs often give fairly complete refactoring suggestions for this kind of task, but developers still need to make architecture calls and avoid refactoring for its own sake.
5. Engineering Essentials for Handing Legacy Code to AI
1. Context management: do not make the model guess
The biggest risk in legacy code debugging is missing context. An effective approach is:
- First provide the directory structure and module responsibilities;
- Then provide key function signatures;
- Then provide the error symptom and reproduction steps;
- Only then ask the model to output a fix.
The more structured the context, the closer the AI output is to executable.
2. Small-step verification: do not make one big change
AI is good at generating patches that look complete, but a one-shot big change amplifies risk. A safer rhythm is:
- Change only one module at a time;
- Verify immediately after each change;
- Keep rollback points;
- Record how the symptom changed after each edit.
3. Have the AI output a diagnostic plan, not just final code
In complex debugging, asking the model to output diagnostic steps first is often more efficient than asking for the answer directly. For example:
- Which return values need to be confirmed;
- Which pointers and handles need to be printed;
- Which modes and resolutions need to be verified;
- Which log points need to be observed.
This significantly reduces changes that look reasonable but cannot be put into practice.
4. Build a validation loop
AI-generated code is only the start. The validation loop is what makes engineering deployment real:
- Compilation passes;
- Startup passes;
- Key path logs are complete;
- Functionality is repeatable;
- Error paths have fallbacks.
Without a validation loop, AI programming easily stays at “looks like it runs.”
6. Capability Boundaries and Best Practices
What LLMs are good at
- Quickly generating structured code skeletons;
- Summarizing common error patterns;
- Giving executable troubleshooting steps;
- Completing local refactoring under clear constraints;
- Generating helper code such as logs, assertions, and test stubs.
What still needs human oversight
- Real hardware differences in complex environments;
- System-level protocol compatibility issues;
- Architecture-level tradeoffs and long-term maintenance strategy;
- Locating and optimizing performance bottlenecks;
- Final judgment on business and security boundaries.
In other words, AI is better suited as a senior assistant than as an unattended responsible party. The reliable collaboration model is: humans define goals and constraints, AI provides candidate solutions and diagnostic paths, and humans verify and decide.
7. Further Thought: Code Repairability Is Becoming a Key AI-Era Metric
In the past, code was often judged by “does it run.” In the AI-assisted programming era, one more dimension matters: whether the code is easy for another intelligent tool to understand, diagnose, and fix.
From this angle, modularity, clear naming, return value conventions, logging, and assertions are not just engineering aesthetics. They are infrastructure that directly affects AI collaboration efficiency. Well-structured code has a lower takeover cost for AI. Otherwise, even a strong model gets pulled into a low-efficiency loop by messy context.
If you are maintaining legacy systems, adapting low-level drivers, debugging graphical interfaces, or want to use LLMs for real engineering troubleshooting, start from this checklist:
- Have the AI do a code review and output a problem list first;
- Fix only one minimal failure at a time;
- Every change must correspond to a reproducible symptom;
- Use logs and serial output to build observability;
- Refactor and optimize only after the program runs;
- Always keep rollback and version comparison ability.
8. Conclusion
“AI cleaning up after AI” sounds like a joke, but it points to a very real direction: the value of LLMs is not only generating from zero, but also taking over, diagnosing, and refining. In real development, the latter is often harder and more valuable.
Getting code to run is only the starting point. When code can be continuously understood, continuously verified, and continuously evolved, that is when engineering really lands.
