AI › Concept

Multi-agent orchestration patterns and workspace isolation

Compare Supervisor-Worker, Router, and Handoff patterns for multi-agent systems, with structured A2A messaging and Git worktree workspace isolation.

Multi-agent orchestration patterns and workspace isolation

Stuffing every role and tool into a single monolithic agent leads to context bloat, tool-selection errors, and slow, expensive turns. This post compares the Supervisor-Worker, Router, and Handoff orchestration patterns, then covers structured Agent-to-Agent (A2A) messaging and Git worktree workspace isolation in Kotlin.


Why monolithic agents hit a wall

Most LLM agent prototypes start the same way: one model instance wired up to file I/O, web search, Git commands, code search, and database queries. That works fine on a small demo, then falls apart as soon as task complexity grows.

1
2
3
4
5
6
7
8
[Monolithic Agent Failure Loop]
Oversized system prompt + 50 bound tools
       ▼
Context window bloat (raw logs and search dumps accumulate every turn)
       ▼
Tool-selection errors & missed instructions (lost in the middle)
       ▼
Repeated retries -> token cost spikes and high latency

Three bottlenecks drive that failure loop:

  1. Context bloat and poisoning: Thousands of lines of scraped docs or compiler output collected during research stay in the conversation history. By the time the agent writes code, it’s near the token ceiling and forgets earlier constraints.
  2. Tool-selection errors: Once you bind more than 20–30 tools to a single model call, the model starts confusing similar schemas, calling the wrong function, or dropping required parameters.
  3. Cost and latency spikes: Even a trivial status check resends tens of thousands of accumulated tokens on every turn.

Applying separation of concerns fixes this: split one overloaded agent into smaller, role-focused agents coordinated by an explicit orchestration pattern.


Three core multi-agent orchestration patterns

Multi-agent coordination generally falls into three patterns depending on who owns control flow and how tightly context needs to be isolated.

flowchart TD
    subgraph P1["1. Supervisor-Worker (Hierarchical Delegation)"]
        S["Supervisor (Orchestrator)"]
        W1["Worker: Researcher"]
        W2["Worker: Coder"]
        W3["Worker: Tester"]
        S -->|"Decompose and delegate"| W1
        S -->|"Assign implementation"| W2
        S -->|"Run verification"| W3
        W1 -.->|"Return summary"| S
        W2 -.->|"Return summary"| S
        W3 -.->|"Return summary"| S
    end

    subgraph P2["2. Router (Intent Gateway)"]
        R["Router (Classifier)"]
        A1["Doc Agent (Search)"]
        A2["SQL Agent (DB Query)"]
        A3["Issue Agent (Tickets)"]
        R -->|"Docs question"| A1
        R -->|"Data stats"| A2
        R -->|"Incident report"| A3
    end

    subgraph P3["3. Handoff / Swarm (Peer Control Transfer)"]
        Triage["Triage Agent"]
        Billing["Billing Agent"]
        Tech["Tech Support Agent"]
        Triage -->|"Handoff control"| Billing
        Billing -->|"Handoff control"| Tech
        Tech -->|"Return resolved"| Triage
    end

1. Supervisor-Worker (hierarchical delegation)

A central Supervisor breaks a high-level goal into subtasks, assigns each subtask to a specialized Worker, and aggregates the final output.

  • Why it works: Each worker receives only the tools its role needs—the coder gets file edit tools, while the researcher gets read-only search tools. Raw HTML, long stack traces, and noisy build logs stay trapped inside the worker’s context; the supervisor only sees a concise summary.
  • Best fit: Large codebase refactors, architecture research plus migration planning, and multi-step CI/CD workflows.

2. Router (branching entry gateway)

A lightweight Router classifies the user’s intent once and forwards the request directly to a single specialist agent or pipeline.

  • Why it works: You skip back-and-forth delegation hops, so latency stays low. Because the router needs no tools of its own, a fast, inexpensive model (such as Flash or Haiku) can handle classification in milliseconds.
  • Best fit: Support chatbots splitting billing, technical support, and account questions, or search gateways routing across wikis, live databases, and announcements.

3. Handoff / Swarm (peer control transfer)

Instead of a central controller, peer agents dynamically hand off active session control to one another—the model popularized by OpenAI’s Swarm architecture.

  • How it works: A Triage Agent handles the opening conversation. When the user asks for a refund, it calls transfer_to_billing(), passing active control and conversation context to the Billing Agent to finish the request.
  • Why it works: Adding a new specialist doesn’t require rewriting a central planner, and conversational sessions feel direct.
  • Best fit: Interactive multi-domain support desks and sequential ticket triage flows.

Choosing a pattern—and when not to go multi-agent

