Debugging Legacy Code with LLMs: A Practical Playbook for AI-Assisted Takeover
This article walks through a real-world experiment in which a stronger LLM was handed a half-finished, non-running low-level graphics program generated by another coding tool and asked to act as reviewer, debugger, and refactorer at once. It explains why taking over legacy code is harder than generating from scratch, then details the first round of work (static review before any edits, adding observability, fixing a dangling buffer pointer across a display-mode switch, and correcting protocol identifier misuse) and the second round focused on input debouncing, timestamp-based frame pacing, explicit initialization, return-code checking, and structural cleanup without rewriting the architecture. It closes with a five-layer human-AI debugging framework, a list of common pitfalls, and the conclusion that review-first, evidence-driven, small-step regression, and clear boundaries make high-barrier domains such as low-level graphics, drivers, and firmware tractable.
1. Where the Problem Starts: Why Taking Over Legacy Code Is Harder Than Generating From Scratch
Writing a program from scratch and taking over an undocumented historical codebase that does not run are two tasks with completely different difficulty levels. The former only requires the model to generate code. The latter additionally demands three things: the ability to read someone else’s design intent, the ability to turn vague failure symptoms into verifiable hypotheses, and the restraint not to break existing structure across multiple rounds of edits.
The scenario in this practice was fairly representative: a low-level graphics program generated by an AI coding tool had been left in a half-finished state. The directory had been split into seven files, and the modular breakdown looked reasonably clean — entry point, main loop, game logic, rendering, and input handling each had its place — but the program as a whole would not run, and even the basic build environment could not be set up smoothly. Throwing it away would obviously be a waste, so the approach was to bring in a more capable model to “clean up the mess,” assigning it three roles at once: code reviewer, fault locator, and refactorer.
This kind of work has a specific name in engineering: legacy takeover. The difficulty is not in writing new code but in establishing credibility — you must first prove that you understand the old code before you have the right to modify it.
2. Round One Goal: From “Doesn’t Run” to “Runs”
The only acceptance criterion for the first round was that the program could be loaded, would not crash, and displayed the expected screen. Any optimization was deferred.
2.1 The First Step Is Always Static Review, Not Direct Edits
After receiving the code, the first instruction was not “fix it,” but:
Read through this code, describe its execution flow module by module,and list the issues you believe could prevent the program from runningproperly, ordered by severity. Do not modify any files for now.
This prompt contains three key constraints: restate the flow first (forcing the model to actually read the code instead of guessing), order by severity (which sets the sequence for subsequent fixes), and prohibit changes (avoiding a large-scale rewrite before understanding is established).
The model then inspected the entry function, main loop, game logic, rendering, and input handling module by module, and produced a list of issues covering handle lifecycles, incorrect protocol identifier references, buffer information becoming invalid after a mode switch, and missing return-code checks. The value of this list was not that everything on it was correct, but that it turned “an unknown pile of garbage” into “several hypotheses that can be verified one by one.”
Practice note: during the review phase, the model should be asked to distinguish “definite bugs” from “suspicious design choices” and to cite the file and function where the judgment comes from. Conclusions without location information cannot be verified and cannot be regression-tested.
2.2 Fault One: Exits Immediately at Startup, Root Cause in Buffer Information Lifecycle
On its first run, the program did start, printed the log showing the main loop had begun, and then exited immediately — a small step forward from not starting at all, but still a crash.
The way to handle it was to introduce observability rather than let the model keep guessing:
Add serial-port logging along the critical path, printing the returnstatus code and key pointer values at each step. Do not change thebusiness logic.
The logs showed the anomaly occurred after the graphics output protocol call. Further analysis revealed that the pointer to the information structure obtained when querying mode information pointed to memory that had already become invalid after the display mode was switched — that buffer is owned by the protocol implementation, and a mode switch rebuilds it, so the old pointer immediately becomes a dangling pointer. The fix was to query the frame buffer information once more after the mode was set, instead of reusing the result from before the switch.
A general rule can be abstracted here: any pointer or handle that is owned by an external component and whose lifetime is not controlled by the caller must not be reused across a state change. The same holds for device drivers, graphics stacks, and database connection handles.
2.3 Fault Two: Runs but Shows Nothing, Root Cause in Identifier Reference
Once the crash was resolved, the program entered the main loop but produced no graphical output. Combining the model’s judgment with the logs, the problem lay in an incorrect identifier reference used during the graphics output protocol location phase: within a framework, the same functional family often has multiple similar identifiers (one for installation, one for querying, one for a global variable) with different semantics. Using the wrong one may make location “succeed” while returning the wrong object, or may fail to find the handle at all.
The fix principle: use only the semantically unambiguous identifier for protocol location, and handle location failure explicitly instead of continuing.
/* Example: protocol location must check status and abort on failure rather than continue */status = locate_protocol(&graphics_protocol_guid, NULL, &gop);if (status != success || gop == NULL) {log_error("locate gop failed: %x", status);return status;}
2.4 Methodology Distilled From Round One
Abstracted from the process above, the first round was really four fixed actions: establish observability, turn symptoms into hypotheses, change one variable at a time, and regress immediately after each change. In most cases where “the AI can’t fix it,” the problem is not model capability but the fact that the human gave an instruction with no chain of evidence, such as “it doesn’t run, you fix it.”
3. Round Two Goal: Refinement, Optimization, and Maintainability
Getting it to run is only the starting point. The second round shifted the goal to quality and experience, with typical tasks including:
- Input handling: key debouncing and repeat-trigger suppression to avoid continuous jumps caused by long presses;
- Timing stability: replacing fixed delays with timestamp-based frame pacing to keep speed consistent across different refresh rates;
- Resources and boundaries: explicitly initializing all structures to avoid random behavior from uninitialized fields on the stack;
- Error paths: checking and reporting the return code of every external call, with silent ignoring prohibited;
- Structural convergence: lifting scattered magic numbers into constants and consolidating repeated logic into functions, while keeping the existing module boundaries intact.
The most important reminder in this round was to constrain the model from “rewriting the architecture along the way.” The following prompt was used to lock down the boundaries:
Make local changes only; keep the existing file layout and functionsignatures unchanged;for each change, explain the reason, the scope of impact, and how itwas verified;do not introduce new third-party dependencies.
4. A General Framework for Human-AI Collaborative Debugging
Abstracted from this practice into a transferable process, it can be summarized in five layers:
- Symptom layer: record logs, reproduction steps, environment, and versions completely; describing something as simply “not working” is prohibited.
- Hypothesis layer: have the model output a ranked list, annotating the verification cost of each hypothesis.
- Verification layer: change one thing at a time and confirm or refute it with a minimal experiment.
- Regression layer: run a fixed acceptance checklist at the end of each round to prevent fixing A while breaking B.
- Convergence layer: write verified conclusions into comments or documentation, forming an organizational asset.
With this process in place, the model’s value is significantly amplified; without it, model output often looks reasonable but cannot be put into practice.
5. Common Pitfalls
- Reusing pointers or handles owned by external components across state changes;
- Misusing identifiers or constants with similar semantics, compounded by missing failure handling;
- Only adding prints without changing structure, so log noise masks the real problem;
- Changing multiple places at once, which makes fault attribution fail;
- Ignoring return codes, so errors get swallowed;
- Overstepping into refactoring during the refinement phase and introducing new defects.
6. Conclusion
The real takeaway from this experiment — one model cleaning up after another — was not that a particular model is stronger, but that a repeatable human-AI collaboration paradigm was validated: review first, evidence-driven, small steps with regression, and clear boundaries. Once this process is established, high-barrier scenarios such as low-level graphics, drivers, and firmware can also be advanced reliably. Layer on top of that unified cloud-based build, logging, and monitoring/alerting capabilities, and centralize the environment, logs, and artifacts of each experiment, and a team can turn individual experience into reusable engineering standards.
