Debugging Legacy Code with LLMs: A Practical Workflow for AI Coding Agents
This article walks through a practical workflow for using large language models to debug existing legacy code rather than generate new projects from scratch. It covers a structured read-only review before any edits, adding observability to diagnose silent exits and black screens, fixing handle and buffer lifecycle bugs, and refining stability, resource management, portability, and maintainability. It closes with four reusable principles—evidence first, small verified steps, constrained output, and acceptance criteria defined upfront—for turning AI-assisted legacy maintenance into a repeatable engineering process.
1. The Starting Point: Why Taking Over a Mess Beats Generating From Scratch
A demo video of a small game generated from scratch looks impressive, but real engineering work more often looks like this: the code already exists, the structure seems reasonable, and yet it does not run. Fixing this kind of legacy code is exactly where the capabilities of large language models tend to fall short—it requires understanding unfamiliar code, an unfamiliar runtime environment, and vague failure symptoms all at once.
A typical session unfolded like this: first, an AI coding tool was asked to implement a small graphical game. After several hours it still had not set up a working build environment and produced no runnable program. It did, however, leave behind seven source files with a clear modular structure—entry point, main loop, logic, rendering, and input each in their own place. This “looks right but does not run” output became the input for another large model to take over debugging.
The point of this comparison is not that one tool is strong and another is weak. It is this: the completeness of generated code is not the same as whether the project actually runs. To judge the real capability of a coding agent, look at whether its troubleshooting path is reliable when evidence is thin, symptoms are vague, and the environment is unfamiliar.
2. Round One: From “Looks Correct” to “Actually Runs”
The first step in taking over is not to change code, but to build an understanding of it.
1. Do a Structured Review First, Not Immediate Edits
Put the untouched code into a new working directory. The first instruction should be extremely restrained:
Review this code and list the issues that could prevent it from running,ordered by risk from high to low. For each issue, explain the basis foryour judgment (file, function, call chain).Do not modify the code.
The “do not modify” constraint is critical. Otherwise the model tends to edit as it reads, making it impossible to later separate “original problems” from “newly introduced problems.” Within a few minutes, the resulting list typically covers: entry point and dependency initialization order, exit conditions of the main loop, acquisition and release of graphics protocol handles, the polling method for input events, and cache invalidation after mode switches.
2. Symptom One: Exits Immediately on Startup
The program compiles and starts, prints the log showing the main loop has begun, and then exits right away. This kind of “silent crash” is especially common in bare-metal or firmware environments, because exceptions are often swallowed by the layer above.
The effective approach is to add observability rather than make the model guess:
Add serial logs before and after key calls, outputting return values,handles, pointers, and status codes; locate the call between the lastsuccessful print and the first anomaly.
The logs narrowed the range to just after the graphics output protocol mode query. Further analysis showed that the information structure returned by the mode query was no longer valid after the mode-set call—the memory the pointer referred to had been overwritten, so reading frame buffer information afterward returned dirty data. The fix was to query the frame buffer information again after the mode is set, rather than reuse the old pointer. This kind of “handle/buffer lifecycle” issue is a frequent defect in resource-management code.
3. Symptom Two: It Runs but the Screen Is Black
Once the crash was resolved, the process stayed stable but produced no output on screen. At this point the code logic was working, and the problem came down to protocol identification: the firmware environment contains multiple graphics-related protocol identifiers, and using the wrong one means no usable graphics output interface can be obtained.
The recommended troubleshooting order is fixed: confirm the protocol is installed → confirm the identifier matches the current firmware specification → confirm there is a fallback path when location fails. The corresponding defensive code looks roughly like this:
EFI_STATUS Status;EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop = NULL;Status = gBS->LocateProtocol(&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&Gop);if (EFI_ERROR(Status) || Gop == NULL) {// Log the error code and degrade gracefully: print a notice over serial// to avoid silent failurereturn Status;}
At this point the program went from “not runnable” to “runnable but with functionality still to be verified,” which met the acceptance criteria for round one: compiles, starts, runs continuously, and failures are observable.
3. Round Two: Refinement and Experience Optimization
Once it runs, the work moves into refinement. The focus of this round shifts from “fixing bugs” to “improving quality,” and it is best to proceed along four dimensions:
- Stability: Decouple frame rate from input polling so logic speed is not tied to refresh speed; introduce time-difference accumulation for fixed-step updates.
- Resource management: Define the allocation and release boundaries for every resource; prohibit both double frees and missed frees.
- Portability: Extract resolution, color format, and key mappings into configuration to abstract away differences between firmware and display modes.
- Maintainability: Add unit tests for the pure-logic parts so that collision, scoring, and boundary-bounce rules can be verified without a graphics environment.
A representative fixed-step main loop:
while (running) {UINT64 now = ReadTimestamp();Accum += (now - Last) * Scale;Last = now;while (Accum >= Step) {Update(&Game); // Pure logic, independently testableAccum -= Step;}Render(&Game); // Responsible only for drawingPollInput(&Game); // Input only changes state, not the screen directly}
4. Methodology: Four Principles for Using LLMs in Maintenance Scenarios
- Evidence first: Add logs and assertions before letting the model reason; debugging without observability is just guessing.
- Small, verified steps: Fix one class of problem at a time, run immediately after each change, and keep a clean state you can roll back to.
- Constrain the output: Specify “analyze only, do not change,” “modify only one file,” and “always provide the basis for your judgment.” This significantly reduces the chance of going off track.
- Define acceptance criteria upfront: Write down the conditions for “runnable” before starting, to avoid getting stuck in a loop of “it looks done.”
If this workflow is run in the cloud, general-purpose capabilities can amplify the benefits: a container platform can provide a consistent and reproducible build environment, object storage can hold snapshots of code and artifacts, a logging service can centrally collect serial and runtime output, and monitoring and alerting can track the failure rate and duration of long-running tasks. Baidu AI Cloud provides exactly these general-purpose capabilities in this kind of development pipeline, helping teams turn “AI taking over legacy code” from an individual skill into a repeatable engineering process.
The final conclusion is this: to measure a coding agent, do not look only at whether it can quickly generate a nice piece of code. Look at whether it can build understanding in an unfamiliar project, add observability, and converge on problems step by step based on evidence. Only by solidifying this method is there real room to improve the maintenance efficiency of legacy systems.
