Originally published on tamiz.pro.

Running three frontier coding agents in the same directory is a reliability problem waiting to happen. They overwrite each other's files, compete for the same Git index, leak credentials into shell history, and leave you with a transcript that cannot be reproduced six months later. The fix is not a clever prompt. It is an architecture: one immutable base image, one cloned repository per agent, one sandbox per agent, and a deterministic merge stage where a human or a verifier decides what survives.

This tutorial builds that architecture from scratch using Docker, Dev Containers, and a small Python orchestrator. The result is a reproducible environment where Claude Code, OpenAI Codex CLI, and xAI's Grok CLI can work concurrently against the same codebase without stepping on one another.

  • 1. The Failure Modes of Unmanaged Agents
  • 2. Target Architecture
  • 3. Prerequisites
  • 4. Building the Immutable Workspace Image
  • 5. Writing Agent Adapters
  • 6. Building the Orchestrator
  • 7. Adding Verification and Merge Gates
  • 8. Reproducibility: Pinning, Hashing, and Replaying
  • 9. Running the Swarm End to End
  • 10. Production Hardening
  • 11. Frequently Asked Questions

1. The Failure Modes of Unmanaged Agents

The naive setup looks like this:

# Do not do this claude "implement pagination" & codex "implement pagination" & grok "implement pagination" & wait 

Every agent sees the same working tree. Every agent can run git add ., git commit, or git checkout. Every agent inherits the same environment variables. Every agent writes to the same log file. The result is nondeterministic and frequently corrupt.

The concrete problems:

Failure mode What actually happens Architectural fix
Shared working tree Agents overwrite each other's edits mid-run One clone per agent
Shared .git index Concurrent git add corrupts the staging area Never let agents touch the parent repo's Git metadata
Credential bleed Tokens leak into shell history, traces, or diffs Per-agent secret injection, scrubbed transcripts
Unpinned toolchain Agent behavior changes when a CLI auto-updates Version-pinned base image
No verification You cannot tell which agent produced correct code Automated test/lint gate before merge
Unreviewable diffs Three agents' changes collapse into one noisy patch Per-agent branch, diff artifact, structured summary
Unbounded execution An agent loops until it exhausts your budget Wall-clock timeout, token ceiling, kill switch

The mental model: treat each coding agent as an untrusted, nondeterministic function. Its inputs are a prompt, a repository snapshot, and a tool environment. Its output is a proposed patch plus a transcript. Your orchestrator's job is to make the inputs hermetic and the outputs reviewable.

2. Target Architecture

The architecture has five layers.

Layer 1: Immutable base image. A single Dockerfile pins the runtime, language toolchains, and the three agent CLIs at exact versions. The image is built once and referenced by digest.

Layer 2: Per-agent isolation. Each agent gets its own container with its own clone of the repository, mounted only at a dedicated work directory. The parent repository is never mounted read-write into agent containers.

Layer 3: Adapter interface. Each vendor CLI is wrapped in a small adapter that exposes the same contract: take a prompt, run headlessly, emit a patch, emit a transcript, exit with a status. Swapping vendors means writing one adapter, not rewriting the orchestrator.

Layer 4: Orchestrator. A Python process clones the repo N times, launches one container per agent, streams logs, enforces timeouts, and collects artifacts into a run directory.

Layer 5: Verification and merge gate. Each agent's patch is applied to a fresh verification clone, where tests and linters run. Only patches that pass and that a reviewer approves get merged.

 +-------------------------+ | Orchestrator (host) | | clones, dispatches, gates| +------------+------------+ | +----------------------+----------------------+ | | | +------v------+ +------v------+ +------v------+ | Container | | Container | | Container | | Claude Code| | Codex | | Grok | | work/clone | | work/clone | | work/clone | +------+------+ +------+------+ +------+------+ | | | +----------------------+----------------------+ | +------------v------------+ | Verification clones | | tests -> lint -> review | +------------+------------+ | +------------v------------+ | Merge to target branch | +-------------------------+ 

The key invariant: no two agents ever share a writable filesystem. Concurrency is handled by the orchestrator, not by hoping the agents cooperate.

3. Prerequisites

You need:

  • Docker Engine 24.0 or newer, with the Compose plugin
  • Git 2.40 or newer
  • Python 3.11 or newer on the host
  • API credentials for the three providers, exported as environment variables
  • A repository you can clone locally