CriterionSupervisor-WorkerRouterHandoff (Swarm)
Control flowHierarchical (centralized)Single-shot dispatch (gateway)Decentralized (peer transfer)
Context isolationHighest (summaries only)High (independent sessions)Medium (passes conversation state)
Tools per agent3–5~53–7
Typical latencyMedium to high (multi-hop)Lowest (one route, direct run)Fast (one active agent at a time)
Failure recoveryStrong (supervisor can reassign)Moderate (requires re-routing)Moderate (needs loop guards)

Don’t reach for a multi-agent architecture by default. If your task needs fewer than five tools, finishes in a couple of turns, and doesn’t pull massive raw logs into context, a single well-prompted agent is simpler, faster, and cheaper to debug. Multi-agent systems add serialization, prompt-handoff bugs, and coordination latency—pay that tax only when context bloat or tool count actually degrades a single agent.


Designing an Agent-to-Agent (A2A) message envelope

Passing raw strings between agents makes it hard to track who sent what, whether a task succeeded, or where artifacts live. A typed message envelope keeps coordination explicit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/main/kotlin/com/example/agent/orchestration/model/AgentMessage.kt
package com.example.agent.orchestration.model

import java.time.Instant
import java.util.UUID

enum class MessageType {
    TASK_ASSIGNMENT, // Assign work (Supervisor -> Worker)
    TASK_PROGRESS,   // Intermediate status update (Worker -> Supervisor)
    TASK_COMPLETE,   // Final summary and artifact pointers (Worker -> Supervisor)
    TASK_FAILED,     // Failure report (Worker -> Supervisor)
    PEER_HANDOFF     // Transfer active control (Agent -> Agent)
}

data class AgentMessage(
    val messageId: String = UUID.randomUUID().toString(),
    val senderId: String,
    val recipientId: String,
    val type: MessageType,
    val summary: String,
    val payload: Map<String, Any> = emptyMap(),
    val timestamp: Instant = Instant.now()
)

Two messaging rules prevent most orchestration failures:

  1. Keep raw logs out of the envelope: Write 10,000-line build logs to a local artifact file and put only a short summary plus the file path in TASK_COMPLETE.
  2. Support async cancellation: The supervisor shouldn’t block blindly on a worker. Run workers inside an async loop with strict timeouts so stalled workers can be cancelled cleanly.

Workspace isolation with Git worktrees

The nastiest bug in parallel coding agents is two workers editing the same directory at the same time. Concurrent file writes cause race conditions, half-applied diffs, and broken builds.

sequenceDiagram
    autonumber
    actor User as User
    participant Sup as Supervisor
    participant CoderA as Coder A (Feature)
    participant CoderB as Coder B (Refactor)
    participant FS as Filesystem (Git Worktree)

    User->>Sup: Implement feature and refactor in parallel
    Sup->>FS: branch_workspace(branch: "agent/feature-a")
    Sup->>FS: branch_workspace(branch: "agent/refactor-b")
    Sup->>CoderA: Spawn worker (bind Workspace A)
    Sup->>CoderB: Spawn worker (bind Workspace B)

    par Isolated parallel execution
        CoderA->>FS: Edit and build in Workspace A
        CoderB->>FS: Edit and build in Workspace B
    end

    CoderA-->>Sup: Report completion (return diff)
    CoderB-->>Sup: Report completion (return diff)
    Sup->>FS: Verify and merge changes safely
    Sup-->>User: Return final report

I split workspace modes into three levels:

  • Inherit mode: Shares the parent directory directly. Use this only for read-only researchers and reviewers.
  • Branch mode: Creates an isolated working copy via git worktree (or a temporary clone). If a worker corrupts files or fails tests, you delete the directory without touching the main working tree.
  • Share mode: Shares the underlying Git object store while isolating each worker’s index and working tree, saving disk space while keeping branch edits separate.

Implementing a Supervisor orchestrator in Kotlin

Here’s a minimal Kotlin coroutines sketch showing how a supervisor coordinates a read-only researcher (INHERIT) followed by a coding worker (BRANCH).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// src/main/kotlin/com/example/agent/orchestration/engine/SupervisorOrchestrator.kt
package com.example.agent.orchestration.engine

import com.example.agent.orchestration.model.AgentMessage
import com.example.agent.orchestration.model.MessageType
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import java.io.File
import java.util.UUID

data class SubagentSpec(
    val name: String,
    val role: String,
    val systemPrompt: String,
    val tools: List<String>,
    val workspaceMode: WorkspaceMode = WorkspaceMode.BRANCH
)

enum class WorkspaceMode { INHERIT, BRANCH, SHARE }

