LLM-Assisted Code Repair and Verification: An Engineering Approach to Fixing Incomplete Code

    When existing code fails to compile or run, large language models (LLMs) can act as reviewers and debugging partners, but they cannot replace engineering verification. This article presents a reusable workflow for repairing incomplete code in firmware, driver, and GUI development. Using a graphical mini-game that goes from unrunnable to stable as a running example, it shows how to define acceptance criteria, build a problem map through structured review, and fix issues in priority order—from startup crashes and missing display caused by protocol configuration, to input and main-loop stability. It then covers a second optimization round focused on stability, rendering performance, logging, and regression testing. Readers will learn how to place an LLM's analysis inside a closed loop of compilation, runtime logs, and testing to turn "it looks like it runs" into code that is genuinely deliverable.

    LLM-Assisted Code Repair and Verification: An Engineering Approach to Fixing Incomplete Code

    1. Background: When the Code Exists but Won’t Run

    In firmware development, driver debugging, and GUI development, a common and awkward situation arises: the code does not start from scratch. Instead, an automated tool or a previous generation pass has left behind a skeleton that looks complete. The directory structure is clear, the modules are reasonably separated, and files for rendering, input, and game logic may even be present—yet compilation and runtime repeatedly fail.

    These scenarios place higher demands on developers. Compared with writing features from scratch, taking over incomplete code requires three capabilities at once: understanding the existing structure, locating runtime anomalies, and completing fixes without breaking the architecture. Large language models and AI coding assistants are well suited to the roles of “code reviewer” and “debugging collaborator,” but they cannot replace engineering verification. A truly reliable process places the LLM’s analysis inside a closed loop made of compilation, runtime, logs, and regression tests.

    This article uses “a graphical mini-game in a firmware environment going from unrunnable to stable” as its thread and abstracts a general, LLM-assisted repair methodology from it. The article does not compare specific products; instead, it focuses on: when code already exists but won’t run, how to use an LLM to complete review, diagnosis, repair, and optimization.

    2. Task Goals and Acceptance Criteria

    Before making any changes, you must first define the acceptance criteria. Otherwise, an LLM tends to produce changes that “look correct” but cannot pass real runtime verification.

    An executable acceptance standard can be divided into four layers:

    1. Compilation passes: the code compiles in the target environment without relying on extra toolchains or non-reproducible environments.
    2. Startup passes: the program loads into the firmware runtime without immediately exiting, crashing, or deadlocking.
    3. Graphical output passes: the program enters the main loop and displays the game screen stably.
    4. Interaction passes: input events are captured correctly, game state updates with input, and abnormal exits do not damage the system.

    With this standard in place, every subsequent fix can map to a clear goal. For example, if the program compiles but exits as soon as it starts, the problem is most likely in initialization or protocol calls; if it enters the main loop but shows a black screen, the problem lies in the display protocol or frame-buffer acquisition.

    3. First Round of Repair: From “Compiles” to “Runs”

    3.1 Code Review: Build a Problem Map First

    When taking over incomplete code, the first step is not to modify code directly, but to have the LLM perform a structured review. The review targets should include:

    • Entry function: whether necessary initialization is completed;
    • Main loop: whether there is infinite blocking or abnormal exit conditions;
    • Game logic: whether state updates are complete and boundary checks are correct;
    • Rendering module: whether a valid frame buffer is obtained and whether mode switching is handled;
    • Input handling: whether it relies on blocking calls, and whether there are timeouts and default values;
    • Resource management: whether handles, buffers, or protocol objects are left unreleased.

    At this stage, the value of the LLM is to quickly generate a “problem map.” It may not locate every root cause in one pass, but it can rank suspicious points by priority. For example, it might identify issues such as:

    • a graphics protocol handle not validated before use;
    • stale mode information reused after a mode change;
    • a buffer pointer that may point to an invalid address;
    • missing error-code handling in the main loop;
    • an input module that may block system startup.

    Not all of these are necessarily the final root cause, but together they form the candidate set for subsequent debugging.

    3.2 First Problem: Crash on Startup

    After compilation passes, the first run shows the pattern “startup—a few log lines printed—exit.” Such problems are usually not logic errors but lifecycle errors: an object is acquired during initialization but becomes invalid after the state changes, and the program keeps using the old pointer.

    Serial logs can reveal how far the program gets before stopping. If the logs show that the program has not yet reached the main loop and that the exit happens after mode setting, you can focus your attention on the graphics protocol and display mode.

    A common repair approach is: after setting the display mode, re-query the current mode information and re-acquire the frame-buffer address. Pseudocode:

    1. graphic_protocol.query_mode(&mode_info)
    2. graphic_protocol.set_mode(mode_info.mode)
    3. // Re-acquire after the state transition
    4. graphic_protocol.query_mode(&mode_info)
    5. frame_buffer = mode_info.frame_buffer

    The key to this kind of fix is not the number of lines, but the low-level development principle it embodies: when the system state changes, previously saved handles, pointers, or cached information may no longer be valid. If an LLM lacks this domain constraint, it may keep the original pointer; therefore, the developer needs to write the requirement “resources must be re-acquired after a low-level state change” explicitly into the repair prompt.

    3.3 Second Problem: No Display Due to Protocol Configuration Errors

    The program no longer exits, but the screen is still blank. At this point, the problem typically shifts from “crash” to “resource acquisition failure.” In firmware graphics development, the graphics output protocol is a common dependency, but the environment may contain multiple display-related protocols or identifier definitions. If the program selects the wrong one, it may fail to obtain a usable graphics output interface.

    An LLM can surface such risks through static inspection, but truly locating the cause still requires runtime verification. The recommended repair steps are:

    1. Check the return value of protocol location, distinguishing among “protocol not found,” “protocol exists but mode is invalid,” and “frame buffer unavailable”;
    2. Log the protocol-location result and the number of modes, rather than only “success” or “failure”;
    3. If the graphics protocol is located but rendering fails, prioritize checking the mode number and resolution information;
    4. If protocol location fails, check whether the corresponding driver is loaded in the runtime environment and whether the protocol identifiers match.

    Pseudocode:

    1. status = locate_graphic_output_protocol(&protocol)
    2. if status != SUCCESS:
    3. log_error("graphic protocol not found")
    4. return status
    5. status = protocol.query_mode(&mode_info)
    6. if status != SUCCESS or mode_info == NULL:
    7. log_error("query mode failed")
    8. return status

    This step demonstrates the advantage of LLM-assisted debugging: it can generate candidate explanations from error messages and help the developer break a vague symptom like “black screen” into several smaller, verifiable problems.

    3.4 Third Problem: Input and Main-Loop Stability

    Once graphics can be displayed, interaction must be checked. Common issues include:

    • input reading uses a blocking approach, causing the main loop to stall;
    • key states have no debouncing, producing continuous triggering;
    • the game loop has no fixed frame rate, causing logic updates to run too fast or too slow;
    • abnormal exit paths do not release resources;
    • boundary-condition checks are missing, such as blocks going out of bounds or collision detection being skipped.

    These problems often do not surface on the first launch, so the second round of repair must focus on stability and maintainability.

    4. Second Round of Optimization: From “Runs” to “Deliverable”

    4.1 Stability Optimization

    A stably running program must not only “avoid crashing” but also remain controllable under abnormal input. A state machine can be introduced to manage the game lifecycle—for example, initialization, running, paused, ended, and exiting. Each state has a clear responsibility, avoiding a main loop cluttered with condition checks.

    A schematic structure:

    1. while is_running:
    2. handle_input()
    3. update_game_logic()
    4. render_frame()

    On this basis, watchdog-style protection can be added: if a stage takes too long, log a warning; if input events remain abnormal, enter a safe-exit flow. For firmware programs, resource release is especially important. Even if the program ultimately exits, it should ensure that handles, memory, and protocol references are cleaned up correctly to avoid affecting the host environment.

    4.2 Performance and Rendering Optimization

    Graphical mini-games usually do not need a complex rendering pipeline, but frame-rate stability still deserves attention. Common optimization points include:

    • use a fixed time step to update logic, avoiding game-speed changes caused by frame-rate fluctuation;
    • reduce per-frame repeated computation, such as caching a static background;
    • limit the drawing region to the valid screen area to avoid out-of-bounds writes;
    • throttle input sampling to avoid jitter caused by high-frequency interrupts.

    These methods do not depend on any specific platform capability; they are general optimization ideas for graphical programs.

    4.3 Logging and Observability

    In low-level debugging, logging is the most important observation tool. It is recommended to divide logs into three categories:

    • Startup logs: record the loading phase, protocol location, and mode-setting results;
    • Runtime logs: record frame-loop counts, input events, and abnormal branches;
    • Error logs: record failure reasons, error codes, and context state.

    An LLM can generate further analysis from the logs, but the prerequisite is to specify: “do not only change the code—also add verifiable logs.” This significantly reduces repeated trial and error.

    4.4 Testing and Regression

    After an LLM repairs the code, you must verify through testing rather than trusting the model’s own description. The recommended test path includes:

    1. Compilation test: ensure there are no compilation errors;
    2. Startup test: confirm the program does not exit immediately;
    3. Display test: confirm the screen can be output normally;
    4. Input test: confirm key operations can change the game state;
    5. Exception test: simulate no-graphics environments, missing input, or unsupported modes;
    6. Regression test: after fixing a new problem, confirm that old functionality is not broken.

    If conditions allow, tests can be fixed into scripts or test cases so that every change is verified automatically. This is the key to moving AI-assisted development from “conversational patching” toward “engineering-grade delivery.”

    5. Engineering Experience: Strengths and Boundaries of LLM-Assisted Repair

    From this abstracted practice, a few clear conclusions can be drawn.

    First, LLMs are good at quickly reading code structure and generating a candidate list of problems. For modular but unrunnable code, they can rapidly identify the relationships among the entry point, main loop, rendering, and input.

    Second, LLMs are good at proposing hypotheses from logs and error symptoms. However, low-level issues such as pointer lifecycles, protocol state transitions, and firmware loading order often require developers to supply domain knowledge.

    Third, LLMs are not suited to freely improvising without acceptance criteria. Without constraints like “it must run,” “the frame buffer must be re-acquired,” or “error codes must be output,” a model may generate code that is syntactically correct but behaviorally unstable.

    Fourth, the engineering closed loop matters more than a single generation. Compilation, runtime, serial logs, serial monitoring, and regression verification—none of these links can be missing.

    Therefore, a more reasonable way to use an LLM is not to treat it as a one-shot answer generator, but as a continuously collaborating debugging partner: the developer defines the environment, constraints, and acceptance criteria, while the model handles rapid analysis, generates modification suggestions, and contributes test ideas.

    6. A Reusable Practice Workflow

    To reproduce a similar approach in a real project, you can follow this workflow:

    1. Prepare a minimal reproduction environment: place the code in a clean directory and ensure dependencies are reproducible.
    2. Define the input materials: provide the model with the code structure, the compilation method, the runtime environment, and the current error symptoms.
    3. Review first, avoid large changes: ask the model to list risk points rather than immediately rewriting all the code.
    4. Fix by priority: first resolve crashes and startup failures, then handle display and input, and optimize last.
    5. Verify after each fix: use logs to confirm whether the fix actually took effect.
    6. Keep a change record: document each problem’s symptoms, causes, fixes, and verification results.
    7. Refactor and optimize last: once functionality is stable, then handle code style, logging standards, and resource management.

    This workflow applies not only to graphical programs but also to complex low-level development scenarios such as firmware drivers, embedded modules, and foundational toolchain components.

    7. Conclusion

    The value of LLM-assisted development lies not in replacing the developer, but in shortening the time from “discovering a problem” to “forming a hypothesis.” When code already exists but won’t run, the real difficulty is judging whether the problem lies in the lifecycle, protocol configuration, input blocking, or rendering logic. LLMs can significantly lower analysis costs, but the final answer must always be verified through compilation, runtime, logs, and testing.

    In low-level development and firmware scenarios, caution is especially important: a seemingly simple pointer fix may determine whether the entire system remains stable, and the choice of a protocol identifier may decide whether graphical output is usable at all. Placing an LLM’s generation capability inside an engineering process is what moves AI-assisted development from “looks like it runs” to “genuinely deliverable.”