Zero Labs
Industry News / AI

Why Your AI Orchestrator Should Never Write Code

Source · Towards AI By Mikhail Rogov

From the publisher’s feed, collected in the ZeroLabs newsroom.

A Production Blueprint for Multi-Agent SystemsForty-plus production workflows. Three months. Three providers. Six agents. One rule that held: the orchestrator must never execute.The PrincipleThe orchestrator must never execute. Not mostly delegate. Never. It decomposes, delegates, validates, and escalates. It does not write code. It does not run tests. It does not modify files. That boundary held across every provider, every agent topology, and every failure mode we hit — and it is the single rule that separates systems that scale from systems that collapse under their own context. In the first article, I described what broke. This article is the system that survived.Since that system went into production, the major AI labs have independently converged on the same structural boundary. Anthropic published orchestrator-worker separation as the recommended topology. OpenAI’s Agents SDK formalized hierarchical delegation through agent.as_tool(). Google’s Agent Development Kit shipped parent-child delegation with LLM-driven routing. Three different labs, three different architectures, one shared conclusion: the thing that decides what to do must not be the thing that does it.What follows is deliberately prescriptive — not a build log but a blueprint, informed by where multi-agent systems break and what survives. The forcing function is context pollution — when implementation details (function signatures, test failures, dependency errors) fill the orchestrator’s context window and degrade its ability to manage the system.In practice: the orchestrator spots a failing import in the SWE (Software Engineer) agent’s output and decides to “quickly” fix it. Twenty minutes later, its context is full of node_modules resolution paths and TypeScript compiler errors. Three other agents are idle. The orchestrator has forgotten which tickets are in progress and what the original epic required. The “quick fix” consumed the strategic reasoning capacity the orchestrator exists to protect.The separation is not philosophical. It is structural.Where the Industry Is (February 2026)Before explaining how the system works, it helps to understand what it sits alongside. If you want to understand the system before comparing it, skip to “The Agent Topology” and return here after.Anthropic’s Orchestrator-Workers is the closest relative — nearly identical decompose-delegate-validate loop, but silent on whether the orchestrator should avoid execution. That silence is the gap this pattern fills.OpenAI’s Agents SDK offers handoffs and agent.as_tool() hierarchy with Sessions and Temporal for crash recovery — production-ready for pipelines, but no central decision-maker maintains state across a multi-day workflow unless you build one.LangGraph provides the most mature checkpointing evaluated — powerful for branching workflows, though the graph abstraction carries real setup cost for mostly linear pipelines.Google ADK ships hierarchical agent composition with shared Session State — the closest to Delegated Reasoning’s structure, but nothing prevents the parent from executing alongside its children.The pattern across all four: every framework allows the orchestrator to execute. None forbid it. Delegated Reasoning is not a framework — it is a discipline. The strict separation, artifact-based recovery, and quantitative scope governance are constraints you impose, not features you install.When choosing: use LangGraph for complex branching. Use OpenAI Agents SDK for production durability with broad model support. Use Anthropic’s patterns if Claude is your primary model. Use Google ADK for hierarchical delegation. Layer Delegated Reasoning’s discipline on top of whichever you pick — or, as we did, skip the framework entirely and let the discipline be the architecture.The framework choice is an infrastructure decision. What follows is the operational architecture that sits above it.The Agent TopologyA Delegated Reasoning system has two layers: one orchestrator that reasons about work, and specialized agents that perform it. The topology matters more than the count.The AgentsThe orchestrator — called the DEM (Delegated Engineering Manager) — sits at the center. It runs on a standard-tier model optimized for reliable instruction-following and never writes a line of product code. Six specialized sub-agents surround it. They are: Ticket Planning, Architecture+Spec, SWE, Review, E2E, and Research.In the first article, the system had five agents — reduced from the original seven after absorbing both Discovery and Research into the orchestrator. Since then, Research was externalized back to a dedicated agent. The reason is the principle itself: Research investigations fill context with implementation details — file dependencies, scope analysis, codebase structure — exactly the kind of pollution the orchestrator’s context cannot afford. Discovery stayed absorbed. It classifies feature size in eight seconds. The orchestrator handles this between tool calls.The distinction between Discovery and Research is the distinction that governs the entire topology: how long the task takes relative to the cost of keeping the orchestrator’s context clean.One dependency the topology requires but most tutorials omit: a ticketing system. The planning agent reads from and writes to a ticketing system — Linear, Jira, Shortcut — via API. The ticketing system is the source of truth for what gets built; the artifact system is the source of truth for how it was built. Each implementation ticket carries a DoD checklist that the SWE (Software Engineer) agent must satisfy and the review agent verifies. The orchestrator moves tickets through states (Todo -> In Progress -> In Review -> Done) as agents complete their work, and will not spawn a SWE agent until all blocking tickets are marked Done. Without a structured ticketing system providing machine-readable acceptance criteria, the scope governance described later has nothing to measure against.The 30-Second Rule: How “Never Execute” Works in PracticeIf the orchestrator can answer the question in 30 seconds of reasoning, do not spawn an agent. If it cannot, always spawn — the orchestrator’s context window is too valuable to spend on execution.This is the single most useful heuristic for agent topology decisions. “The orchestrator must never execute” is the principle. The 30-second rule is how it works in practice — the operational boundary between orchestrator reasoning and agent execution.Discovery’s absorption is the worked example. It classified feature size in eight seconds. Wrapping that in an agent lifecycle — spawn a process, set up a worktree, monitor heartbeat, validate the artifact, clean up — added minutes of overhead to a task the orchestrator could handle in a single tool call. Discovery fell below the 30-second line. Research stays above it: scope investigations take minutes, fill context with implementation details, and degrade the orchestrator’s subsequent decisions.In our system, thirty seconds was the threshold. Yours will depend on your model speeds, context costs, and task complexity. The principle is the boundary, not the number.The rule also prevents over-spawning. Every unnecessary agent adds coordination cost — spawning, monitoring, artifact validation, failure recovery — that the orchestrator must manage. The right question is never “could an agent do this?” but “does this task cost more in orchestrator context than in agent lifecycle overhead or could it be externalized into a tool?”Multi-Provider Model RoutingIn our system, this is how we route models to agents:{"routing": { "dem": { "model": "Sonnet" }, "ticket-planning": { "model": "Sonnet" }, "architecture-spec": { "model": "Opus" }, "swe": { "model": "Codex" }, "review": { "model": "Gemini" }, "e2e": { "model": "GPT" }, "research": { "model": "Gemini" } }}The tier names map to concrete model IDs from multiple providers — the specific models change every time a stronger release lands. The prescription is the pattern, not the specific assignments: match models to cognitive tasks, not to agent roles. The SWE agent runs on a codex because agentic code execution is what those models are purpose-built for. The Review agent runs on gemini because reviewing a consolidated diff across dozens of files requires deep analysis over large context. The orchestrator runs on sonnet because reliable instruction-following matters more than deep reasoning for delegation decisions.The counterintuitive discovery: routing the orchestrator to a deep-reasoning model made it worse. It over-analyzed simple dispatch decisions. The orchestrator does not need to think deeply. It needs to follow its own rules reliably.Keep routing in configuration, not code. Changing a model assignment is a JSON edit. When a new model releases, test it on one agent without touching the others.Artifact-Based CommunicationAgents never see each other’s raw output. Every sub-agent produces exactly one structured JSON artifact on disk, validated against a schema before the orchestrator reads it. The next agent gets a fresh context from the orchestrator, informed by the previous artifact but never contaminated by it.class Artifact(BaseModel): module: str # "swe", "ticket-planning", "review" status: Literal["success", "failure", "escalation_required", "need_info"] timestamp: datetime # ISO 8601 UTC params: dict # env_vars + agent-specific params output: dict # typed per-agent (SWEOutput, ReviewOutput, etc.) errors: list[dict] warnings: list[dict] escalation: list[dict] metadata: ArtifactMetadata # execution_time_ms, model_used, retry_count, usageEvery agent writes the same top-level schema. What differs is output: the SWE agent reports commit_sha, files_changed, and implicit scope counts; the Review agent reports issues[] and approved. The orchestrator knows exactly where to look regardless of which agent produced the artifact.Why artifacts over message passing — where one agent’s output is passed directly into the next agent’s context, keeping everything in memory? Three reasons.Crash-survivability. Files persist. In-memory messages do not. When an agent crashes mid-execution, its partial artifact on disk tells the orchestrator exactly where it stopped.Schema validation. Malformed output is caught before it propagates. The artifact schema validator rejects bad data at the boundary, not three agents downstream where the failure is incomprehensible.Context isolation. The orchestrator reads a structured summary, never a wall of raw agent output. Each agent starts with a clean context window. This is how you prevent the context pollution that the entire architecture exists to avoid.Input flows through environment variables (EPIC_ID, ORCHESTRATOR_ROOT, BASE_BRANCH), not context injection. The orchestrator never pastes the previous agent’s output into the next agent’s prompt. The artifact is on disk. The next agent’s spec tells it where to find what it needs.Artifacts and routing define how agents communicate. But six agents sharing one checkout will destroy each other’s work before the first artifact is written.Agent Isolation: One Worktree Per AgentEvery SWE agent runs in its own git worktree. Not a branch — a worktree: a separate filesystem checkout of the same repository, with its own working directory, its own node_modules, its own index, and its own HEAD. For those unfamiliar: git worktree add ../agent-swe-branch feature/EXP-184 creates a new directory with a full checkout of the repository on a separate branch. Multiple worktrees coexist, each on a different branch, sharing the same .git history. Creating one takes seconds. Deleting one is instant.The orchestrator creates the worktree before spawning the agent and removes it after consolidation. This is the mechanism that makes parallel agent execution possible.The shared-checkout failure. Without isolation, two agents working on the same repository will collide. Agent A commits to the shared branch while Agent B is mid-edit on the same files. Git state corrupts. Staged changes interleave. The failure is nondeterministic — invisible in testing, catastrophic in production. Every team that runs parallel agents in a shared checkout discovers this.The orchestrator’s filesystem must be read-only. The orchestrator checkout (ORCHESTRATOR_ROOT) contains agent specs, scripts, configuration, and logs. SWE agents must never write to it. An environment guard at the start of every SWE run resolves both ORCHESTRATOR_ROOT and WORKTREE_PATH to their real filesystem paths and fails hard if they match. The orchestrator reads artifacts from its own filesystem; the agent writes code to its worktree. The two never mix.How it works in practice:$WORKTREE_BASE/ feat/EXP-182-P1/ EXP-201/ ← SWE agent 1's isolated worktree EXP-202/ ← SWE agent 2's isolated worktree EXP-203/ ← SWE agent 3's isolated worktree1. The orchestrator creates a phase branch (feat/EXP-182-P1) from the current base.2. For each ticket, git worktree add creates an isolated checkout under the phase directory, branched from the phase branch.3. The SWE agent receives WORKTREE_PATH as an environment variable and runs entirely within it.4. When an agent produces a feat: $TICKET commit, the orchestrator queues its worktree for merge. Consolidation is continuous — the orchestrator does not wait for all agents to finish — but merges respect dispatch order (see below).5. Before consolidation, monitoring validates that the worktree exists, its .git metadata is intact, and the commit reported in the agent’s artifact actually exists in the expected worktree.Consolidation order matters. The orchestrator merges worktrees in FIFO order — the order tickets were dispatched, not the order agents finished. This makes the consolidated branch deterministic: given the same ticket queue and the same agent outputs, the merge sequence is identical. Nondeterministic merge order was the source of our hardest-to-reproduce integration failures before we enforced FIFO.Crash recovery. When an agent crashes, its worktree persists on disk. The orchestrator can inspect it, respawn the agent into the same worktree (preserving partial work), or remove it and start clean. The decision is based on the artifact state: if the agent wrote a partial artifact before crashing, the orchestrator knows exactly where it stopped. If no artifact exists, the worktree is treated as corrupted and recreated.The tradeoff is disk space — worktrees accumulate fast. Disk is cheap relative to the engineering time saved by not building a custom isolation layer. Claude Code launched native worktree isolation in February 2026 — the same pattern, independently validated.Git worktrees are to AI agents what containers are to microservices: the minimum viable isolation boundary that makes everything else possible.Agents now have isolated environments, structured communication, and cognitive-task-matched models. The harder question is what happens when they do more than they were asked to do.Scope Governance: The 30% ThresholdSet a hard boundary on implicit scope. Without one, every agent run will silently redefine its task.AI agents do not resist scope creep the way human engineers do. A human knows the PR reviewer will ask “why is this file changed?” An agent has no such social pressure. It sees adjacent code that “should” be improved and improves it. Each individual change is reasonable. In aggregate, the agent has reinterpreted its assignment.The SWE agent in this system tracks every file it modifies against the Definition of Done — the precise acceptance criteria for a task: what files should change, what tests should pass, what behavior should be observable. Files specified in the ticket are “planned scope.” Everything else is “implicit scope.” The agent reports both counts in its artifact, and the orchestrator computes the ratio.The 30% threshold was discovered, not designed. Across forty-plus SWE agent runs, we found a consistent boundary:- Below 30% implicit scope: tolerable noise. Import updates, type fixes, test fixtures that needed adjustment. Normal adjacent work that any competent engineer would do.- Above 30% implicit scope: the agent had not gone slightly beyond the ticket. It had reinterpreted the ticket. The Definition of Done was incomplete, and the agent filled the gaps with its own judgment.“Below 30% is a code review question. Above 30% is a planning failure.”The system responds in two tiers:1. Block (>30%): Stop consolidation. The Research agent investigates the implicit files — are they necessary dependencies or scope creep? If necessary, the orchestrator expands the Definition of Done and reruns. If scope creep, it reruns with tighter constraints. Fix the cause, not the code.2. *Flag (≤30%): Copy the implicit changes to the review agent for verification. These are code review questions, not architectural problems.When a Block triggers a rerun and the follow-up reports zero implicit files, that is not just clean code — it is proof the planning system self-corrected. The zeroed counters become a provable artifact: the system caught a planning gap, investigated it, fixed it, and verified the fix.Here is what this looks like in practice:1. The SWE agent completes a ticket. Its artifact reports: planned_files: 4, implicit_files: 3 — a 43% implicit scope ratio.2. The orchestrator reads the artifact, computes the ratio: 43% exceeds the 30% threshold. It creates a dod_gap_blocking escalation and halts consolidation.3. The Research agent investigates the three implicit files, determines they are necessary dependencies, and reports back with a structured recommendation.4. The orchestrator expands the Definition of Done to include the three files as planned scope. The SWE agent reruns with the updated DoD.5. The follow-up artifact reports: planned_files: 7, implicit_files: 0 — zeroed counters. The escalation clears. Consolidation resumes.The orchestrator logic is ten lines:def evaluate_scope(artifact: dict) -> str: planned = artifact["output"]["planned_files"] implicit = artifact["metadata"]["implicit_scope"]["implicit_files"] ratio = implicit / (planned + implicit) if (planned + implicit) > 0 else 0.0 if ratio > 0.30: return "block" # halt consolidation, investigate elif implicit > 0: return "flag" # pass to review, highlight in PRreturn "clean"The 30% threshold emerged from our forty-plus runs. Start there; calibrate for your codebase and ticket granularity.Every engineering leader has asked “why is this file changed?” in a PR review. This automates the question and gives it a quantitative answer. But governance handles what agents produce. The next question is what happens when they stop producing anything at all.Five-Signal Failure DetectionA single monitor class evaluates five independent signals. They are not stacked layers — they are parallel checks that collectively distinguish genuine failure from false positives. Build your monitoring first, not last. If monitoring fails, agents fail silently — and silent failures cascade.Four of the five signals are straightforward:- Log Heartbeat (20s interval): Poll the agent’s log. If it stops growing, investigate.- Content Hashing: Hash log content, not timestamps. An agent stuck in a retry loop — logging the same ConnectError every three seconds — looks alive by timestamp. Content hashing catches the repetition.- Transport Error Detection: Pattern-match log structure to distinguish “the agent is dying” from “the agent is reading someone else’s error.” Keyword search is not enough. A false positive kills a productive agent.- Tool-Call Awareness: Before declaring death, check whether a tool call is in flight. Long-running operations produce no log output. Without this, the heartbeat kills healthy agents mid-operation.The fifth signal is the one that earned its own story.Signal 5: Git Activity Watchdog. Monitor git commits independently of log activity. If the agent has not committed within its expected task window, flag it as stalled regardless of what every other signal says.During a production run, a SWE agent was tasked with a straightforward component refactor. Forty minutes in, the heartbeat showed healthy. The content hash confirmed output was changing. No transport errors. But the git watchdog had not seen a commit on a task estimated at fifteen minutes. The agent had entered a circular reasoning pattern: generate a solution, find a type error, undo, try again. The log was full of productive-looking reasoning that went nowhere. The watchdog flagged the stall, the orchestrator killed the agent and respawned it with a tighter constraint set, and the retry completed in eight minutes.Recovery PatternsDetection is half the problem. Recovery completes it:- Retry with user escalation. A failed agent gets up to five retries with exponential backoff. If the failure persists, the orchestrator escalates to the user — not to another model.- Orphan cleanup. When an agent crashes, its worktree and spawned processes may still exist. Monitoring identifies and removes all of them. A clean crash leaves nothing behind.- Guardrail catalog. Every “DO NOT” rule in the agent specifications exists because an agent did exactly that thing in production. “DO NOT write to the repository root” — because one did. The guardrail catalog is the system’s immune system.Monitoring keeps agents alive. The review loop determines whether what they produce is worth keeping.The Review LoopReview can be parallelized because it is read-only. Fixing cannot be parallelized because fixes interact. This asymmetry is the entire design.Fan-Out Review, Fan-In FixThe review system fans out for reading: the Review agent, a third-party automated review tool (CodeRabbit), and a Definition of Done verification check all run on the consolidated diff in parallel. Different lenses catch different things.When issues are found, all of them go to a single SWE agent. One agent, one handoff file, one fix cycle. The code gets re-reviewed. The loop repeats — up to five iterations before the system escalates to a human.Why One FixerThe lesson was earned through collision. Two fix agents worked in parallel on the same component. One moved shared state up to a parent provider. The other added local component state. Both compiled. Both passed type checks. Merged together, the component had two sources of truth that silently diverged on every update. No linter caught it. No build failed. The conflict was semantic, not syntactic.A single fixer holding all issues in context can reason about interactions between fixes. Parallel fixers cannot — and the “faster” approach is actually slower to converge.“Optimize for fewer review cycles, not faster individual cycles.”The pre-spawn scope guard rejects reviews if the file count exceeds 100 — a red flag that the planning agent did not break the work down well enough. At that point, the problem is planning, not review. Five iterations is the hard maximum. Beyond that, the accumulated context of fixes-on-fixes degrades agent reasoning, and human judgment is more efficient.What’s NextThe architecture works. These are the boundaries where it stops — and where the next iteration starts.Manual model evaluation. When a new model releases, evaluation is empirical: swap it into one agent slot, observe the results over several runs, compare. There is no automated benchmarking. The capability gap between models shows up as convergence speed, not pass/fail — which makes it harder to measure and harder to predict for new task types.Orchestrator as single point of failure. If the orchestrator crashes, the pipeline stalls. Recovery requires human intervention — restarting, re-reading pipeline state from artifacts on disk, determining where to resume. The artifacts make recovery possible. They do not make it automatic.No self-learning from failures. When an agent fails and the orchestrator tries to self-heal with a different approach, the retry succeeds — but the system does not learn why the first attempt failed. The guardrail catalog is updated manually after recurring patterns are noticed. If the same edge case appears three weeks later in a different feature, the agent will hit it again.The system already produces the data — failure artifacts, retry logs, before-and-after scope ratios. What does not exist yet is the feedback loop that turns signal into prevention. Building it requires distinguishing failures that generalize from failures that are context-specific. We have not built it because the false-positive cost of automated guardrails is higher than the manual cost of curating them — for now.Cost analysis — per-run API spend, multi-provider cost comparison, and the economics of model escalation on retry — will be covered in the operational companion piece.Building This YourselfFive decisions, in priority order. Each one is load-bearing.1. Enforce orchestrator/executor separation. Not “mostly separate” — completely separate. Your orchestrator agent specification should contain explicit “DO NOT” rules — not guidelines, rules. “Do not run pnpm install.”, “Do not modify any files”, “Do not fix lint issues”, “Do not fix failing tests” Without them, every model will eventually decide a quick fix is faster than spawning an agent. It always is — and it always degrades the orchestrator’s context. Start with a single orchestrator and a single execution agent. Get the separation working before adding specialization.2. Isolate agent execution with worktrees (or equivalent). Each agent needs its own filesystem. Git worktrees provide this natively: git worktree add creates a separate checkout with its own working directory, index, and HEAD. The agent runs in its worktree; the orchestrator reads artifacts from its own checkout. When the agent finishes, the orchestrator merges the worktree into the consolidated branch and removes it. Without this, parallel agents corrupt each other’s state. Alternatives exist (Docker containers, separate clones), but worktrees have the lowest overhead and the tightest integration with git-based workflows.3. Adopt artifact-based communication. Define your artifact schema before you build your first agent — it becomes the contract that every agent and the orchestrator depend on. Require at minimum: module, status, output, errors, escalation, metadata. Validate the schema before the orchestrator reads the artifact — malformed output caught at the boundary is a 30-second fix; malformed output caught three agents downstream is a 30-minute investigation.4. Add scope governance from the start. The ratio is implicit_files / (planned_files + implicit_files). Above 30%, halt. Below 30%, flag. This is ten lines of logic in the orchestrator, and it catches planning failures before they contaminate the review cycle. It requires machine-readable Definitions of Done in your ticketing system — without them, the threshold has nothing to measure against.5. Build monitoring before agents. If you build agents first, you will have agents that fail silently. The five signals described above (heartbeat, content hashing, transport errors, git activity, tool-call awareness) are the foundation, not the capstone. Test each signal with injected failures before trusting it in production.Build SequencingBuild in this order: monitoring -> artifact schema + validation -> orchestrator with one agent -> worktree isolation -> scope governance -> additional agents. The temptation is to start with agents because they are the interesting part. Resist it. An agent without monitoring is a process you cannot observe. An agent without artifacts is a process you cannot recover from. An agent without isolation is a process that will interfere with the next one.The Operational StackBeyond the five decisions, you need infrastructure that most tutorials leave out:A real ticketing system. Not a database table. Not a YAML file. A ticketing system — Linear, Jira, Shortcut — that the orchestrator reads from and writes to. The ticketing system is the orchestrator’s external memory. Without it, the orchestrator must hold all task state in context — which is the context pollution you built the architecture to avoid.Model routing configuration. A JSON file that maps agents to model tiers. Not code. Configuration. When a new model releases, you change one line and test it on one agent. Our routing file is eight lines of JSON. The performance difference between routing all agents to one model and matching models to cognitive tasks is significant.If you are using LangGraph, your graph is the orchestrator. Apply the separation discipline to it — the orchestrator node delegates, worker nodes execute. If you are using OpenAI Agents SDK, your parent agent is the orchestrator. Apply the same discipline. The pattern is framework-agnostic. The discipline is what matters.A Ticket Through the PipelineA ticket arrives: “Add dark mode toggle to settings page.” The orchestrator classifies it as SMALL (under 30 seconds of reasoning) and skips Architecture+Spec. The Ticket Planning agent decomposes it into two implementation tickets with Definitions of Done.Two SWE agents run in parallel — one per worktree, one per branch. The first completes within scope and merges. The second exceeds the 30% implicit scope threshold. The orchestrator blocks consolidation, sends the Research agent to investigate, expands the Definition of Done, and reruns. The follow-up reports zeroed counters.Review fans out in parallel: code review, CodeRabbit, DoD verification. Issues found go to a single SWE agent for fixing. Re-review passes. The orchestrator drafts a PR and hands off to the human.Sizing ItThe system is six agent specs, one orchestrator spec, a schema validator, a scope guard, and a monitoring module. It is not a weekend project — but the core (orchestrator + one agent + artifact schema + monitoring) can be stood up in a week. Add agents incrementally, one at a time, each solving a documented failure mode.This is not a framework. It is an architecture — and the architecture is transferable even if no line of code is reused.The orchestrator is the product. Not the agents. Not the models. Not the framework.If you haven’t read Part 1 — the mind shift and the 5 dead ends — start there: “What 371 Git Worktrees Taught Me About Multi-Agent AI.”Building multi-agent AI systems? I’d love to hear what patterns work for you — find me in the comments.*Why Your AI Orchestrator Should Never Write Code was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.