Refactoring Legacy Vehicle Firmware: A Low-Cost Multi-Agent Workflow

    This article explains how to refactor the low-level code of a 30-year-old vehicle control system using a coordinated multi-agent workflow on a budget of roughly fifteen dollars. It covers how to break a vague maintenance request into behavior, interface, implementation, and verification layers; how to schedule agents across low-, mid-, and high-cost model tiers with hard call limits; how to build layered context packages from symbol tables, disassembly snippets, and domain dictionaries; and the mandatory safety boundaries, three-layer regression testing, and common pitfalls such as context pollution, over-refactoring, hallucinated constants, and runaway budgets. The goal is a repeatable engineering process, not letting a model write code on your behalf.

    1. Background: Why Low-Level Code in a 30-Year-Old Vehicle Is Hard to Change

    A vehicle that has been in service for more than thirty years usually has electronic control units that were never designed for modern development workflows. The firmware may be a mix of assembly and early high-level languages, variable names are length-limited abbreviations, comments are missing or out of sync with the implementation, the compiler toolchain has long been unmaintained, and the flashing interface may be reduced to pin headers and a homemade adapter board. Adding a feature or fixing a defect in such a system traditionally means finding paper schematics, hiring an engineer familiar with the platform, reverse-engineering calibration parameters, and validating repeatedly on the actual vehicle — a cycle measured in months and costs measured in tens of thousands of yuan.

    The new variable in the last couple of years is that AI coding tools can now handle a substantial share of code reading, refactoring, and test generation. Multiple agents dividing the work — one for retrieval and localization, one for implementation and refactoring, one for review and test design — can run a complete pipeline on a very small budget. This article focuses on the engineering method behind that pipeline, not on any specific product.

    2. Overall Approach: Translating “Fixing a Car” into a Computable Engineering Task

    Agents do not handle vague goals well. Whether the refactor succeeds depends first on the quality of the task definition. It helps to split the original request into four layers:

    1. Behavior layer: the expected externally observable behavior, for example “limit peak output torque when reversing at low speed.”
    2. Interface layer: which signals, registers, or calibration constants are involved, and what the read/write timing constraints are.
    3. Implementation layer: which module and which functions the change lands in, and whether new lookup data is needed.
    4. Verification layer: how to prove on a test bench or in a closed area that the change is correct and can be rolled back.

    Only when all four layers are written out clearly is the agent output reviewable. In practice, the most common cause of failure is not insufficient model capability but requirements that stop at the behavior layer, producing code that looks reasonable yet cannot run on a real controller.

    3. Agent Orchestration Under a Cost Constraint

    A budget on the order of fifteen dollars means you cannot call large models without restraint. A workable strategy is tiered scheduling:

    • Cheap stage: use a low-cost text model for log categorization, candidate variable names, and draft comment completion.
    • Medium stage: use a mid-tier model for cross-file call chain mapping and refactoring drafts.
    • Expensive stage: call a high-capability model only at key decision points (memory layout changes, timing-sensitive logic rewrites), and require structured conclusions rather than large blocks of code.

    Illustrative orchestration pseudocode:

    1. plan = {
    2. "tasks": [
    3. {"id": "T1", "role": "scanner", "tier": "low", "goal": "List symbols and addresses related to torque limiting"},
    4. {"id": "T2", "role": "mapper", "tier": "mid", "goal": "Reconstruct the call chain and interrupt context"},
    5. {"id": "T3", "role": "coder", "tier": "mid", "goal": "Produce a minimal diff and a rollback plan"},
    6. {"id": "T4", "role": "reviewer", "tier": "high", "goal": "Review timing and memory safety, output a risk list"},
    7. {"id": "T5", "role": "tester", "tier": "low", "goal": "Generate test bench cases and assertions"}
    8. ],
    9. "budget": {"max_calls": 120, "hard_stop": True}
    10. }

    Three engineering constraints matter: first, set a hard call limit and stop when the budget is exceeded, reporting what has been completed; second, persist all intermediate artifacts to files to avoid repeatedly feeding long contexts; third, allow each task to output only one format (JSON or unified diff) so it can be validated automatically.

    4. Context Engineering: Making Agents “Understand” Legacy Code

    Understanding legacy code costs far more than writing new code. An effective approach is to build a layered context package:

    • Symbol table: address, length, type, inferred semantics, with a confidence score.
    • Disassembly snippets: keep only the functions relevant to the current task and trim unrelated sections.
    • Domain dictionary: map abbreviations to readable names, for example expanding a three-letter abbreviation into “torque upper limit.”
    • Change constraints: state explicitly which memory regions must not be touched and which interrupt service times must not be extended.

    It is worth stressing that all semantic inferences should carry a confidence score and be reviewed by a human. Writing low-confidence inferences directly into control logic is the most dangerous operation in this kind of project.

    5. Safety and Compliance Boundaries (Not Optional)

    For a real vehicle or any physical actuator, the risk of a code change is at the level of human life. The following red lines must be established:

    • Close the loop in simulation or on a test bench first; never flash a first change directly onto a real vehicle.
    • Keep the original firmware image and its checksum to guarantee one-click rollback.
    • Write-protect the changed region; do not flash until static checks and regression tests pass.
    • Logic involving braking, steering, airbags, and similar systems is out of scope for automated refactoring and must be handled by a qualified professional organization.
    • Keep an audit log throughout: who changed what and when, and which requirement it was based on.

    6. Verification: Three Layers of Regression

    The first layer is static verification: zero new compiler warnings, comparison of stack depth and memory usage, and cycle estimation for critical paths. The second layer is behavioral verification: replay input stimuli and compare output waveforms before and after the change, point by point against a tolerance. The third layer is environmental verification: cover boundary conditions such as high and low temperature, voltage dips, and communication frame loss on the test bench. Only when all three layers are green is closed-area testing on a real vehicle allowed.

    7. Common Pitfalls and How to Avoid Them

    • Context pollution: stuffing unrelated modules into the context makes the model invent functions that do not exist. Avoid it by trimming context per task.
    • Over-refactoring: agents tend to “optimize along the way” and break existing timing. Avoid it by requiring a minimal diff.
    • Hallucinated constants: plausible-looking calibration values get generated. Avoid it by requiring every constant to be traceable to the original data table.
    • Budget overrun: agents wait on each other in a loop. Avoid it with timeouts and a maximum number of rounds.

    8. Conclusion

    Refactoring the low-level code of old equipment on a very small budget is not about letting a model write code for you. It is about structuring engineering knowledge so agents can take on verifiable work — retrieval, drafts, and test generation — within controlled boundaries. When tasks are clearly layered, context is traceable, verification closes across three layers, and rollback is always available, this kind of refactoring becomes engineering-repeatable. If you need to host code repositories, build artifacts, and audit logs, general-purpose cloud capabilities such as object storage, container platforms, and log monitoring with alerting can be used to build a reproducible pipeline, turning a one-off attempt into a long-term asset.