Agent Fusion (fusion)
Version Python Tests Providers License: MIT
Multi-model deliberation, nested coding swarms, quality-diversity evolution, and cross-family verification for Claude Code, OpenAI Codex CLI, and AndrewCode — zero API keys, zero Python dependencies, real CLI dispatch only.
Table of Contents
- Overview & Key Features
- Architecture & Tech Stack
- Getting Started
- Configuration & Environment Variables
- Collaboration Modes, Hive & Scripts
- Core 6 Deliberation & Execution Modes
- Hive, Designer & Board Modes
- 4-Pillar Council Upgrade Modes (
race,harden,evolve,ledger-moe,stigmergy,tui) - Advanced Swarm Topologies (
python/fusion_swarm) - Hive — nested AndrewCode swarm on one board
- How a run works
- What makes it good (and honest)
- Available Scripts & Entrypoints
- API, Board & Cockpit Reference
- Testing
- Deployment & Host Integration
- Troubleshooting
- Contributing
- Credit & Research Provenance
- License
Overview & Key Features
Agent Fusion (fusion) is a multi-agent orchestration plugin and Python standard-library swarm runtime that coordinates your locally installed AI coding CLIs (Claude Code, OpenAI Codex CLI, Gemini CLI, Grok, GitHub Copilot CLI, OpenCode, AndrewCode, and Ollama) as a disciplined engineering organization. Instead of routing through paid proxy APIs or asking one model to role-play a committee, Fusion spawns real OS subprocesses across distinct model families, isolates file mutations inside Git worktrees or macOS APFS copy-on-write clones, coordinates agents over a transactional SQLite WAL message board, and verifies code changes with deterministic test gates and cryptographic evidence receipts.
Single-model coding agents suffer from correlated blind spots: the model that writes a subtle bug rarely catches that same bug when asked to self-review. Naive multi-agent wrappers waste tokens by running 4-agent committees on one-line fixes or letting agents overwrite each other's files. Agent Fusion solves both failure modes. It routes tasks by risk and complexity (from zero-overhead solo up to panel, council, hive, race, harden, and evolve), enforces a strict anti-simulation contract (absent models are reported as ABSENT, never fabricated), and requires a different model family to audit plans and implementations before merge.
Key Features
- Cross-Family Deliberation & Anti-Conformity — Dispatches blind parallel fan-outs (
panel), anonymized cross-examination rounds with mandatory flaw-naming (council), adversarialdebate, blindvote, and multi-roundultimate-reviewacross distinct model families (claude,codex,gemini,grok,copilot,opencode,local). - Nested Hive Swarms on a Single SQLite WAL Board — Plans a validated
SwarmSpecwith an Architect (gpt-6-astraorclaude), spawns heterogeneous Captains and up tomax_childrennested workers (andrewcode), and coordinates them over.fusion/board.dbwithkqueueinstant wakeups (board.wakeup) and hook-driven agent re-wake (--hook-rewake). - Competitive Worktree Racing (
fusion race) — Spawns $N$ distinct model families in parallel isolated Git worktrees or APFS clones on the same task, runs your test suite in every lane, and promotes the fastest verified winner—or invokes a cross-family judge to cherry-pick the strongest diff hunks. - Adversarial Wave-Hardening (
fusion harden) — Runs iterative[Red-Team Critic ‖ Edge-Case Mutator] → Implementer Patch → Test Gatewaves until the critic finds zero high-severity defects and all tests pass. - MAP-Elites Quality-Diversity Evolution (
fusion evolve) — Evolves code across a 2D archive grid (correctness_bin×conciseness_bin) with multi-island ring migration and fast-to-slow cascade evaluation (AST syntax → unit tests → full benchmark). - Empirical Wilson-Score MoE Routing & Stigmergy (
fusion ledger-moe,board stigmergy) — Ranks(provider, role, task_type)combinations from.fusion/runs.jsonlusing the 95% Wilson lower confidence bound with latency tie-breaking, and shares expiring file/bug pheromone traces across parallel workers. - Live SSE Web Cockpit & Zero-Dependency Curses TUI (
fusion tui) — Streams real-time DAG topology, lane heartbeats, board messages, and stigmergy trails over Server-Sent Events (/api/stream) with interactive operator steering (POST /api/board/post), alongside a 4-pane terminal dashboard. - Zero-Copy APFS Workspaces & Cryptographic
REPO_RECEIPTHonesty — Provisions instant copy-on-write workspaces on macOS viacp -c(clonefile(2)) with automaticgit worktreefallback, and verifies reviewer file-inspection claims against SHA-256 digests (REPO_RECEIPT:VERIFIEDvsREPO_RECEIPT:UNVERIFIED).
Architecture & Tech Stack
System Context (C4 Level 1)
Agent Fusion sits between the engineer's host coding harness and the locally installed provider CLIs, coordinating isolated workspaces and durable state without external cloud services.
C4Context
title Agent Fusion — System Context (C4 Level 1)
Person(dev, "Software Engineer", "Invokes /fusion commands or CLI scripts in repository")
System_Ext(host, "Host Coding Harness", "Claude Code, OpenAI Codex CLI, or AndrewCode")
System(fusion, "Agent Fusion", "Multi-model deliberation, nested swarm orchestrator, and verification engine")
System_Ext(providers, "Local Provider CLIs", "claude, codex, gemini, grok, copilot, opencode, andrewcode, ollama")
SystemDb(repo, "Git Repository & .fusion State", "Git worktrees, APFS clones, SQLite WAL board.db, JSONL ledger")
Rel(dev, host, "Runs /fusion:* or fusion.py")
Rel(host, fusion, "Dispatches skills, commands, and MCP tools")
Rel(fusion, providers, "Spawns blind/scoped subprocesses via adapters")
Rel(fusion, repo, "Provisions worktrees/clones, persists board & receipts")
Container Architecture (C4 Level 2)
Inside Agent Fusion, bash entrypoints handle fast provider discovery and blind fan-out, while the zero-dependency fusion_swarm Python package manages DAG execution, SQLite WAL coordination, workspace isolation, and observability.
C4Container
title Agent Fusion — Container Architecture (C4 Level 2)
Person(user, "Engineer / Host Agent", "CLI, Slash Commands, or Web/TUI Operator")
Container(cli, "Bash & CLI Entrypoints", "Bash / Python 3", "fusion.sh, swarm.sh, ureview.sh, route.sh, fusion.py")
Container(engine, "Swarm & Evolution Engine", "python/fusion_swarm", "hive, team, race, harden, evolve, ledger_moe, graph, metaloop")
Container(coord, "Transactional Board & Mailbox", "SQLite WAL + JSONL", "board.py, mailbox.py, stigmergy_traces, kqueue board.wakeup")
Container(iso, "Workspace & Scope Isolator", "Git + APFS clonefile(2)", "workspaces.py, scope.py, supervision.py")
Container(cockpit, "Live Observability Cockpit", "HTTP SSE + curses", "dashboard_server.py, dashboard_static.html, tui.py")
Container(mcp, "Coordination MCP Server", "stdio JSON-RPC", "mcps/fusion-coordination/server.py")
Rel(user, cli, "Invokes mode or workflow")
Rel(user, cockpit, "Monitors SSE stream & posts steering")
Rel(cli, engine, "Executes selected topology")
Rel(engine, coord, "Registers agents, claims tasks, logs stigmergy")
Rel(engine, iso, "Provisions worktrees/clones & checks scope gates")
Rel(cockpit, coord, "Reads WAL state & injects operator messages")
Rel(mcp, coord, "Exposes board & mailbox tools to host agent")
4-Pillar Council Upgrade Pipeline
The diagram below traces how a task flows through the 4-Pillar Council Upgrades from intake and empirical routing to isolated execution, stigmergic coordination, and receipt-verified synthesis.
flowchart LR
Task["Task Intake"] --> Router["Ledger-MoE Router\n(Wilson 95% CI)"]
Router --> Spec["Designer / SwarmSpec\n(Fail-Closed Validation)"]
Spec --> Iso["Workspace Provisioner\n(APFS cp -c / Git Worktree)"]
Iso --> Exec["Execution Topology\n(Hive / Race / Harden / Evolve)"]
Exec <--> Board["SQLite WAL Board\n(Stigmergy + kqueue Wakeup)"]
Board <--> Cockpit["Live Web SSE & TUI\n(Operator Steering)"]
Exec --> Gate["Verification Gate\n(Test Suite + REPO_RECEIPT SHA-256)"]
Gate --> Verdict["Synthesized Verdict\n& Ledger Append"]
For sequence and state diagrams covering race, harden, evolve, and kqueue re-wake, see docs/ARCHITECTURE.md.
Tech Stack
| Layer | Technology | Version | Purpose |
|---|---|---|---|
| Core Engine | Python Standard Library (fusion_swarm) | Python 3.10+ | Swarm topologies, Hive runner, MAP-Elites evolution, Wilson MoE router, worktree/APFS isolator |
| CLI Dispatcher | Bash (fusion.sh, swarm.sh, ureview.sh) | Bash 3.2+ / 5.x | Zero-latency provider discovery, blind parallel fan-out, cross-family review harness |
| Coordination Bus | SQLite 3 (WAL mode) + JSONL Sidecar | SQLite 3.35+ | Multi-process message board (board.db), durable mailbox leases, expiring stigmergy trails |
| Event Wakeup | macOS select.kqueue + File Mtime Fallback | macOS / POSIX | Sub-millisecond wakeup notifications on .fusion/board.wakeup without polling spin-loops |
| Workspace Isolation | Git Worktrees + macOS APFS clonefile(2) | Git 2.30+ / APFS | Zero-copy CoW clones (cp -c) and isolated worktree lanes with pre/post SHA-256 scope manifests |
| Web Cockpit | http.server + Server-Sent Events (SSE) + Vanilla ES6 | HTTP/1.1 | Live /api/stream push telemetry, SVG DAG renderer, stigmergy table, interactive steering form |
| Terminal Cockpit | curses (python/fusion_swarm/tui.py) | Python stdlib | 4-pane terminal monitor (Active Lanes, Live Board Feed, Stigmergy Trails, Run Cost/Health) |
| MCP Integration | mcps/fusion-coordination/server.py | MCP stdio | Exposes board, mailbox, task claim, and heartbeat tools to Claude Code, Codex, and AndrewCode |
Layout
fusion/
├── .claude-plugin/ Claude Code plugin & marketplace manifests
├── .codex-plugin/ OpenAI Codex CLI plugin manifest
├── .kimi-plugin/ AndrewCode / Kimi plugin manifest
├── plugin.json Root plugin manifest
├── kimi.plugin.json Root AndrewCode / Kimi manifest (skills + commands + SYSTEM.md)
├── .mcp.json / mcp.json MCP server registration for fusion-coordination
├── SYSTEM.md Host-neutral system prompt contract
├── CLAUDE.md / CODEX.md / KIMI.md Host-specific setup and operating guides
├── INSTALL.md Cross-platform installation guide
├── fusion.py Unified cross-platform CLI entrypoint
├── install.sh / install.ps1 macOS, Linux, and Windows installers
├── commands/ Slash-command entrypoints (/fusion, /fusion:hive, /fusion:ultimate-review, ...)
├── skills/
│ ├── fusion/ Umbrella router skill
│ ├── fusion-orchestrate/ Core conductor skill + references/ (panel, council, debate, vote, swarm, modes)
│ ├── fusion-hive/ Nested AndrewCode swarm skill
│ ├── fusion-designer/ Architect-led SwarmSpec topology designer skill
│ ├── fusion-board/ SQLite WAL message board & stigmergy skill
│ ├── fusion-team/ Scoped multi-agent coding team skill
│ ├── fusion-swarms/ MoA, Heavy, Discuss, Flow, Reason, Ladder, SpecLock, Breaker, Ballot
│ ├── fusion-metaloop/ Chief Operator + Board Advisor iterative coding loop
│ ├── fusion-graph/ Dataflow task graphs & bitemporal knowledge graphs
│ ├── fusion-ultimate-review/ Autonomous cross-family plan audit, pride gate & implementation review
│ ├── fusion-ultraswarm/ Multi-variant worktree competition & synthesis
│ └── fusion-ultracode/ Single-command autonomous pipeline
├── python/fusion_swarm/ Stdlib-only Python swarm & verification engine
│ │ identities.py · board.py · spawn.py · designer.py · hive.py · hive_prompts.py
│ │ race.py · harden.py · evolve.py · ledger_moe.py · tui.py · mailbox.py
│ │ workspaces.py · scope.py · execution.py · supervision.py · strategies.py
│ │ team.py · metaloop.py · graph.py · kgraph.py · factory.py · lanes.py
│ └── ... moa.py · heavy.py · discuss.py · flow.py · reasoning.py · ladder.py · ballot.py
├── scripts/
│ ├── fusion.sh Discover, route, dispatch, panel, council, verify, ledger
│ ├── swarm.sh CLI wrapper for python/fusion_swarm (hive, race, harden, evolve, tui, ...)
│ ├── ureview.sh Cross-family plan/impl review + REPO_RECEIPT SHA-256 verifier
│ ├── dashboard_server.py Stdlib HTTP + SSE (/api/stream) + POST /api/board/post cockpit server
│ ├── dashboard_static.html Single-file live Web Cockpit UI
│ ├── fusion_install.py Cross-platform slim installer & verifier
│ ├── install-kimi.py Idempotent AndrewCode / Kimi plugin installer
│ └── providers/ Per-CLI adapters (claude.sh, codex.sh, gemini.sh, grok.sh, copilot.sh, opencode.sh, local.sh)
├── mcps/fusion-coordination/ Stdio MCP server exposing board & mailbox coordination tools
├── config/ Provider catalog, mode rosters, and model aliases
├── docs/ Architecture, Hive contract, Coding Teams, Coordination, Credits & Research
└── tests/ validate.sh + test_hive_docs.py + test_council_upgrades.py + 35 offline suites
Getting Started
Prerequisites
- OS: macOS (APFS
clonefile(2)+kqueueaccelerated), Linux, or Windows (Git Bash / WSL / PowerShell). - Python: Python
3.10or newer (uses only the Python standard library; zeropip installpackages required). - Git: Git
2.30+(for worktree isolation and diff scope auditing). - Provider CLIs: Any 2 or more locally authenticated coding CLIs on your
PATH:
| Family | Binary | Headless Flag | Notes |
|---|---|---|---|
| Claude | claude | claude -p --output-format text | Default judge / synthesizer when off the panel |
| Codex | codex | codex exec --skip-git-repo-check | Strongest code auditor and implementation worker |
| Gemini | gemini | gemini -p -o text | Fast 1M-context architectural scout |
| Grok | grok | grok -p | Independent xAI reasoning family |
| Copilot | copilot | copilot -p -s | GitHub Copilot CLI adapter |
| OpenCode | opencode | opencode run | Multi-provider terminal coding agent |
| AndrewCode | andrewcode | node .../main.mjs --print --prompt-file | Nested Hive worker & captain harness |
| Local | ollama | ollama run <model> | Offline open-weight execution (qwen3-coder, deepseek-r1) |
Install
# Clone the repository
git clone https://github.com/andrewr303/agent-fusion.git
cd agent-fusion
# Install into Claude Code, OpenAI Codex CLI, and AndrewCode (macOS / Linux)
./install.sh
# Or use the cross-platform Python installer with verification
python3 scripts/fusion_install.py --target all
python3 scripts/fusion_install.py --verify
Host-specific installation:
- Claude Code:
./install.shregisters the local marketplace (fusion-local) and installsfusion@fusion-local, or run/plugin marketplace add ./agent-fusionfollowed by/plugin install fusion@fusion-local. - OpenAI Codex CLI: See CODEX.md —
./install.shlinks~/.codex/plugins/fusion,~/.codex/skills/fusion*, and~/.agents/skills/fusion*. - AndrewCode / Kimi Code: See KIMI.md —
kimi.plugin.jsonat the repo root (mirrored at.kimi-plugin/plugin.json) exposes./skills/,./commands/, and./SYSTEM.md. Runpython3 scripts/install-kimi.pyto install into~/.andrewcode/plugins/fusion. - Windows: Run
.\install.ps1in PowerShell or double-clickinstall.cmd. See INSTALL.md for platform details.
Quick start
Verify your detected provider CLIs and run your first multi-model panel or dry-run swarm without spending tokens:
# 1. Discover installed and authenticated provider CLIs
bash scripts/fusion.sh discover
Expected output (varies by installed CLIs):
claude available claude
codex available codex
gemini available gemini
grok available grok
# 2. Preview how Fusion routes a prompt (zero token spend)
bash scripts/fusion.sh route "design a zero-downtime Postgres shard migration"
# 3. Preview a 3-way competitive worktree race in dry-run mode
bash scripts/swarm.sh race --dry-run --competitors claude,codex,gemini --test-cmd "pytest -q" "fix race condition in token bucket"
# 4. Run the full offline validation and 802-test suite
bash tests/validate.sh
Inside Claude Code, Codex CLI, or AndrewCode, invoke slash commands directly:
/fusion:panel Review this auth middleware for session fixation and timing side-channels
/fusion:council Should we shard the event log by tenant_id or time_bucket?
/fusion:hive Build a full-stack webhook retry service with SQLite persistence and tests
/fusion:ultimate-review Audit and harden the current branch end-to-end
Configuration
Fusion works out of the box with zero configuration files by auto-discovering installed CLIs. To customize behavior per repository, create .fusion/config.json or set environment variables:
{
"default_mode": "auto",
"providers": ["claude", "codex", "gemini", "grok"],
"judge": "claude",
"timeout_sec": 180,
"max_agents": 4,
"verify_commands": ["pytest -q"],
"learning": true,
"local_model": "qwen2.5-coder:14b"
}
Environment Variables
| Variable | Required | Default | Description |
|---|---|---|---|
FUSION_TIMEOUT | No | 180 (900 in ureview) | Per-provider subprocess execution timeout in seconds |
FUSION_JUDGE | No | claude | Default synthesizer / judge family (automatically rotated off the panel when possible) |
FUSION_BOARD | No | .fusion/board.db | Path to the SQLite WAL coordination message board |
FUSION_AGENT_ID | No | Role-derived | Unique agent identifier injected into spawned Hive/Team subprocesses |
FUSION_PARENT_ID | No | "" | Parent agent identifier in nested Hive trees (architect → captain → child) |
FUSION_SWARM_ID | No | Run timestamp | Unique identifier for the active swarm run |
FUSION_CLAUDE_MODEL | No | CLI default | Override model flag passed to claude adapter |
FUSION_CODEX_MODEL | No | CLI default | Override model flag passed to codex adapter |
FUSION_GEMINI_MODEL | No | CLI default | Override model flag passed to gemini adapter |
FUSION_GROK_MODEL | No | CLI default | Override model flag passed to grok adapter |
FUSION_LOCAL_MODEL | No | Auto-detected | Ollama model tag used by scripts/providers/local.sh |
ANDREWCODE_BIN | No | Auto-discovered | Explicit command or path to andrewcode CLI (node .../main.mjs) |
Collaboration modes
/fusion picks the mode from task shape and risk, or you can force one with /fusion:<mode>.
| Mode | Topology | What happens | Use when |
|---|---|---|---|
| solo | 1 | Host answers directly. Zero sub-agent overhead. | Obvious, low-risk, reversible tasks. |
| panel | N → 1 | $N$ models answer blind & in parallel on the exact same neutral prompt; an off-panel judge synthesizes consensus, divergence, and blind spots. | Code review, bug hunt, second opinion, design critique. |
| council | N → N → 1 | Round 1 blind fan-out → Round 2 anonymized cross-review (Response A/B/C, anti-conformity prompt requiring each reviewer to name a concrete flaw) → Judge verdict with kill criteria. | Architecture decisions, high-stakes trade-offs, security design. |
| debate | A ⇄ B → J | Proponent vs. Skeptic steelman & rebuttal rounds → Judge rules on the surviving argument. | Binary technology choices, RFC stress-testing. |
| vote | N → tally | Independent structured JSON ballots + confidence-weighted tally. | Priority ranking, option triage, go/no-go gates. |
| swarm | plan → [W₁…Wₖ] → verify | Lead decomposes into file-disjoint sub-tasks → workers execute in isolated worktrees → cross-model reviewer + test gate. | Multi-file feature builds, parallel refactors. |
Hive, Designer, and Board Modes
| Mode | Slash Command | Topology | What happens | Use when |
|---|---|---|---|---|
| hive | /fusion:hive | Architect → Captains → Children ⇄ Board | Architect emits a validated SwarmSpec; Captains and nested andrewcode children coordinate on a shared SQLite WAL board (board.db) with kqueue wakeups. | Large multi-subsystem coding missions requiring hierarchical delegation. |
| designer | /fusion:designer | Task → Architect → SwarmSpec | Architect (gpt-6-astra or claude) invents the bespoke agent topology (form, roles, channels, stages, gates) validated fail-closed before any worker spawns. | Designing custom multi-agent workflows before spending worker tokens. |
| board | /fusion:board | Agents ⇄ SQLite WAL (.fusion/board.db) | Inspects, posts, polls, or records stigmergy traces on the shared transactional Hive Board (init, post, poll, tree, stigmergy). | Inspecting live swarm state, injecting human steering, or sharing stigmergy. |
4-Pillar Council Upgrade Modes
| Mode / CLI | Invocation | Inspiration | What happens |
|---|---|---|---|
| race | swarm.sh race --competitors claude,codex,gemini --test-cmd "pytest" | everything-claude-code / claude-octopus | Spawns $N$ model families in parallel isolated worktrees/APFS clones on the same task, runs --test-cmd in every lane, and promotes the fastest passing winner (or invokes a judge to cherry-pick). |
| harden | swarm.sh harden --waves 3 --test-cmd "pytest" | clean-harbor / superpowers-v | Iterative adversarial wave loop: [Red-Team Critic ‖ Edge-Case Mutator] → Implementer Fix → Verification Command. Terminates early when zero high-severity findings remain and tests pass. |
| evolve | swarm.sh evolve --target file.py --generations 4 --islands 2 | openevolve / ShinkaEvolve | Quality-Diversity MAP-Elites grid (correctness_bin × conciseness_bin) with multi-island ring topology migration and 3-stage cascade evaluation (ast.parse → unit test → benchmark). |
| ledger-moe | swarm.sh ledger-moe --task-type code --role worker | claude-flow / awesome-claude-code-subagents | Parses .fusion/runs.jsonl, computes the 95% Wilson score lower confidence bound per (provider, role, task_type), breaks ties by median latency, and outputs empirical routing rankings. |
| stigmergy | python -m fusion_swarm.board --db "$FUSION_BOARD" stigmergy ... | claude-flow Stigmergic Environment | Agents leave expiring typed pheromone traces (bug-hotspot, lock-warning, verified-clean, interface-contract) on specific files (path, strength, ttl_seconds) auto-injected into teammate prompts. |
| tui | swarm.sh tui --db .fusion/board.db | Terminal Swarm Monitor | Zero-dependency Python curses 4-pane live terminal dashboard displaying Active Lanes, Live Board Feed, Stigmergy Pheromone Trails, and Run Cost/Health (q to quit, r to refresh). |
Advanced Swarm Topologies (python/fusion_swarm)
| Slash Command | CLI Subcommand | Pattern & Mechanics |
|---|---|---|
/fusion:moa | swarm.sh moa | Layered Mixture-of-Agents — $L$ proposer layers where each layer sees all prior layer outputs, feeding a final aggregator. |
/fusion:heavy | swarm.sh heavy | HeavySwarm — Research director decomposes question into $K$ angles → parallel scouts → synthesis + verification pass. |
/fusion:discuss | swarm.sh discuss | Facilitated GroupChat — Multi-turn roundtable with turn-taking modes (round_robin, director, speak_when_new) and convergence check. |
/fusion:ladder | swarm.sh ladder | Difficulty-Escalation Ladder — Tier 0 (solo) → Tier 1 (best-of-3) → Tier 2 (moa) → Tier 3 (heavy), escalating only on failed quality checks. |
/fusion:speclock | swarm.sh speclock | Spec-Locked Parallel Builders — Freezes shared interface contracts first, then dispatches file-disjoint parallel builders + contract verifier. |
/fusion:breaker | swarm.sh breaker | Adversarial Builder / Breaker Loop — Builder writes patch → Breaker crafts concrete failing reproducers → Builder hardens → Referee gates. |
/fusion:ballot | swarm.sh ballot | Blind Multi-Criteria Ballot — Independent rubric scoring with Borda count + Condorcet winner detection + minority report preservation. |
/fusion:gate | swarm.sh gate | Execute-Then-Verify Loop — Propose patch → run real shell verification (pytest, cargo test, tsc) → feed stderr back into repair loop. |
/fusion:metaloop | swarm.sh metaloop | Chief Operator + Board Advisor Loop — Iterative multi-turn coding loop with worktree scope gates and non-voting cross-family Board Advisor. |
/fusion:graph | swarm.sh graph / kg | Task & Knowledge Graphs — Dataflow DAG scheduler with critical-path linting (fake_edge, one_writer_per_file) + bitemporal Knowledge Graph (kg). |
/fusion:ultraswarm | swarm.sh ultraswarm | Multi-Variant Worktree Competition — Parallel full implementations in isolated worktrees followed by comparative synthesis. |
/fusion:ultimate-review | ureview.sh | Autonomous Cross-Family Review — Plan audit → adjudication → implementation → Pride Gate → cross-family implementation review with REPO_RECEIPT. |
Hive — nested AndrewCode swarm on one board
When a coding mission spans multiple subsystems, Fusion Hive (/fusion:hive) combines Architect-designed topology (SwarmSpec), nested process trees (SpawnLimits), and a single shared SQLite WAL coordination board (.fusion/board.db). Full specification: docs/HIVE.md.
Architect latitude
The Architect (gpt-6-astra on AndrewCode or claude on Claude Code, with Fable 5.1 / claude-opus reasoning) has full Architect latitude to invent the swarm topology (SwarmSpec) subject only to hard constraints enforced fail-closed by validate_spec and SpawnLimits:
- Every role id is unique (
^[a-z][a-z0-9_-]{0,39}$), total roles $\le 24$, andcountper role $\le 8$. - Total spawned agents never exceed
SpawnLimits.max_total_agents(default16), nested children per captain never exceedmax_children(default8), and recursion depth never exceedsmax_depth(default3). - Non-architect roles never talk to the human directly; all inter-agent communication flows through
.fusion/board.db. - Every
andrewcodesubprocess is invoked with real non-interactive flags (node C:/dev/andrew-code/apps/kimi-code/dist/main.mjs --print --prompt-file <file> --thinking-effort <level> --output-format stream-json)—never fabricated in-process text.
Example: 4-captain / 8-child nested topology
In a 4-captain / 8-child Hive run, the Architect designs a custom topology mixing model families at the Captain layer while spawning 4 nested AndrewCode children (or up to 8 children across captains):
- Captain 1 (
andrewcode/muse-spark-1.3) leads backend schema & migrations, spawning nestedandrewcodechildren onglm-5.3andmuse-spark-1.3. - Captain 2 (
andrewcode/glm-5.3) leads API handlers & validation, spawning nestedandrewcodechildren. - Captain 3 (
captain grok) leads adversarial edge-case and security auditing. - Captain 4 (
captain copilot) leads CI harness and integration test verification.
Every agent polls and posts to the shared board using the board CLI:
python -m fusion_swarm.board --db "$FUSION_BOARD" poll --agent "$FUSION_AGENT_ID"
When --wait <seconds> is passed to poll, board.py uses macOS select.kqueue on .fusion/board.wakeup to wake the waiting agent within milliseconds of any post, dm, or reply—and if --hook-rewake is enabled on hive.py, idle agents with unread @mentions or dm: messages are automatically re-spawned with their unread inbox context.
How a run works
- Discover (
fusion.sh discover) — Probes which provider CLIs exist onPATHand can execute non-interactively. - Route (
route.shorswarm.sh ledger-moe) — Classifies task risk and complexity, optionally consulting empirical Wilson confidence scores in.fusion/runs.jsonl. - Isolate (
workspaces.py) — Creates per-lane workspaces using zero-copy macOS APFScp -c(clonefile(2)) orgit worktree add --detach, recording a baseline SHA-256 scope manifest (scope.py). - Dispatch (
fusion.sh/python/fusion_swarm) — Spawns real OS subprocesses withstart_new_session=True, heartbeat supervision (supervision.py), and--dry-runpreview support. - Verify (
ureview.sh/gate/scope_gate) — Runs the project's test suite, checks file-scope boundaries (outside_allowed,protected_touched), and verifies reviewerREPO_RECEIPTfile hashes. - Synthesize & Record (
ledger.sh) — Synthesizes consensus, divergence, and blind spots into an actionable verdict and appends the run record to.fusion/runs.jsonl.
What makes it good (and honest)
- Real dispatch only — Every sub-agent response comes from an actual OS subprocess invocation (
claude,codex,gemini,grok,copilot,opencode,andrewcode,ollama). The host agent is strictly forbidden from role-playing or simulating another model's output. Use--dry-runto preview topology without spawning processes. - Absent ≠ agreement — If a provider CLI times out, exits non-zero, or is not installed, Fusion reports
ABSENT (<reason>)in the run banner and synthesis. Silence is never counted as a concurring vote. - Cryptographic
REPO_RECEIPTverification — In/fusion:ultimate-review, cross-family reviewers must emit aREPO_RECEIPT: path=<relpath> sha256=<prefix8+> line1=<text>proving they read the repository files on disk.ureview.sh verify-receiptrecomputes the SHA-256 digest and downgrades unverified claims toREPO_RECEIPT:UNVERIFIED. - Judge off the panel — Whenever 3+ provider families are available, the synthesizer/judge is kept off the initial responder panel so it never grades its own draft.
- Anti-conformity cross-review — In
councilandultimate-review, peer drafts are anonymized (Response A,Response B, ...) and each reviewer must identify at least one concrete flaw (name-the-flawrule) before agreeing.
Available Scripts & Entrypoints
| Entrypoint | Subcommands / Flags | Description |
|---|---|---|
python3 fusion.py | discover, route, panel, council, hive, race, harden, evolve, ledger-moe, tui | Unified cross-platform CLI dispatcher |
bash scripts/fusion.sh | discover, route, panel, council, verify, ledger, doctor | Core bash orchestrator for blind fan-out, cross-review, and ledger stats |
bash scripts/swarm.sh | hive, designer, board, team, race, harden, evolve, ledger-moe, tui, moa, heavy, discuss, flow, reason, ladder, speclock, breaker, ballot, gate, metaloop, graph, kg, ultraswarm | Entrypoint for all python/fusion_swarm topologies |
bash scripts/ureview.sh | init, plan-review, impl-review, verify-receipt, status | Autonomous cross-family review harness and REPO_RECEIPT verifier |
python3 scripts/dashboard_server.py | --root .fusion --port 8765 | Live HTTP + Server-Sent Events (/api/stream) Web Cockpit server |
python3 scripts/fusion_install.py | --target {all,claude,codex,andrewcode}, --verify, --dry-run | Cross-platform slim plugin installer and integrity checker |
python3 scripts/install-kimi.py | --home ~/.andrewcode, --dry-run | Idempotent installer for AndrewCode / Kimi Code |
API, Board & Cockpit Reference
Board & Stigmergy CLI (python -m fusion_swarm.board)
# Initialize board schema (agents, channels, messages, acks, presence, stigmergy_traces)
python -m fusion_swarm.board --db "$FUSION_BOARD" init
# Poll unread messages with kqueue instant wakeup (up to 30s timeout)
python -m fusion_swarm.board --db "$FUSION_BOARD" poll --agent "$FUSION_AGENT_ID" --wait 30
# Record an expiring stigmergic discovery trace on a file
python -m fusion_swarm.board --db "$FUSION_BOARD" stigmergy put \
--agent "$FUSION_AGENT_ID" --path "src/auth/jwt.py" \
--kind "bug-hotspot" --note "Missing exp claim validation on refresh path" \
--strength 0.95 --ttl 3600
# Query active stigmergy traces (sorted by strength DESC)
python -m fusion_swarm.board --db "$FUSION_BOARD" stigmergy list --path-prefix "src/auth"
Live Web Cockpit HTTP & SSE Endpoints (scripts/dashboard_server.py)
| Method & Path | Response Type | Description |
|---|---|---|
GET / | text/html | Serves the single-file live Web Cockpit (scripts/dashboard_static.html) |
GET /api/stream | text/event-stream | Server-Sent Events stream pushing snapshot frames whenever .fusion/ state changes |
GET /api/overview | application/json | Aggregate run counts, active lanes, provider health, and recent activity |
GET /api/runs | application/json | Normalized list of swarm runs with status, mode, duration, and lane breakdowns |
GET /api/dag?run_id=<id> | application/json | Live DAG nodes (id, label, status) and directed edges for SVG rendering |
GET /api/stigmergy | application/json | Active non-expired stigmergic pheromone traces from .fusion/board.db |
POST /api/board/post | application/json | Posts a human steering message ({"channel": "hive", "sender": "human", "body": "..."}) to board.db |
Testing
Agent Fusion ships with 802 offline unit and contract tests across 37 test modules. Tests never make live network or paid CLI calls; they execute in ~5 seconds using temporary directories and deterministic mock adapters.
# Run the full 9-stage contract, shell syntax, JSON, and unit test validator
bash tests/validate.sh
# Run the entire Python unittest discovery suite (802 tests)
PYTHONPATH=python python3 -m unittest discover -s tests
# Run specific test suites
PYTHONPATH=python python3 -m unittest tests.test_council_upgrades
PYTHONPATH=python python3 -m unittest tests.test_hive_docs
PYTHONPATH=python python3 -m unittest tests.test_conductor_docs
Deployment & Host Integration
Agent Fusion deploys locally into your coding harnesses without external servers or Docker containers:
- Standard Multi-Host Deployment: Run
./install.sh(macOS/Linux) or.\install.ps1(Windows) to install the slim runtime surface into Claude Code, OpenAI Codex CLI, and AndrewCode simultaneously. - Slim Surface Guarantee:
scripts/fusion_install.pycopies only the runtime directories (.claude-plugin,.codex-plugin,.kimi-plugin,assets,commands,config,docs,mcps/fusion-coordination,memory,python,scripts,skills,tests) and root manifests, never copying local.fusion/state or external vendor trees. - MCP Coordination Server:
.mcp.jsonandmcp.jsonregistermcps/fusion-coordination/server.pyas a stdio MCP server so host agents can callfusion_board_post,fusion_board_poll,fusion_task_claim, andfusion_heartbeatnatively.
Troubleshooting
| Symptom | Root Cause | Resolution |
|---|---|---|
fusion.sh discover shows fewer than 2 providers | Provider CLIs are not on PATH or require login | Run which claude codex gemini grok copilot opencode ollama and authenticate each CLI (claude login, codex login, etc.) |
REPO_READ:DEGRADED (sandbox_process_spawn_failed) on Windows | Codex Windows sandbox blocks nested CreateProcessAsUserW calls | Run ureview.sh from a standard shell outside the restricted sandbox or pass --dangerously-bypass-approvals-and-sandbox in trusted worktrees |
REPO_RECEIPT:UNVERIFIED during /fusion:ultimate-review | Reviewer hallucinated a file SHA-256 or read a stale branch | Re-run bash scripts/ureview.sh verify-receipt <session_dir> <review_file> or re-dispatch the reviewer with worktree access |
sqlite3.OperationalError: database is locked | Stale process holding .fusion/board.db outside WAL timeout | Inspect active processes with python -m fusion_swarm.board --db .fusion/board.db agents and remove stale .fusion/board.db-shm if all workers have exited |
Leftover worktrees in .fusion/worktrees/ after SIGKILL | Host process was hard-killed before context-manager cleanup | Run git worktree prune and remove orphaned directories under .fusion/worktrees/ |
Contributing
- Fork & Branch: Create a feature branch from
main. - Zero External Dependencies: All code under
python/fusion_swarm/andscripts/must use the Python 3.10+ standard library and POSIX bash—never add third-party PyPI or npm runtime dependencies. - Preserve Honesty Invariants: Never weaken the anti-simulation rules (
Real dispatch only,Absent ≠ agreement,REPO_RECEIPTverification, or fail-closedSwarmSpecvalidation). - Verify Before Submitting: Ensure both
bash tests/validate.shandPYTHONPATH=python python3 -m unittest discover -s testspass with zero warnings or failures.
Credit
Agent Fusion synthesizes research and open-source architectural patterns across multi-model deliberation, evolutionary search, task/knowledge graphs, and agent coordination boards. Full module-by-module provenance and citations are documented in docs/CREDITS.md and docs/RESEARCH.md:
- Multi-Model Deliberation & Sidekick Loops — Inspired by OpenRouter Fusion (How It Works and When to Use It & Surpassing Frontier Performance with Fusion), Cognition Devin Fusion (Introducing Fusion in Devin Desktop & CLI — Sidekick feedback loop & genius-boss/idiot-boss split), Andrej Karpathy's
llm-council,openfusion, council-of-high-intelligence,nexus-dev, and AndrewAgent (CODEX.md,KIMI.md,kimi.plugin.json). - Swarm Topologies (
moa,heavy,discuss,flow,reason) — Inspired by kyegomez/swarms (Mixture-of-Agents, HeavySwarm, GroupChat, AgentRearrange, Reflexion/Self-Consistency), re-implemented from scratch on local CLI subprocesses. - Quality-Diversity Evolution (
fusion evolve) — Inspired by algorithmicsuperintelligence/openevolve and SakanaAI/ShinkaEvolve (MAP-Elites quality-diversity grid, multi-island ring migration, and cascade evaluation). - Competitive Racing & Adversarial Wave-Hardening (
fusion race,fusion harden) — Inspired by affaan-m/everything-claude-code, raidium/clean-harbor, procoders/superpowers-v (MIT), and nyldn/claude-octopus (MIT). - Empirical MoE Routing & Stigmergic Coordination (
fusion ledger-moe,stigmergy_traces) — Inspired by ruvnet/claude-flow and VoltAgent/awesome-claude-code-subagents. - Transactional Boards, Worktree Isolation & Event Wakeups (
board.py,mailbox.py,workspaces.py,supervision.py) — Inspired by jahwag/agentbus (MIT), Dicklesworthstone/mcp_agent_mail, AgentWorkforce/relayflows, madison-ai-labs/SwarmWire, ChesterRa/cccc, Intrect-io/OpenSwarm (MIT), Untrivial-ai/agent-orchestrator (Apache-2.0), mraza007/agmsg (kqueuewakeup), and awslabs/cli-agent-orchestrator (hook-driven re-wake). - Task Graphs & Knowledge Graphs (
fusion:graph,kg) — Grounded in the Southeast University Graduate Knowledge Graph Course (npubird/KnowledgeGraphCourse, Prof. Peng Wang), Google DeepMind × MIT (Towards a Science of Scaling Agent Systems, Dec 2025), and Anthropic (Building Effective Agents, Dec 2024).
License
MIT licensed. See LICENSE for full text.