Engineering Multi-Agent Development Legions Driven by Long-Context Models: A Practical Guide
Building a multi-agent development team using LLMs is more than just assigning prompts to different roles. The real challenge lies in ensuring stable, continuous delivery rather than simply generating text. This article explores a comprehensive engineering approach to constructing a multi-agent software delivery system. It covers architectural design, role definition, context management, orchestrator state machines, communication protocols, security boundaries, and reliability design. By treating agents as bounded task executors within an event-driven, trackable, and recoverable engineering framework, organizations can successfully transform conversational AI into a verifiable and robust development pipeline.
From “Chatting” to “Delivering”: Engineering Multi-Agent Development Legions
This article discusses a general technical approach and is not bound to any specific model, platform, tool, or cloud provider. The message formats, state machines, prompts, and code in the text are illustrative and should be adjusted according to organizational standards, permission systems, and compliance requirements during implementation.
1. Problem Definition: The Real Challenge of Multi-Agent Systems is “Stable Delivery”, Not “Generation”
Having multiple agents play the roles of market researcher, product manager, architect, developer, tester, and DevOps might not look complicated: write a prompt for each role and let them message each other. However, when put into continuous production, problems surface quickly:
- Long Task Chains Break Easily: From requirement clarification to final delivery, a process may involve dozens of tool calls and multiple review rounds. Any context loss, formatting error, or timeout can stall the entire workflow.
- Context Pollution and Crosstalk: If all agents share a single long conversation, role instructions, historical decisions, temporary attempts, and invalid information will mix together, leading to behavioral drift.
- Tool Side Effects are Hard to Control: Writing files, modifying code, running tests, and deploying services all produce side effects. Without sandboxes, permission controls, and idempotent designs, greater automation brings greater risk.
- Quality Cannot Rely Solely on Model Self-Evaluation: An agent saying “completed” does not mean the system is deliverable. There must be artifact contracts, automated validation, human gates, and rollback mechanisms.
- 7x24 Operation Demands Engineering Reliability: Retries, rate limiting, checkpoint recovery, dead-letter queue handling, budget controls, monitoring alerts, and audit replays are all indispensable.
Therefore, a usable multi-agent development legion is essentially an event-driven, state-trackable, artifact-verifiable, permission-convergent, and failure-recoverable software delivery system. The large model is responsible for understanding, reasoning, and generation; the engineering system is responsible for constraint, orchestration, validation, and fallback.
2. Overall Architecture: Treat Agents as “Bounded Task Executors”
A layered architecture is recommended:
Requirement Entry Layer→ Master Orchestrator (Workflow State Machine, Task Queue, Budget & Permission Policies)→ Specialized Agent Pool (Research, Product, Architecture, Development, Testing, Review, Operations)→ Tool Adapter Layer (Code Repositories, Sandbox Execution, Test Runners, Data Queries, Notifications)→ Artifact Repository (Requirements, Designs, Code Patches, Test Reports, Decision Records)→ Quality Gate & Delivery Layer (Review, Release, Rollback, Monitoring)→ Observability (Logs, Metrics, Traces, Audits, Replays)
Key principles:
- The Orchestrator Does Not Make Business Decisions: It handles scheduling, waiting, retrying, escalating to humans, and exception handling. It does not write code or make architectural decisions for the roles.
- Agents Do Not Share Raw Conversations: Each agent has an independent context and collaborates through structured messages and artifact references.
- Artifacts Over Chats: Requirements, API contracts, code patches, test reports, and decision records must be persisted, versioned, and traceable.
- Tool Calls Must Be Controlled: Only the minimum permissions required for the task are granted. Production write operations must go through a human gate.
- Full-Trace Replays: Every task assignment, model output, tool result, and human approval must be traceable to facilitate issue localization and improvement evaluation.
3. Role Design: Every Role Needs “Inputs, Outputs, and Completion Criteria”
More agents are not necessarily better. Role division should revolve around deliverables and responsibility boundaries, not just “looking like a team.” A practical development pipeline can include the following roles.
1. Requirements Analyst
Responsible for translating natural language requirements into verifiable problem descriptions. Outputs:
- Business goals and non-goals;
- User scenarios and edge cases;
- Acceptance criteria;
- Questions requiring clarification;
- Risks and compliance constraints.
The completion criteria is not “understood,” but rather “acceptance criteria can be covered by test cases.”
2. Market & Business Researcher
Responsible for collecting information within compliant data sources. Outputs evidence tables, field lists, competitor capability comparisons, and lists of assumptions. Each conclusion should include its source, time, and confidence level. Collecting non-public data or bypassing access controls is prohibited.
3. Product Manager
Responsible for the PRD, user stories, priorities, entity models, and interaction flows. The PRD must include:
- Functional requirements;
- Non-functional requirements (e.g., performance, reliability, retention periods, permissions);
- Data fields and state transitions;
- Exception flows;
- Acceptance criteria;
- Explicitly out-of-scope items.
4. Architect
Responsible for module division, API contracts, data models, deployment topology, capacity, and risks. Architecture outputs should form a reviewable design document with explicit key decision records (e.g., why a specific queue, storage, or scheduling method was chosen).
5. Task Decomposer
Breaks down the PRD and architecture into a DAG task graph. Each task must include:
- Task ID and dependencies;
- Input artifacts and versions;
- Output contract;
- Acceptance criteria;
- Allowed tools;
- Timeout and retry strategies;
- Requirement for human approval.
6. Development Agent
The development agent handles only narrow-scope tasks, such as “implementing a data collection adapter” or “writing tests for an alert rule engine.” It should output:
- Code patches;
- Change descriptions;
- Self-test results;
- Risks and uncovered items.
For complex coding tasks, it can call controlled intelligent coding tools or local code agents, but these must run in an isolated environment and only modify specified branches or directories.
7. Testing Agent
Responsible for unit tests, integration tests, end-to-end tests, and fault injection. Test reports must include test cases, pass rates, failure logs, reproduction steps, and defect severity. The testing agent is not responsible for “proving the code is flawless,” but for “providing verifiable quality evidence.”
8. Review & Security Role
Responsible for code review, dependency risks, secret leaks, privilege escalation, prompt injection, and data compliance checks. High-risk changes must be escalated to humans.
9. Release & Operations Role
Responsible for release plans, database migrations, canary strategies, rollback plans, and monitoring configurations. Production releases, production data write operations, and paid resource changes must require a human approval gate.
10. Master Orchestrator Agent
Responsible for receiving requirements, selecting workflows, assigning tasks, checking artifacts, handling blockages, and escalating to humans. The master should not get bogged down in implementation details but should maintain global state: current goals, completed artifacts, pending issues, budget consumption, and risk levels.
4. Context Engineering: Long Context is Not “Stuffing Everything In”
Long-context models can significantly improve the stability of long tasks, but context must be managed proactively in engineering. A layered memory approach is recommended:
- Task Context: Current goal, acceptance criteria, deadlines, permission boundaries.
- Artifact References: IDs, versions, and summaries of PRDs, API contracts, code patches, and test reports.
- Decision Records: Why a design was chosen, which alternatives were discarded, and residual risks.
- Tool Results: Retain only structured results and key logs to avoid polluting the context with verbose outputs.
- Failure Experiences: Attempted solutions, failure reasons, and pitfalls to avoid.
- Human Instructions: Approval opinions, priority adjustments, and compliance requirements.
A general context pack can be designed as follows:
{"task_id": "req-001-T3","role": "backend_developer","goal": "Implement price snapshot write and idempotent update","inputs": [{"type": "artifact", "id": "api-contract-v4", "summary": "Price snapshot API fields and status codes"},{"type": "artifact", "id": "data-model-v2", "summary": "Core entities and unique key definitions"},{"type": "decision", "id": "adr-007", "summary": "Use task idempotency key to avoid duplicate writes"}],"constraints": ["Can only modify specified modules","Must not introduce unapproved external dependencies","Must provide failure retry and duplicate write tests"],"tool_allowlist": ["repo.read", "file.write.sandbox", "test.run"],"acceptance": ["Repeated writes of the same snapshot do not create duplicate records","Returns a retryable error on write failure","Tests cover normal, duplicate, and timeout scenarios"],"context_version": "2025-01-01T10:00:00Z"}
Key practices:
- Separate Summaries from Originals: Retain versions and summaries for high-value artifacts; read details via references only when needed.
- Context Budget: Set a context limit for each role. If exceeded, trigger summarization, retrieval, or phased execution.
- Decisions are Immutable: Once an Architecture Decision Record (ADR) is approved, it should not be overwritten by chat logs; changes require a new version.
- Periodic Checkpoints: After completing each milestone, save state, artifacts, and pending issues to support checkpoint recovery.
- Prevent Prompt Injection: External web pages, user inputs, and third-party data must be treated as untrusted content and cannot directly enter the system instruction area; tool calls must pass permission validation.
5. Orchestrator: Managing “Uncertain Agents” with State Machines
Agent outputs are inherently uncertain, so the orchestrator must place more emphasis on validation, retries, and human fallbacks than traditional workflows. A typical task state includes:
RECEIVED → CLARIFYING → PLANNED → RUNNING→ WAITING_HUMAN / WAITING_DEPENDENCY→ REVIEWING → DELIVERED→ FAILED → RETRYING / ROLLED_BACK
Core mechanisms:
- Idempotent Task Keys: Generate a unique key using “Requirement ID + Phase + Task ID + Attempt Number” to avoid repeated side effects from duplicate executions.
- Leases & Heartbeats: Executing tasks hold a lease and report heartbeats periodically; expired leases trigger rescheduling by the orchestrator.
- Max Rounds & Budget: Limit the number of model calls, tool calls, execution time, and cost per task to prevent infinite loops.
- Structured Validation: Every output must pass JSON Schema or custom validators; failures trigger repair prompts or reassignment.
- Dead-Letter Queue: Tasks that fail after multiple retries enter a dead-letter queue for human intervention rather than retrying indefinitely.
- Compensating Transactions: Pre-design compensation operations for steps that produce side effects, such as shutting down temporary environments, rolling back branches, or revoking uncommitted changes.
- Human Gates: Production releases, sensitive data access, paid resource changes, and privilege escalations must wait for human approval.
Illustrative pseudocode:
function run_task(task):context = load_context_pack(task.id)if not acquire_lease(task.id):return "skip: task is running elsewhere"for step in task.steps:emit("step.started", task.id, step.id)result = agent.execute(step, context)if not validate_schema(result):result = agent.repair(result, step.output_schema)if result.need_human:save_checkpoint(task, step, result)return wait_for_human(task.id)if result.failed and step.retryable:schedule_retry(task, step, backoff(step.attempt))return "retry_scheduled"save_artifact(result.artifact)append_event(task.id, step.id, result.summary)context = update_context(context, result)mark_delivered(task.id)
Note: The orchestrator should not treat natural language like “I think it’s done” as a completion signal. It must check artifacts, test reports, and gate results.
6. Communication Protocol: Let Agents “Message” Without “Brain Contamination”
Agents should use structured messages rather than endlessly forwarding chat logs. A general message envelope can include:
{"message_id": "msg-1001","trace_id": "req-001","from": "architect","to": "backend_developer","intent": "TASK_ASSIGNMENT","task_id": "req-001-T3","artifact_refs": [{"id": "api-contract-v4", "version": 4},{"id": "data-model-v2", "version": 2}],"payload": {"goal": "Implement price snapshot write service","acceptance": ["Idempotent write", "Retryable on failure", "Provide test report"]},"deadline": "2025-01-01T18:00:00Z","requires_ack": true,"confidence": 0.86}
Recommended rules:
- Messages are immutable; corrections are made via new messages or new artifact versions.
- Every task assignment requires an acknowledgment (ACK); if no ACK is received before a timeout, it is reassigned.
- Natural language is only for clarification and explanation; key decisions must be formalized into structured artifacts.
- Messages contain only references and summaries, not full historical conversations.
- Multiple candidate versions of the same artifact are allowed but must be labeled with status: Draft, Pending Review, Approved, or Deprecated.
7. Complete Pipeline Example: Competitor Price Monitoring System
Assume the requirement is: Build an e-commerce competitor price monitoring system that periodically collects prices, original prices, discounts, and stock status. It should provide trend charts, mark abnormal fluctuations, and trigger alerts via enterprise collaboration tools for low prices, extreme volatility, or out-of-stock situations. It must also support spreadsheet export.
Phase 1: Requirement Intake & Clarification
The entry point can be a collaboration platform bot, a form, or an API. The system first standardizes the requirement into:
- Goal: Monitor price and inventory changes for specified products;
- Deliverables: Collection service, storage, analysis API, frontend dashboard, alerts, export;
- Non-goals: Do not bypass access controls, do not collect non-public data, do not promise millisecond-level real-time updates;
- Constraints: Collection frequency, retention period, alert recipients, export fields, and concurrency scale.
If information is insufficient, the Requirements Analyst raises clarification questions rather than letting the Development Agent guess.
Phase 2: Market Research & Data Compliance
The Market Researcher outputs a field list and evidence table, such as: Product ID, Source, Snapshot Time, Current Price, Original Price, Discount Type, Stock Status, Collection Status. All data sources must comply with the target site’s Terms of Service, access rate limits, and local laws. For sources that prohibit automated collection, switch to manual entry, authorized APIs, or third-party authorized data.
Phase 3: PRD & Acceptance Criteria
The Product Manager defines core entities:
- Product: Product ID, Name, Category, Source;
- Snapshot: Snapshot ID, Product ID, Collection Time, Price, Original Price, Discount, Stock Status;
- Alert Rule: Trigger Condition, Threshold, Silence Period, Notification Target;
- Export Task: Filter Conditions, Fields, Generation Status, Expiration Time.
Acceptance criteria examples:
- Repeated reports of the same product at the same collection time do not create duplicate snapshots;
- Collection failures are visible, retryable, and do not block other products;
- Alerts are generated when price fluctuations exceed the rule threshold, and the same rule does not repeatedly trigger during the silence period;
- Trend charts can be queried by time range;
- Export files have complete fields, and tasks can retry or report failure on timeout.
Phase 4: Architecture Design
The Architect designs:
- Scheduling Service: Generates collection tasks based on products and sources;
- Collection Adapter Layer: Different sources use different adapters, outputting a unified snapshot structure;
- Message Queue: Peak shaving, decoupling collection and analysis;
- Storage: Relational storage for products and rules, time-partitioned storage for snapshot data, object storage for export files;
- Analysis Service: Calculates trends, volatility, and out-of-stock status;
- Alert Engine: Rule matching, silence period, deduplication, notification;
- Query API & Frontend Dashboard;
- Logging, metrics, tracing, and auditing.
Phase 5: Task Decomposition
The Task Decomposer generates a DAG:
T1 Data Model & MigrationT2 Collection Adapter InterfaceT3 Scheduling & Idempotent Snapshot WriteT4 Trend & Anomaly DetectionT5 Alert Rules & Silence PeriodT6 Query API & DashboardT7 Spreadsheet ExportT8 Integration Testing & Fault InjectionT9 Release & Monitoring Configuration
Each task binds input artifacts, output contracts, and acceptance criteria. T3 depends on T1, T2; T4 depends on T1, T3; T8 depends on all functional tasks.
Phase 6: Development & Testing
The Development Agent receives only narrow context. For example, when implementing T3, it only reads the data model, API contract, coding standards, and idempotency requirements. Outputs include code patches, change descriptions, and test reports. The Testing Agent supplements exception scenarios: duplicate messages, out-of-order messages, collection timeouts, database unique key conflicts, alert silence periods, and export task interruptions.
Phase 7: Review, Release & Operations
The Review role checks code quality, dependency risks, secret leaks, and permission boundaries. The Release role generates a canary plan, database migration rollback strategy, and monitoring items. Post-launch, monitoring covers collection success rate, data freshness, alert accuracy, export failure rate, and message backlog. When anomalies occur, the system automatically creates tickets or escalates to humans instead of letting the agent retry infinitely.
8. Tool Layer: Prioritize Permissions, Sandboxes, and Audits
Every tool adapter should have unified metadata:
- Input/Output Schema;
- Permission scope;
- Timeout and retry strategy;
- Rate limiting quota;
- Dry-run support;
- Side-effect generation;
- Audit fields.
Principles:
- Least Privilege: Development agents can only write to specified branches and directories and cannot directly operate production databases.
- Read/Write Separation: Query tools can be called automatically; write operations require approval or are restricted to sandboxes.
- Network Egress Control: Only allow access to domains or internal services required for the task to reduce data exfiltration risks.
- No Secrets in Context: Use a Key Management Service (KMS); tools inject short-lived credentials at runtime.
- All Tool Calls are Auditable: Record caller, parameter summaries, result status, and artifact references.
- Two-Person Review for High-Risk Operations: Production releases, data deletion, permission changes, and paid resource scaling must require human confirmation.
9. Reliability Design for 7x24 Operation
To keep the agent legion running continuously, the uncertainty of LLMs must be incorporated into the fault model.
| Fault Mode | Typical Symptom | Engineering Countermeasure |
|---|---|---|
| Output format error | Missing JSON fields, type mismatch | Schema validation, repair prompt, fallback retry |
| Context loss | Forgets acceptance criteria, repeats questions | Checkpoints, artifact references, context pack rebuild |
| Tool timeout | Tests hang, API unresponsive | Timeouts, circuit breakers, async tasks, compensation |
| Duplicate side effects | Duplicate DB writes, repeated alerts | Idempotency keys, unique constraints, dedup tables |
| Agent loops | Repeatedly modifying the same file | Max rounds, budgets, loop detection, human intervention |
| Concurrency conflicts | Multiple agents editing same file | Task branches, file locks, merge gates |
| Data source changes | Missing fields, changed page structure | Adapter contract tests, data quality alerts |
| Secret leakage | Credentials appear in logs | Secret scanning, redaction, egress auditing |
| Cost overrun | Abnormal growth in API calls | Budget quotas, rate limiting, per-task accounting |
Additionally, the system should support task replay from logs and artifacts: given the same requirement version, prompt version, tool version, and randomness configuration, it should be able to reproduce the key decision path. Replays may not exactly reproduce model outputs, but should reconstruct the state and locate deviations.
10. Evaluation System: Don’t Measure the Agent Legion by “Feels Good”
It is recommended to evaluate at both the task level and the system level.
Task-level metrics:
- Task completion rate;
- First-time acceptance pass rate;
- Rework ratio;
- Average delivery time;
- Human intervention rate;
- Tool call failure rate;
- Cost per task.
System-level metrics:
- Workflow bottleneck distribution;
- Context rebuild count;
- Dead-letter task ratio;
- Alert accuracy and false positive rate;
- Rollback count;
- Mean time to recovery (MTTR);
- Regression results after prompt, model, and tool version changes.
During implementation, maintain a golden task set: including normal requirements, ambiguous requirements, conflicting requirements, tool failures, malicious inputs, and high-risk changes. Before deploying any changes to prompts, model routing, or tool permissions, run regressions on the golden task set, followed by a canary rollout.
11. Cost and Efficiency Governance
Multi-agent systems are prone to “context bloat” and “redundant labor.” Recommendations:
- Route simple classification, summarization, and formatting tasks to smaller models or rule engines;
- Use stronger models for complex architecture, cross-module reasoning, and failure diagnosis;
- Replace repeated full-text injections with artifact summaries and retrieval;
- Cache repeated reads of the same file;
- Prefer deterministic tools for deterministic tasks like testing and static analysis;
- Set time, call count, and cost budgets for each requirement;
- Periodically analyze which roles’ outputs are actually used downstream, and remove invalid roles and redundant steps.
Cost optimization should not come at the expense of quality. Production changes, security reviews, and compliance checks should not be bypassed to save money.
12. Security, Compliance, and Human Fallback
The security boundaries of a multi-agent system include at least:
- Data Compliance: Only collect authorized data, adhering to access frequency, privacy, and retention period requirements.
- Prompt Injection Protection: Isolate external content from system instructions; tool permissions should not expand based on external text.
- Supply Chain Security: Scanning dependencies for vulnerabilities, licenses, and source trustworthiness.
- Code Execution Isolation: Untrusted code runs only in sandboxes with no production network access by default.
- Audit & Accountability: Record who initiated, which agent executed, what tools were called, and which artifact version was produced.
- Human Fallback: Retain the ability to reject, pause, roll back, and take over high-risk operations.
So-called “7x24 autonomy” does not mean “unaccountable.” A more reasonable definition is: the system automatically advances on routine tasks, escalates to humans in abnormal, high-risk, and low-confidence scenarios, and ensures humans can quickly take over.
13. Implementation Roadmap
Phase 1: Single-Link Pilot
Select a clearly bounded, verifiable scenario with only three roles: Requirements Analyst, Developer, and Tester. Persist all artifacts and require human approval for key steps. The goal is to run through the “Requirement → Artifact → Validation” loop.
Phase 2: Introduce Orchestration & Observability
Add task queues, state machines, idempotency keys, retries, dead-letter queues, and log tracing. Start tracking task completion rates, rework rates, and human intervention rates.
Phase 3: Multi-Role Collaboration & Quality Gates
Add Architect, Reviewer, Security, and Release roles. Establish artifact contracts, automated validation, and human gates. Apply least privilege and sandboxes to high-risk tools.
Phase 4: Scaling & Cost Governance
Support concurrent tasks, model routing, budget controls, canary releases, and replay evaluations. Template mature workflows while retaining room for project-specific customization.
14. Common Pitfalls
- Turning Multi-Agent into Multiple Chat Windows: Without artifact contracts and state machines, more messages just create more chaos.
- Letting All Roles Share Full Context: Leads to role drift and context pollution.
- Focusing Only on Model Capability, Ignoring Engineering Capability: Without idempotency, retries, audits, and rollbacks, automation cannot enter production.
- Letting Agents Operate Production Directly: High-risk operations must have human gates and least privilege.
- Replacing Quality Verification with Model Self-Evaluation: Testing, static analysis, schema validation, and human review are indispensable.
- Chasing Full Automation Endlessly: A reasonable goal is “auto-advance + exception escalation + human takeover.”
- Ignoring Cost & Evaluation: Without budgets and regression sets, the system easily becomes increasingly expensive and unstable.
15. Conclusion
Building a multi-agent development legion using long-context models is not about making each agent “talk like an expert.” It is about equipping the entire system with the engineering capabilities to be orchestrable, isolatable, verifiable, recoverable, and auditable. A mature solution should achieve:
- Requirements have acceptance criteria;
- Tasks have DAGs and state machines;
- Agents have independent contexts;
- Collaboration uses structured messages;
- Tool calls have permissions and sandboxes;
- Artifacts have versions and quality gates;
- Failures have retries, compensation, and human fallbacks;
- Operations have logs, metrics, audits, and replays;
- Improvements have evaluation sets and cost constraints.
Once these engineering foundations are in place, long-context models can maintain goal alignment and reduce forgetting across task chains of dozens of rounds or more, sustaining the development pipeline. A 7x24 agent legion is not about “letting models run free,” but “using engineering systems to constrain model capabilities onto a deliverable track.”