Verify the environment:

docker --version docker compose version git --version python3 --version 

Set up a working directory:

mkdir -p ~/ai-swarm && cd ~/ai-swarm git init 

This tutorial uses a small sample repository so the results are verifiable. Create it:

mkdir -p sample-app/src sample-app/tests cd sample-app cat > src/calc.py <<'PY' def add(a, b): return a + b def divide(a, b): return a / b PY cat > tests/test_calc.py <<'PY' from src.calc import add, divide def test_add(): assert add(2, 3) == 5 def test_divide_by_zero_raises(): try: divide(1, 0) except ZeroDivisionError: return raise AssertionError("expected ZeroDivisionError") PY cat > pyproject.toml <<'TOML' [project] name = "sample-app" version = "0.1.0" requires-python = ">=3.11" [tool.pytest.ini_options] testpaths = ["tests"] TOML cat > Makefile <<'MAKE' test: python -m pytest -q lint: python -m compileall -q src MAKE git add -A git commit -m "Initial sample application" 

The task you will give the agents is deliberately specific and testable:

Implement safe division. divide(a, b) must raise ValueError when b == 0, and must preserve integer division semantics when both arguments are integers. Add tests. Do not change the public function signatures.

4. Building the Immutable Workspace Image

Create the project structure:

cd ~/ai-swarm mkdir -p swarm/adapters swarm/templates touch swarm/__init__.py swarm/adapters/__init__.py 

Now write the Dockerfile. The important detail is pinning: use exact versions, never latest.

# swarm/templates/Dockerfile.agent FROM python:3.12.4-slim-bookworm ENV DEBIAN_FRONTEND=noninteractive \ PYTHONUNBUFFERED=1 \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ GIT_TERMINAL_PROMPT=0 \ npm_config_update_notifier=false RUN apt-get update && apt-get install -y --no-install-recommends \ git \ ca-certificates \ curl \ jq \ ripgrep \ make \ nodejs \ npm \ && rm -rf /var/lib/apt/lists/* # Pin the three agent CLIs to exact versions. RUN npm install -g \ @anthropic-ai/claude-code@1.0.53 \ @openai/codex@0.20.0 \ @vibe-kit/grok-cli@1.0.0 \ && npm cache clean --force # Pin Python tooling used by the verification gate. RUN pip install --no-cache-dir \ pytest==8.3.3 \ ruff==0.6.9 WORKDIR /workspace # Non-root by default. The orchestrator overrides the UID when needed. RUN useradd --create-home --uid 10001 agent \ && chown -R agent:agent /workspace USER agent CMD ["sleep", "infinity"] 

A note on version numbers: check the actual release tags for each CLI before you build, and update the pins. The mechanism is what matters, not the specific strings. If a CLI ships as a standalone binary rather than an npm package, replace the install step with a checksum-verified download.

Build it and record the digest:

cd ~/ai-swarm docker build -f swarm/templates/Dockerfile.agent -t ai-swarm-agent:local . # The digest is what you pin in production. docker image inspect ai-swarm-agent:local --format '{{index .RepoDigests 0}}' 

For a local build without a registry, RepoDigests may be empty. Inspect the image ID instead:

docker image inspect ai-swarm-agent:local --format '{{.Id}}' 

In production, push to a registry and reference the manifest digest:

docker tag ai-swarm-agent:local registry.example.com/ai-swarm-agent:2024-06-01 docker push registry.example.com/ai-swarm-agent:2024-06-01 

5. Writing Agent Adapters

Each adapter is a shell script that runs inside the container. It receives the task via an environment variable and writes two artifacts into the work directory: agent.patch and transcript.log.

Create a shared entrypoint that every adapter uses:

