From Fixing Bugs to Building Systems: Multi-Agent Engineering for Long-Horizon Coding Tasks
As coding models shift from single-turn assistance to multi-stage, cross-file execution, engineering practices must change with them. This article examines four actionable questions: why long-horizon tasks fail, how to organize multi-agent orchestration, how to design verifiability, and how to govern cost through reasoning-effort tiering. It also covers how to read benchmark scores correctly, verifiability patterns by task type, case abstractions for building a system from scratch and migrating a production service across languages, the human role in defining authorization boundaries, a phased rollout roadmap with metrics, and common anti-patterns.
When discussing the new generation of coding models, most of the attention has shifted from “single-turn accuracy” to “long-horizon task completion.” This reflects a shift in the form of the capability itself: models are no longer just tools that autocomplete code snippets, but task executors that can take on multi-stage, cross-file work requiring self-verification and self-correction. The engineering methods that go with this must change too—from “humans write code, models assist” to “humans set goals and acceptance criteria, models execute in bulk.” This article revolves around four actionable questions: why long tasks fail, how multi-agent orchestration should be organized, how verifiability should be designed, and how cost can be governed under reasoning-effort tiering.
1. Why “long tasks” are the new dividing line
Short tasks can succeed by luck: one generation, one compile, one glance at the answer. The difficulty of long-horizon tasks lies in state accumulation. A development task that spans days typically contains dozens to hundreds of decision points, and each one can introduce a deviation—deviations that later steps inherit as established fact. The three failure modes the industry often cites are essentially all long-task problems:
- Context pollution: erroneous assumptions from early stages linger in the context, and subsequent reasoning is repeatedly misled by them;
- Goal drift: once a task is decomposed to some level, the sub-task’s goal is no longer equivalent to the original goal;
- Missing verification: the model produces an implementation that “looks reasonable,” but no one—and no automation—judges whether it is correct.
So whether a coding model is suited to long tasks cannot be measured by static benchmark scores alone. It comes down to three things: whether task decomposition is sound, whether the outputs can be automatically verified, and whether errors can be located and rolled back.
2. How to read benchmark scores correctly
The three common types of benchmarks each have clear boundaries:
- End-to-end coding benchmarks: given a natural-language requirement, they judge whether the generated program passes hidden tests. They measure the ability to go “from zero to runnable,” but the problems are usually limited in scale and struggle to reflect the difficulty of multi-file refactoring.
- Repository-level software engineering benchmarks: given a real codebase and a problem description, they require the model to locate, modify, and make existing tests pass. This is closer to daily work, but still does not cover “sustained iteration across weeks.”
- Composite capability indices: aggregated from multiple sub-items (scientific reasoning, knowledge understanding, coding, instruction following, and so on). Their value lies in fast side-by-side comparison, but aggregation hides weak spots—a model that leads by a few points overall may clearly lag in one specific sub-capability.
It is worth noting that generational improvements of a few percentage points to just over ten percentage points are common, and such numbers should be treated as trend signals rather than capability guarantees. A more valuable practice for engineering teams is to build a private benchmark set: select 30–100 real tasks with clearly defined completion conditions from historical tickets, with fixed inputs, fixed acceptance scripts, and a fixed budget cap, then run regular regressions. The core metric is not “can it do it” but “first-pass rate” and “manual rework rate.”
3. Multi-agent orchestration: from single-point execution to distributed collaboration
When a model can reliably complete sub-tasks, the most direct way to increase throughput is parallel decomposition. A typical three-layer structure looks like this:
# Illustrative pseudocode: the orchestration layer handles decomposition, dispatch, aggregation, and arbitrationdef run_project(spec, budget, verifier):plan = planner(decompose(spec)) # generate task tree + interface contractsshared = SharedState(spec, plan) # requirements, interfaces, board, artifact indexwhile pending := shared.next_ready(): # dispatch only tasks whose dependencies are metbatch = [worker(task, shared) for task in pending[:PARALLEL]]results = gather(batch, budget_per_task=budget)shared.commit(results) # commit artifacts + acceptance evidence togethershared.merge_check() # interface drift and conflicts surface herereturn integrator(shared), verifier(shared)
The key to this structure is not “spin up many agents” but three constraints:
- Contracts first: produce contracts for data structures and function signatures before parallel implementation. Parallelism without contracts amounts to letting multiple agents each invent their own protocol, and the integration phase will inevitably require rework.
- Single source of truth: requirements, backlogs, and the index of completed artifacts must converge in one place (a file or a lightweight service), to avoid state forking when each agent holds its own copy.
- Explicit arbitration: conflicts are not resolved at the worker layer but adjudicated centrally by the orchestration layer. Letting sub-agents negotiate among themselves introduces unpredictable communication costs and deadlock risk.
4. Verifiability design: the foundation of long tasks
Whether a long task converges depends on whether each step has an acceptance condition that can be automatically judged. The engineering practice is “acceptance first”: determine how correctness will be judged before writing the implementation.
| Task type | Acceptance method | Notes |
|---|---|---|
| Interfaces/services | Contract tests + successful compile | Contract tests prevent signature drift |
| Algorithms/functions | Unit tests + property tests | Property tests cover generated inputs |
| Legacy migration | Behavioral baseline snapshot + traffic replay | The gold standard for migration correctness |
| Frontend/interaction | Snapshot comparison + critical-path automation | Dual verification of visuals and flows |
| System-level projects | End-to-end bootable + smoke checks | See the next section |
Four guardrails come with this. First, checkpoints: commit once each verifiable unit is complete, so a failure can roll back to the last checkpoint rather than starting over. Second, minimal failing cases: any failure must be compressed into a reproducible minimal input, otherwise subsequent fixes are just guesses. Third, context layering: manage “current task context / project memory (conventions and decisions) / full index” separately, using retrieval instead of full injection. Fourth, least privilege: run the execution environment in a sandbox, inject credentials on the platform side rather than writing them into the context, and whitelist network access on demand.
5. Case abstraction: from an empty directory to a bootable system
“Build an operating system from an empty folder” is a compelling case because it possesses an acceptance verifier that is extremely hard to cheat: it can boot on an emulator or real hardware and respond to external events such as disk, keyboard, and network. This is completely different from “it compiles”—compilation only checks syntax and types, while booting requires the initialization order, interrupt handling, and memory layout all to be self-consistent.
These kinds of projects follow a layered bootstrapping approach:
- Skeleton: bootloader → enter protected mode → minimal kernel initialization → serial output. The acceptance criterion is “see one line of output.”
- Memory and abstractions: physical/virtual memory management, processes and scheduling. The acceptance criterion is “create and switch between two tasks.”
- Storage stack: block device driver → file system → file read/write. The acceptance criterion is “data still exists after reboot.”
- Interaction: interrupts → keyboard input → display output → simple windows and login.
- Networking: link layer → protocol stack → one accessible service.
- Delivery form: installation media and installer.
Each layer ends with an independent baseline test that can run automatically before moving to the next. This rhythm of “skeleton first, add capability layer by layer, verify each layer” applies equally to any medium-to-large project built from scratch—only the verifier changes to compilation, tests, and end-to-end scenarios.
6. Case abstraction: production system cross-language migration
Another kind of case is migrating an online service from a dynamic scripting language to a system-level compiled language, with startup time improving by an order of magnitude after the migration. The risk in this kind of change lies not in “writing code” but in “behavioral equivalence,” and there are four reusable paths:
- Build a baseline first: record real requests and responses, capture the latency distribution of critical paths, and form a replayable input set.
- Run dual tracks in parallel: run the old and new implementations simultaneously, compare result differences with shadow traffic, and drive fixes with the difference list.
- Gradual rollout: increase traffic by percentage step by step, with a clear rollback trigger at each step.
- Startup-path optimization: convert synchronous blocking at startup into lazy initialization, move heavy computation to compile time or build time, parallelize mutually independent initializations, and reduce network and disk round trips during startup. The payoff from startup-time optimization depends heavily on where the problems lie in the original implementation, so the magnitude must be measured and confirmed rather than assumed as a fixed multiple.
A related fact is worth noting: when the vast majority of merged changes in an engineering team’s core codebase are generated by models, the bottleneck shifts from “writing” to “reviewing.” This means the review process must be reworked—automated checks (formatting, static analysis, unit tests, contract tests, security scans) must come first, and humans handle only what automation cannot cover: design intent, boundary semantics, security impact, and maintainability.
7. Cost governance: reasoning-effort tiering and budget control
The cost structure of long tasks is often underestimated. Total cost is roughly token consumption multiplied by unit price, and token consumption is jointly determined by context length, number of iterations, and number of retries, growing superlinearly—a task that fails twice may cost several times more than one that succeeds on the first try. There are five actionable governance measures:
# Illustrative pseudocode: route reasoning tier by task risk and set budget circuit breakersdef dispatch(task, ctx):if task.risk == "critical": # critical path, security-relatedreturn solve(task, ctx, effort="max", budget_usd=ctx.cap * 0.4)if verifier.available(task): # mechanical tasks with automatic acceptancereturn solve(task, ctx, effort="low", budget_usd=ctx.cap * 0.05)return solve(task, ctx, effort="medium", budget_usd=ctx.cap * 0.2)
- Model and tier layering: use low reasoning effort or smaller models for mechanical sub-tasks (adding tests, fixing formatting, adding logs); reserve the highest tier for architecture decisions and hard debugging.
- Context trimming: replace full-file injection with retrieval and summarization; look back at historical rounds on demand rather than carrying everything.
- Cache reuse: cache repeated calls with the same prefix and reusable intermediate artifacts to avoid paying twice.
- Budget circuit breakers: set token and cost caps for each project and each sub-task, and automatically downgrade or hand off to humans when a cap is exceeded, rather than letting the agent retry indefinitely.
- Parallelism constraints: parallelism compresses wall-clock time but also raises peak cost, so set it by delivery deadline rather than by spare compute.
One important lesson: when effects are similar, “lowering the reasoning tier + stricter acceptance” is often more cost-effective than “switching to a stronger model,” because the extra money usually goes to redundant self-reflection rather than effective progress.
8. The human role: authorization boundaries and governing over-conservatism
In practice, developers report that more capable models are sometimes “over-responsible”: repeatedly confirming, refusing to execute inherently reasonable tasks, or judging risk scope too broadly. This is not a model defect but a sign that authorization boundaries have not been expressed explicitly. A workable approach is to maintain two lists:
- Autonomous execution list: change types that can be committed automatically (adding tests, fixing lint, updating docs, local refactoring with all tests green).
- Must-ask list: changes involving permissions and security configuration, data deletion or migration, production environment changes, cross-module interface changes, and dependency upgrades.
At the same time, require the agent to output confidence and evidence: which files it relied on, which commands it ran, and which outputs it saw. Conclusions without an evidence chain are not accepted. This is both risk control and the basis for later auditing.
9. Phased rollout roadmap and metrics
| Phase | Goal | Key actions | Exit condition |
|---|---|---|---|
| 0 Infrastructure | Make correctness judgeable | Complete CI, unit tests, contract tests, static checks, observability | Trunk commits automatically yield a pass/fail conclusion |
| 1 Single-agent pilot | Validate payoff | Limit scope to adding tests, fixing small bugs, writing docs | Stable data on first-pass rate and rework rate |
| 2 Multi-agent pipeline | Increase throughput | Build an implement–test–review three-stage pipeline, contracts first | Integration conflicts can be detected and quickly fixed |
| 3 Multi-day projects | Take on big goals | Checkpoints, budget circuit breakers, human gates per stage | Deliverables pass end-to-end acceptance |
Metrics to track continuously: task first-pass rate, share of manual rework hours, average cost per task, average delivery cycle, and defect escape rate (the number of problems found by users after release). Among these, “defect escape rate” is the only lagging indicator, yet also the only one that cannot be optimized away—the first four can all be made to “improve” by making the agent more conservative, while only this one reflects true quality.
10. Common anti-patterns
- Tests changed to green: agents tend to modify assertions rather than fix the implementation. Countermeasure: make test files read-only for implementation tasks, and review test changes separately.
- Context pollution: erroneous assumptions get inherited. Countermeasure: restate the task and constraints at each checkpoint, and periodically restart with a clean context.
- Over-refactoring: rewriting unrelated modules along the way. Countermeasure: minimize change scope and revert all unrelated changes.
- Hallucinated dependencies and interfaces: calling library functions or internal APIs that do not exist. Countermeasure: enforce “read the code before writing code” and whitelist dependencies.
- No one to review: batch output outpaces review capacity. Countermeasure: commit in small steps and split batch changes into minimal units that can be reviewed independently.
Conclusion
The biggest change brought by the new generation of coding models is not “writing faster” but “working continuously for longer.” This requires the engineering side to fill in three things at once: automatically judgeable acceptance conditions, structured multi-agent orchestration with conflict arbitration, and reasoning-effort and budget governance tiered by risk. When these three are in place, thousand-agent collaboration and multi-day tasks move from demo to deliverable; without any one of them, a long task will quietly fail on some hidden assumption. The ceiling of capability is set by the model; whether that ceiling can be used safely is decided by engineering discipline.
