
Orchestrating the AI Swarm: A Reproducible Architecture for Claude Code, Codex, and Grok Agents
Build a reproducible, containerized workspace to run Claude Code, Codex, and Grok coding agents in parallel with isolated sandboxes, shared state, and audit trails.
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,
run_root / agent.name,
task_file,
): agent
for agent in cfg.agents
}
for future in concurrent.futures.as_completed(futures):
agent = futures[future]
try:
result = future.result()
except Exception as exc: # noqa: BLE001
result = AgentResult(
name=agent.name,
status="error",
exit_code=-1,
duration_seconds=0.0,
run_dir=run_root / agent.name,
patch_path=run_root / agent.name / "out" / "agent.patch",
transcript_path=run_root / agent.name / "out" / "transcript.log",
error=repr(exc),
)
results.append(result)
print(f"[{result.status:>10}] {result.name} ({result.duration_seconds:.1f}s)")
results.sort(key=lambda r: r.name)
return results
def write_manifest(
cfg: SwarmConfig,
run_id: str,
task: str,
results: list[AgentResult],
) -> Path:
run_root = cfg.work_root / run_id
manifest = {
"run_id": run_id,
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"task_sha256": hashlib.sha256(task.encode("utf-8")).hexdigest(),
"image": cfg.image,
"base_ref": cfg.base_ref,
"repo_url": cfg.repo_url,
"timeout_seconds": cfg.timeout_seconds,
"agents": [
{
"name": r.name,
"status": r.status,
"exit_code": r.exit_code,
"duration_seconds": round(r.duration_seconds, 2),
"patch_sha256": sha256_file(r.patch_path) if r.patch_path.exists() else None,
"error": r.error,
}
for r in results
],
}
path = run_root / "manifest.json"
path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
return path
def main() -> int:
parser = argparse.ArgumentParser(description="Run a swarm of coding agents.")
parser.add_argument("--task-file", required=True)
parser.add_argument("--task", default=None, help="Inline task text.")
parser.add_argument("--run-id", default=None)
args = parser.parse_args()
task = args.task or Path(args.task_file).read_text(encoding="utf-8")
cfg = SwarmConfig.from_env()
run_id = args.run_id or time.strftime("%Y%m%d-%H%M%S")
results = run_swarm(cfg, task, run_id)
manifest = write_manifest(cfg, run_id, task, results)
print(f"\nManifest: {manifest}")
return 0 if any(r.status == "succeeded" for r in results) else 1
if __name__ == "__main__":
raise SystemExit(main())
7. Adding Verification and Merge Gates
An agent's exit code tells you nothing about correctness. A patch that compiles can still be wrong. The verification stage applies each patch to a fresh clone and runs the project's own checks.
# swarm/verify.py
from __future__ import annotations
import json
import shutil
import subprocess
from dataclasses import dataclass
from pathlib import Path
from .config import SwarmConfig
from .runner import AgentResult
@dataclass
class VerifyResult:
name: str
passed: bool
checks: dict[str, dict[str, object]]
log: str
def _git_clone(cfg: SwarmConfig, dest: Path) -> None:
if dest.exists():
shutil.rmtree(dest)
dest.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(
["git", "clone", "--no-hardlinks", "--branch", cfg.base_ref, cfg.repo_url, str(dest)],
check=True,
capture_output=True,
)
def verify_agent(cfg: SwarmConfig, result: AgentResult) -> VerifyResult:
work = result.run_dir / "verify"
_git_clone(cfg, work)
if not result.patch_path.exists() or result.patch_path.stat().st_size == 0:
return VerifyResult(
name=result.name,
passed=False,
checks={},
log="no patch to verify",
)
apply = subprocess.run(
["git", "apply", "--check", str(result.patch_path)],
cwd=work,
capture_output=True,
text=True,
)
if apply.returncode != 0:
return VerifyResult(
name=result.name,
passed=False,
checks={"apply": {"ok": False, "stderr": apply.stderr.strip()}},
log=apply.stderr,
)
subprocess.run(
["git", "apply", str(result.patch_path)],
cwd=work,
check=True,
capture_output=True,
)
checks: dict[str, dict[str, object]] = {}
commands = {
"test": ["python", "-m", "pytest", "-q"],
"lint": ["python", "-m", "compileall", "-q", "src"],
}
for label, cmd in commands.items():
proc = subprocess.run(cmd, cwd=work, capture_output=True, text=True, timeout=600)
checks[label] = {
"ok": proc.returncode == 0,
"exit_code": proc.returncode,
"stdout": proc.stdout[-4000:],
"stderr": proc.stderr[-4000:],
}
passed = all(bool(c["ok"]) for c in checks.values())
log = "\n\n".join(
f"== {label} ==\n{c['stdout']}\n{c['stderr']}" for label, c in checks.items()
)
return VerifyResult(name=result.name, passed=passed, checks=checks, log=log)
Wire verification into the orchestrator and produce a ranked summary:
# swarm/orchestrator.py (additions)
from .verify import verify_agent, VerifyResult
def run_verification(cfg: SwarmConfig, results: list[AgentResult]) -> list[VerifyResult]:
verified: list[VerifyResult] = []
with concurrent.futures.ThreadPoolExecutor(max_workers=len(results)) as pool:
futures = {
pool.submit(verify_agent, cfg, r): r for r in results if r.status == "succeeded"
}
for future in concurrent.futures.as_completed(futures):
agent = futures[future]
try:
vr = future.result()
except Exception as exc: # noqa: BLE001
vr = VerifyResult(name=agent.name, passed=False, checks={}, log=repr(exc))
verified.append(vr)
print(f"[{'PASS' if vr.passed else 'FAIL':>4}] {vr.name}")
verified.sort(key=lambda v: v.name)
return verified
Now the merge gate. The orchestrator never merges automatically by default. It prepares a branch and a patch file for review:
# swarm/merge.py
from __future__ import annotations
import subprocess
from pathlib import Path
from .config import SwarmConfig
from .runner import AgentResult
from .verify import VerifyResult
def prepare_merge_branch(
cfg: SwarmConfig,
result: AgentResult,
verification: VerifyResult,
) -> str:
"""Create a local branch containing only the verified agent's changes."""
branch = f"swarm/{result.name}"
subprocess.run(
["git", "clone", "--no-hardlinks", "--branch", cfg.base_ref, cfg.repo_url, ".merge-workspace"],
check=True,
capture_output=True,
)
work = Path(".merge-workspace")
subprocess.run(
["git", "apply", str(result.patch_path)],
cwd=work,
check=True,
capture_output=True,
)
subprocess.run(["git", "checkout", "-b", branch], cwd=work, check=True, capture_output=True)
subprocess.run(["git", "add", "-A"], cwd=work, check=True, capture_output=True)
subprocess.run(
["git", "-c", "user.email=swarm@local", "-c", "user.name=swarm",
"commit", "-m", f"swarm: {result.name} candidate patch"],
cwd=work,
check=True,
capture_output=True,
)
return branch
8. Reproducibility: Pinning, Hashing, and Replaying
Reproducibility means you can reconstruct the exact inputs of a run and replay it.
Pin the image by digest. Tags move. Digests do not.
# Pin at build time, reference at run time.
IMAGE="registry.example.com/ai-swarm-agent@sha256:9f2c1e..."
export SWARM_IMAGE="$IMAGE"
Hash the task. The manifest stores task_sha256, so you can prove two runs used the same instruction.
Hash the patch. Each agent's patch gets a SHA-256 in the manifest. If a patch changes, the hash changes.
Freeze the repository state. Clone a specific commit, not a moving branch:
BASE_SHA=$(git -C sample-app rev-parse HEAD)
export SWARM_BASE_REF="$BASE_SHA"
Record the environment. Capture tool versions inside the image:
docker run --rm ai-swarm-agent:local bash -lc \
'claude --version; codex --version; grok --version; python --version'
Store that output alongside the manifest:
mkdir -p runs/$RUN_ID
docker run --rm ai-swarm-agent:local bash -lc \
'claude --version; codex --version; grok --version' \
> runs/$RUN_ID/tool-versions.txt 2>&1
Replay a run. Because the manifest records the task hash, image digest, and base commit, replaying means pointing the same inputs at the same image:
export SWARM_IMAGE="registry.example.com/ai-swarm-agent@sha256:9f2c1e..."
export SWARM_BASE_REF="a1b2c3d4e5f6..."
python -m swarm.orchestrator --task-file task.md --run-id replay-001
The agent outputs will not be byte-identical, because these models are not deterministic. What is reproducible is the environment: same code, same toolchain, same task, same permissions. That is the meaningful guarantee.
9. Running the Swarm End to End
Write the task file:
cat > task.md <<'MD'
Implement safe division in src/calc.py.
Requirements:
- divide(a, b) must raise ValueError (not ZeroDivisionError) when b == 0.
- When both a and b are ints, return an int (integer division semantics).
- When either argument is a float, return a float.
- Do not change the signatures of add or divide.
- Add pytest tests covering zero division, integer division, and float division.
- Run `make test` and make sure it passes.
MD
Export the environment and run:
cd ~/ai-swarm
export SWARM_REPO_URL="file://$HOME/ai-swarm/sample-app"
export SWARM_BASE_REF="$(git -C sample-app rev-parse HEAD)"
export SWARM_IMAGE="ai-swarm-agent:local"
export SWARM_TIMEOUT=600
export ANTHROPIC_API_KEY="..."
export OPENAI_API_KEY="..."
export XAI_API_KEY="..."
python -m swarm.orchestrator --task-file task.md --run-id demo-001
Expected output:
[ succeeded] claude (47.2s)
[ succeeded] codex (39.8s)
[ timeout] grok (600.0s)
Manifest: runs/demo-001/manifest.json
Inspect the artifacts:
ls -la runs/demo-001/claude/out/
cat runs/demo-001/claude/out/changed_files.txt
cat runs/demo-001/claude/out/agent.patch
The patch is a standard unified diff, so it works with every Git tool:
git -C sample-app apply --check runs/demo-001/claude/out/agent.patch
git -C sample-app apply runs/demo-001/claude/out/agent.patch
git -C sample-app diff
To compare candidates side by side, generate a diff between two agents' outputs:
diff -u \
runs/demo-001/claude/out/agent.patch \
runs/demo-001/codex/out/agent.patch \
| head -60
10. Production Hardening
Network policy. The --network none flag in the runner blocks outbound traffic entirely, which breaks the agent API calls. In production, route egress through a proxy that allowlists only the provider endpoints, and deny everything else:
# docker-compose.swarm.yml
services:
agent-runner:
image: registry.example.com/ai-swarm-agent@sha256:9f2c1e...
network_mode: "none"
read_only: true
tmpfs:
- /tmp:exec,size=256m
- /home/agent:exec,size=512m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "2"
memory: 4G
pids: 512
For provider access, use a sidecar proxy container on a dedicated network and set HTTPS_PROXY for the agent only. That way the agent container itself never has general network reach.
Secret handling. Never bake credentials into the image or write them into the task file. Prefer short-lived, scoped tokens issued per run. If your provider supports it, use a credential broker that mints a token with a budget ceiling.
Cost ceilings. Enforce limits at two levels: a token ceiling inside the agent CLI if it supports one, and a wall-clock timeout in the orchestrator. Add a global budget check before launching each agent:
# swarm/budget.py
import os
from dataclasses import dataclass
@dataclass
class Budget:
max_usd_per_run: float
max_usd_per_agent: float
@classmethod
def from_env(cls) -> "Budget":
return cls(
max_usd_per_run=float(os.environ.get("SWARM_MAX_USD_RUN", "5.00")),
max_usd_per_agent=float(os.environ.get("SWARM_MAX_USD_AGENT", "2.00")),
)
Output sanitization. Agent transcripts can contain secrets if the agent reads a config file. Scrub before publishing artifacts:
# swarm/sanitize.py
import re
from pathlib import Path
SECRET_PATTERNS = [
re.compile(r"sk-[A-Za-z0-9]{20,}"),
re.compile(r"xai-[A-Za-z0-9]{20,}"),
re.compile(r"AKIA[0-9A-Z]{16}"),
re.compile(r"gh[pousr]_[A-Za-z0-9]{30,}"),
]
def scrub(text: str) -> str:
for pattern in SECRET_PATTERNS:
text = pattern.sub("[REDACTED]", text)
return text
def scrub_file(path: Path) -> None:
if not path.exists():
return
path.write_text(scrub(path.read_text(encoding="utf-8", errors="replace")), encoding="utf-8")
Structured summaries. Raw transcripts are hard to compare. Ask each agent to emit a summary file with a fixed schema, and validate it:
# swarm/summary.py
import json
from pathlib import Path
REQUIRED_KEYS = {"approach", "files_changed", "tests_added", "known_risks", "follow_ups"}
def load_summary(path: Path) -> dict | None:
if not path.exists():
return None
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return None
if not REQUIRED_KEYS.issubset(data.keys()):
return None
return data
Add an instruction to the task file:
When finished, write a JSON file at /out/summary.json with exactly these keys:
"approach", "files_changed", "tests_added", "known_risks", "follow_ups".
Idempotency and cleanup. A crashed run leaves containers behind. Add a janitor:
#!/usr/bin/env bash
# swarm/cleanup.sh
set -euo pipefail
docker ps -a --filter 'name=swarm-' --format '{{.ID}}' | xargs -r docker rm -f
find ./runs -maxdepth 1 -type d -mtime +14 -exec rm -rf {} +
Observability. Emit structured events per agent so you can build dashboards:
import json
import sys
def emit(event: str, **fields) -> None:
print(json.dumps({"event": event, **fields}), file=sys.stderr, flush=True)
Call emit("agent_finished", name=..., status=..., duration_seconds=...) from the orchestrator. Ship those lines to your log pipeline.
Cost and latency reality check. Three agents working the same task is not automatically better than one. You are paying three times the inference cost and getting three candidate patches. The swarm wins when the task is decomposable, the agents are given distinct roles, or you want a diversity of approaches to compare. If all three agents receive the identical prompt, you mostly get three samples of the same distribution.
A better pattern is role specialization:
# claude: implement the feature
export SWARM_CLAUDE_ROLE="Implement the feature and its tests."
# codex: review and harden
export SWARM_CODEX_ROLE="Review the existing implementation for edge cases and add defensive tests. Do not rewrite working code."
# grok: independent second implementation
export SWARM_GROK_ROLE="Implement the feature independently, optimizing for readability and minimal diff size."
Then pass the role into the task file per agent. Modify execute_agent to write a per-agent task file rather than sharing one:
# In execute_agent, replace the shared task mount with a per-agent one.
agent_task_file = run_dir / "task.md"
agent_task_file.write_text(task_text, encoding="utf-8")
and mount agent_task_file instead of the shared one. This small change turns three redundant workers into a genuine pipeline.
11. Frequently Asked Questions
Do I need a separate container per agent, or can I use separate directories?
Separate directories solve file collisions but not process isolation, resource limits, or credential scoping. Containers give you enforceable boundaries: memory caps, PID limits, dropped capabilities, and a filesystem you can throw away. For anything beyond a local experiment, use containers.
How do I prevent an agent from committing to my main branch?
Do not mount your working repository into agent containers at all. The orchestrator clones per agent, and the entrypoint script commits only to establish a baseline for diffing. Your real repository is never mounted read-write into a container that runs an agent. Merge happens exclusively through the verification gate.
How do I keep costs predictable with three agents?
Set a wall-clock timeout per agent, use a token or cost ceiling in each CLI where available, and enforce a per-run budget in the orchestrator before dispatching. Also scope the task: narrow the prompt, give the agent a file list, and tell it explicitly what not to touch. Most cost overruns come from vague tasks, not from the number of agents.
Can I run this in CI?
Yes, and you should. Run the swarm on a schedule or on labeled issues, publish each agent's patch as a CI artifact, and open a pull request per verified candidate. The manifest and tool-versions file give reviewers the provenance they need. Keep the merge step manual until you have measured how often the automated gate produces correct patches.
For more on building production AI engineering workflows, see Tamiz's Insights.