cat > swarm/templates/entrypoint.sh <<'SH' #!/usr/bin/env bash set -euo pipefail TASK_FILE="${TASK_FILE:-/task.md}" OUT_DIR="${OUT_DIR:-/out}" ADAPTER="$1" mkdir -p "$OUT_DIR" # Never let the agent commit. The orchestrator owns Git history. git config --global user.email "agent@swarm.local" git config --global user.name "AI Swarm Agent" git config --global commit.gpgsign false git config --global core.hooksPath /dev/null cd /workspace git add -A git commit -m "baseline snapshot" --allow-empty >/dev/null 2>&1 || true BASE_COMMIT="$(git rev-parse HEAD)" set +e "$ADAPTER" "$TASK_FILE" 2>&1 | tee "$OUT_DIR/transcript.log" EXIT_CODE="${PIPESTATUS[0]}" set -e # Produce a patch of everything the agent changed. git add -A git diff --cached --binary "$BASE_COMMIT" > "$OUT_DIR/agent.patch" || true # Also export the resulting tree so the verifier can use it directly. git diff --cached --name-only "$BASE_COMMIT" > "$OUT_DIR/changed_files.txt" || true printf '%s\n' "$EXIT_CODE" > "$OUT_DIR/exit_code" printf '%s\n' "$BASE_COMMIT" > "$OUT_DIR/base_commit" exit "$EXIT_CODE" SH chmod +x swarm/templates/entrypoint.sh 

Now the three adapters. Each one is deliberately non-interactive, because an agent waiting on a TTY prompt will hang until your timeout fires.

cat > swarm/adapters/claude.sh <<'SH' #!/usr/bin/env bash set -euo pipefail TASK="$(cat "$1")" # --print runs headlessly. --permission-mode bypasses interactive approval # prompts; only do this inside an isolated sandbox. claude \ --print \ --permission-mode bypassPermissions \ --output-format text \ "$TASK" SH cat > swarm/adapters/codex.sh <<'SH' #!/usr/bin/env bash set -euo pipefail TASK="$(cat "$1")" # codex exec runs a single non-interactive turn. codex exec \ --skip-git-repo-check \ "$TASK" SH cat > swarm/adapters/grok.sh <<'SH' #!/usr/bin/env bash set -euo pipefail TASK="$(cat "$1")" # --yes suppresses interactive confirmations. grok \ --yes \ --no-submit \ "$TASK" SH chmod +x swarm/adapters/*.sh 

The flags vary between CLI versions. Treat these as the shape of the adapter, and validate against the --help output of the version you pinned. The contract the orchestrator depends on is the artifact set, not the flag spelling.

6. Building the Orchestrator

The orchestrator is a Python program that owns all the concurrency. It clones the repository per agent, runs each container, and collects artifacts.

First, the configuration module:

# swarm/config.py from __future__ import annotations import os from dataclasses import dataclass, field from pathlib import Path @dataclass(frozen=True) class AgentSpec: name: str adapter: str secret_env: str extra_env: dict[str, str] = field(default_factory=dict) @dataclass(frozen=True) class SwarmConfig: repo_url: str base_ref: str image: str agents: tuple[AgentSpec, ...] timeout_seconds: int = 900 work_root: Path = Path("./runs") @classmethod def from_env(cls) -> "SwarmConfig": repo_url = os.environ["SWARM_REPO_URL"] base_ref = os.environ.get("SWARM_BASE_REF", "HEAD") image = os.environ.get("SWARM_IMAGE", "ai-swarm-agent:local") timeout_seconds = int(os.environ.get("SWARM_TIMEOUT", "900")) agents = ( AgentSpec( name="claude", adapter="claude.sh", secret_env="ANTHROPIC_API_KEY", ), AgentSpec( name="codex", adapter="codex.sh", secret_env="OPENAI_API_KEY", ), AgentSpec( name="grok", adapter="grok.sh", secret_env="XAI_API_KEY", ), ) return cls( repo_url=repo_url, base_ref=base_ref, image=image, agents=agents, timeout_seconds=timeout_seconds, ) 

Next, the container runner. Notice that secrets are passed as environment variables to the container, not written into files or baked into the image:

# swarm/runner.py from __future__ import annotations import json import os import shutil import subprocess import time from dataclasses import dataclass from pathlib import Path from .config import AgentSpec, SwarmConfig @dataclass class AgentResult: name: str status: str exit_code: int duration_seconds: float run_dir: Path patch_path: Path transcript_path: Path error: str | None = None def _run(cmd: list[str], **kwargs) -> subprocess.CompletedProcess: return subprocess.run(cmd, check=True, capture_output=True, text=True, **kwargs) def prepare_clone(cfg: SwarmConfig, agent: AgentSpec, run_dir: Path) -> Path: """Create a fresh clone for one agent. Never reuse a working tree.""" clone_dir = run_dir / "workspace" if clone_dir.exists(): shutil.rmtree(clone_dir) clone_dir.parent.mkdir(parents=True, exist_ok=True) _run( [ "git", "clone", "--no-hardlinks", "--branch", cfg.base_ref, cfg.repo_url, str(clone_dir), ] ) return clone_dir def execute_agent( cfg: SwarmConfig, agent: AgentSpec, run_dir: Path, task_file: Path, ) -> AgentResult: clone_dir = prepare_clone(cfg, agent, run_dir) out_dir = run_dir / "out" out_dir.mkdir(parents=True, exist_ok=True) secret = os.environ.get(agent.secret_env) if not secret: return AgentResult( name=agent.name, status="skipped", exit_code=-1, duration_seconds=0.0, run_dir=run_dir, patch_path=out_dir / "agent.patch", transcript_path=out_dir / "transcript.log", error=f"missing credential env var {agent.secret_env}", ) container_name = f"swarm-{agent.name}-{os.getpid()}-{int(time.time())}" adapter_path = Path(__file__).parent / "adapters" / agent.adapter entrypoint_path = Path(__file__).parent / "templates" / "entrypoint.sh" cmd = [ "docker", "run", "--rm", "--name", container_name, "--network", "none", # no outbound network except via provider API proxy "--memory", "4g", "--cpus", "2", "--pids-limit", "512", "--cap-drop", "ALL", "--security-opt", "no-new-privileges:true", "-e", f"{agent.secret_env}", "-v", f"{clone_dir}:/workspace", "-v", f"{out_dir}:/out", "-v", f"{task_file}:/task.md:ro", "-v", f"{adapter_path}:/adapters/{agent.adapter}:ro", "-v", f"{entrypoint_path}:/entrypoint.sh:ro", "--workdir", "/workspace", cfg.image, "/bin/bash", "/entrypoint.sh", f"/adapters/{agent.adapter}", ] env_overrides = {k: v for k, v in agent.extra_env.items()} for key, value in env_overrides.items(): cmd[cmd.index("-e") + 1] = f"{key}={value}" started = time.monotonic() timed_out = False try: proc = subprocess.run( cmd, capture_output=True, text=True, timeout=cfg.timeout_seconds, ) exit_code = proc.returncode stdout = proc.stdout stderr = proc.stderr except subprocess.TimeoutExpired: timed_out = True exit_code = 124 stdout = "" stderr = f"timed out after {cfg.timeout_seconds}s" subprocess.run( ["docker", "kill", container_name], capture_output=True, ) duration = time.monotonic() - started (out_dir / "container.log").write_text(stdout + "\n" + stderr, encoding="utf-8") patch_path = out_dir / "agent.patch" transcript_path = out_dir / "transcript.log" if timed_out: status = "timeout" elif exit_code != 0: status = "failed" elif not patch_path.exists() or patch_path.stat().st_size == 0: status = "no_changes"\n else: status = "succeeded" return AgentResult( name=agent.name, status=status, exit_code=exit_code, duration_seconds=duration, run_dir=run_dir, patch_path=patch_path, transcript_path=transcript_path, error=stderr.strip()[:2000] if stderr.strip() else None, ) 

One important correction to the extra_env handling above: mutating cmd by index is fragile because -e appears more than once. Use a cleaner approach in your own code:

# swarm/runner.py (corrected env handling) for key, value in agent.extra_env.items(): cmd.extend(["-e", f"{key}={value}"]) 

Now the main orchestrator with a thread pool for parallel execution:

# swarm/orchestrator.py from __future__ import annotations import argparse import concurrent.futures import hashlib import json import shutil import subprocess import time from pathlib import Path from .config import SwarmConfig from .runner import AgentResult, execute_agent def sha256_file(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as fh: for chunk in iter(lambda: fh.read(65536), b""): h.update(chunk) return h.hexdigest() def run_swarm(cfg: SwarmConfig, task: str, run_id: str) -> list[AgentResult]: run_root = cfg.work_root / run_id run_root.mkdir(parents=True, exist_ok=True) task_file = run_root / "task.md" task_file.write_text(task, encoding="utf-8") results: list[AgentResult] = [] with concurrent.futures.ThreadPoolExecutor(max_workers=len(cfg.agents)) as pool: futures = { pool.submit( execute_agent, cfg, agent<...
Source:https://dev.to/tamizuddin/orchestrating-the-ai-swarm-a-reproducible-architecture-for-claude-code-codex-and-grok-agents-588