Multi-Agent Orchestration for Long-Running Software Engineering: Practical Approaches
This article explains how to apply multi-agent orchestration to long-running software engineering tasks that run for hours or days without step-by-step human input. It covers how error accumulation, context limits, and cost shape system design, and describes practical approaches to task decomposition, quality verification, reasoning cost trade-offs, permission boundaries, and a staged rollout plan.
1. How Long-Running Tasks Change the Picture
Large language models have mostly been used for single-turn question answering or for generating individual functions. A user provides a requirement, the model returns a piece of code, and a person then integrates the pieces. Long-running tasks work differently. They require a system to keep moving for hours or even days without step-by-step human intervention, covering requirements analysis, module design, coding, testing, bug fixing, and documentation.
This shift has three direct consequences.
First, errors accumulate. Even when the accuracy of each step is high, the overall success rate drops noticeably over dozens or hundreds of steps. The system therefore needs checkpoints throughout the process rather than relying only on the final result.
Second, context management becomes a bottleneck. The longer the task, the more intermediate state must be retained, and a single agent’s context window fills up quickly. A common solution is to split the work across multiple sub-agents, with each one carrying only the information relevant to its own part.
Third, cost and latency can no longer be ignored. A single long task may trigger a large number of inference calls, and both the number of calls and the depth of reasoning determine the cost. System design must treat budget as a first-class constraint.
2. Task Decomposition: Turning Large Goals into Verifiable Subtasks
Multi-agent collaboration depends on good decomposition. When decomposition is done well, dependencies between subtasks are clear, and each subtask has explicit inputs, outputs, and acceptance criteria. When it is done poorly, sub-agents duplicate work or overwrite each other’s results.
In practice, decomposition can follow these principles:
- Each subtask produces only one type of result, such as an interface definition, a set of unit tests, or a module implementation.
- Dependencies between subtasks are represented as a directed acyclic graph (DAG) to avoid circular waits.
- Each subtask has acceptance criteria that can be checked automatically, such as passing tests, a clean type check, or conformance to an agreed interface format.
The following simplified scheduler illustrates dependency-driven parallel execution. The worker function is a placeholder. In real use, replace it with an actual model call or tool call.
import asynciofrom dataclasses import dataclass, field@dataclassclass Task:name: strdeps: list[str] = field(default_factory=list)async def run_worker(task: Task, sem: asyncio.Semaphore) -> str:async with sem:# Placeholder: replace with a real model call or tool callawait asyncio.sleep(0.1)return f"{task.name} completed"async def orchestrate(tasks: dict[str, Task], max_parallel: int = 8) -> dict[str, str]:sem = asyncio.Semaphore(max_parallel)results: dict[str, str] = {}pending = dict(tasks)while pending:ready = [t for t in pending.values()if all(d in results for d in t.deps)]if not ready:raise RuntimeError("Circular or unsatisfiable dependencies detected")batch = await asyncio.gather(*(run_worker(t, sem) for t in ready))for task, output in zip(ready, batch):results[task.name] = outputdel pending[task.name]return resultsif __name__ == "__main__":plan = {"Interface definition": Task("Interface definition"),"Storage module": Task("Storage module", deps=["Interface definition"]),"Network module": Task("Network module", deps=["Interface definition"]),"Integration test": Task("Integration test", deps=["Storage module", "Network module"]),}print(asyncio.run(orchestrate(plan)))
This code shows three things. First, a task is scheduled only after its dependencies are satisfied, so the storage module and the network module can run in parallel. Second, the semaphore limits how many workers run at the same time, which prevents resources from being exhausted. Third, results are collected by task name, which makes later integration easier.
3. Quality Loop: Parallel Work Is Meaningless Without Verification
Parallel execution speeds up output, but it also amplifies quality risk. Code generated by separate sub-agents may conflict in its assumptions about interfaces, naming, or error handling. A quality loop is therefore necessary.
Common practices include the following layers:
- Unit-level verification: Run the relevant tests immediately after each subtask produces output. If they fail, retry locally. If the retry limit is exceeded, escalate to a higher-level process.
- Integration-level verification: After all dependencies are complete, run cross-module tests. If an interface inconsistency is found, trace back to the interface definition task and regenerate it.
- Independent review: Have another agent or a static analysis tool check code style, security issues, and boundary conditions. The reviewer should ideally use a different context from the implementer to avoid sharing the same blind spots.
- Human spot checks: Keep manual review points for critical paths, security-sensitive code, and dependency changes.
In addition, all intermediate artifacts should be under version control. Each subtask’s output is best saved as a separate commit or branch. If one stage fails, only that stage needs to be rolled back, and other parts that have passed verification remain untouched.
4. Trade-offs Between Cost and Reasoning Depth
Inference cost typically grows with reasoning depth, context length, and output length. For long tasks, this means not every subtask needs the strongest reasoning mode.
Reasoning levels can be tiered by task difficulty:
- Format conversion, log cleanup, and simple boilerplate generation can use a lower reasoning level.
- Algorithm design, concurrency logic, and security-related code call for a higher reasoning level, paired with stricter verification.
- Planning and integration steps suit a medium level. They need a global view, but their output is comparatively manageable in size.
Budget controls should also be built into the scheduler. For example, set a maximum number of calls, a maximum output length, and a total cost cap for each task. When a limit is exceeded, pause and notify a human. This prevents a sub-agent from getting stuck in an unproductive loop and consuming resources indefinitely.
Cost and quality do not have a linear relationship. In many scenarios, sound task decomposition and thorough verification improve results more reliably than simply increasing reasoning intensity.
5. Permission Boundaries and Security Governance
Long-running agents typically need to read and write files, execute commands, and access the network. The greater the permissions, the higher the risk of accidental operations or manipulation by malicious input. Security design must therefore be included from the start.
Follow these principles:
- Least privilege: Each sub-agent receives only the file paths, tools, and network access scope it needs for its task.
- Isolated execution: Run code in containers or sandboxes separated from the host environment, and restrict outbound network access.
- Treat input as data: External files, web content, and tool return values must not be executed directly as instructions. They should go through explicit parsing and validation.
- Keep secrets out of context: Inject credentials through environment variables or a secrets management service, never into code or prompts.
- Require confirmation for destructive actions: Deleting data, changing permissions, and deploying must require human approval.
At the infrastructure level, standard cloud capabilities such as container platforms, object storage, message queues, logging services, and monitoring and alerting can support these mechanisms. For example, write each subtask’s execution logs to a logging service and set alerts for abnormal behavior to support later traceability. Platforms such as Baidu AI Cloud provide capabilities in these general categories. The specific services should be chosen according to your own compliance requirements.
6. Recommendations for Getting Started
Teams that want to try long-running agent tasks can proceed in stages rather than building a complete system all at once.
Step 1: Choose a small project with clear boundaries, such as refactoring a utility script or filling in tests for a set of interfaces. The goal is to validate the decomposition and verification workflow, not to pursue scale.
Step 2: Write the task decomposition rules as documentation, specifying the inputs, outputs, and acceptance criteria for each type of subtask. This step often has more influence on the final outcome than the scheduler code.
Step 3: Build a minimum viable scheduler. Start with dependency management and parallelism limits, then gradually add retries, budget control, and audit logs.
Step 4: Establish the quality loop. Make sure each subtask has automated verification, and keep manual review at key checkpoints.
Step 5: Adjust reasoning tiers and parallelism based on run data. Record the success rate, duration, and cost of each task type to inform later decisions.
The value of long-running agents lies in freeing people from repetitive decomposition, dispatching, and integration work. Engineers still define the goals, set the acceptance criteria, and take final responsibility for the results.