class SupervisorOrchestrator(
    private val baseWorkspaceDir: File
) {
    suspend fun executeComplexTask(taskDescription: String): String = coroutineScope {
        println("=== [Supervisor] Decomposing task: $taskDescription ===")

        // 1. Define role-scoped subagents
        val subtasks = listOf(
            SubagentSpec(
                name = "research-worker",
                role = "Codebase Researcher",
                systemPrompt = "Inspect the codebase and return a concise summary of edit targets.",
                tools = listOf("view_file", "search_code"),
                workspaceMode = WorkspaceMode.INHERIT
            ),
            SubagentSpec(
                name = "code-worker",
                role = "Feature Developer",
                systemPrompt = "Implement the requested changes and verify the build.",
                tools = listOf("replace_file_content", "write_to_file", "run_build"),
                workspaceMode = WorkspaceMode.BRANCH
            )
        )

        // 2. Run read-only researcher first
        val researchDeferred = async {
            val workspace = prepareWorkspace(subtasks[0])
            runWorker(subtasks[0], workspace, "Map auth module dependencies")
        }

        val researchResult = researchDeferred.await()
        println("=== [Supervisor] Research complete; summary received without raw log bloat ===")

        // 3. Pass only the distilled summary to the coding worker
        val coderDeferred = async {
            val workspace = prepareWorkspace(subtasks[1])
            runWorker(
                subtasks[1],
                workspace,
                "Refactor based on research summary: ${researchResult.summary}"
            )
        }

        val coderResult = coderDeferred.await()
        "Task complete:\n- Research: ${researchResult.summary}\n- Changes: ${coderResult.summary}"
    }

    private fun prepareWorkspace(spec: SubagentSpec): File {
        return when (spec.workspaceMode) {
            WorkspaceMode.INHERIT -> baseWorkspaceDir
            WorkspaceMode.BRANCH -> {
                val branchDir = File(
                    baseWorkspaceDir.parentFile,
                    "workspaces/${spec.name}-${UUID.randomUUID().toString().take(8)}"
                )
                branchDir.mkdirs()
                // Run `git worktree add` or create an isolated snapshot here
                println("[Workspace] Created isolated workspace for ${spec.name}: ${branchDir.absolutePath}")
                branchDir
            }
            WorkspaceMode.SHARE -> baseWorkspaceDir
        }
    }

    private suspend fun runWorker(
        spec: SubagentSpec,
        workspace: File,
        instruction: String
    ): AgentMessage {
        println("[${spec.name}] Starting: '$instruction' (dir: ${workspace.name})")
        // Execute the actual LLM tool loop here
        return AgentMessage(
            senderId = spec.name,
            recipientId = "supervisor",
            type = MessageType.TASK_COMPLETE,
            summary = "${spec.role} finished and verified output",
            payload = mapOf("workspacePath" to workspace.absolutePath)
        )
    }
}

Externalizing topology in YAML

Keep model assignments, delegation limits, and tool allowlists in configuration rather than hardcoding them in Kotlin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# config/orchestration-topology.yml
orchestrator:
  name: "project-supervisor"
  model: "claude-3-5-sonnet"
  delegation_limit: 5
  timeout_seconds: 600

workers:
  - id: "researcher"
    role: "Codebase Researcher"
    model: "claude-3-5-haiku" # Fast, low-cost model for exploration
    workspace_mode: "inherit"
    allowed_tools:
      - "view_file"
      - "search_web"
      - "code_search"
    max_tokens_per_turn: 4096

  - id: "developer"
    role: "Core Developer"
    model: "claude-3-5-sonnet" # Stronger reasoning model for code edits
    workspace_mode: "branch"
    allowed_tools:
      - "write_to_file"
      - "replace_file_content"
      - "run_command"
    max_tokens_per_turn: 8192

Always set a hard delegation_limit and timeout_seconds on both Supervisor and Handoff topologies. Without a hop cap, two peer agents can bounce a request back and forth until your API budget runs dry.


Production checklist

Before moving a multi-agent workflow into production, verify these four rules:

  • Keep the supervisor’s context clean: Never forward raw worker logs into the parent conversation—pass distilled summaries and artifact paths.
  • Cap tools per agent at around five: Narrow tool sets keep function-calling accuracy high and reduce schema confusion.
  • Isolate every write-capable worker: Use git worktree or branch workspaces so concurrent edits never collide on the main tree.
  • Enforce hop limits and timeouts: Bound delegation depth and execution time so loops fail fast instead of burning tokens silently.

Once multiple agents can edit files and run commands in parallel, the next question is how to keep destructive actions safe. In Human-in-the-loop approvals and sandboxing for AI agents, I cover risk tiers, approval gates, and secret-masking guardrails.

This post is licensed under CC BY 4.0 by the author.