Skip to content

andrewr303/fusion

v3.2.0+swarmMIT

Composable coding swarms: 16 forms, six workflows, Sidekick and genius/idiot boss, durable communication, fenced host execution, exact artifact reviews and project knowledge. Explicit selected models; no implicit Claude or CLI fallback. Includes nested AndrewCode Hive and existing graph/council contracts.

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

  1. Overview & Key Features
  2. Architecture & Tech Stack
  3. Getting Started
  4. Configuration & Environment Variables
  5. Collaboration Modes, Hive & Scripts
  6. API, Board & Cockpit Reference
  7. Testing
  8. Deployment & Host Integration
  9. Troubleshooting
  10. Contributing
  11. Credit & Research Provenance
  12. 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), adversarial debate, blind vote, and multi-round ultimate-review across distinct model families (claude, codex, gemini, grok, copilot, opencode, local).
  • Nested Hive Swarms on a Single SQLite WAL Board — Plans a validated SwarmSpec with an Architect (gpt-6-astra or claude), spawns heterogeneous Captains and up to max_children nested workers (andrewcode), and coordinates them over .fusion/board.db with kqueue instant 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 Gate waves 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.jsonl using 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_RECEIPT Honesty — Provisions instant copy-on-write workspaces on macOS via cp -c (clonefile(2)) with automatic git worktree fallback, and verifies reviewer file-inspection claims against SHA-256 digests (REPO_RECEIPT:VERIFIED vs REPO_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

LayerTechnologyVersionPurpose
Core EnginePython Standard Library (fusion_swarm)Python 3.10+Swarm topologies, Hive runner, MAP-Elites evolution, Wilson MoE router, worktree/APFS isolator
CLI DispatcherBash (fusion.sh, swarm.sh, ureview.sh)Bash 3.2+ / 5.xZero-latency provider discovery, blind parallel fan-out, cross-family review harness
Coordination BusSQLite 3 (WAL mode) + JSONL SidecarSQLite 3.35+Multi-process message board (board.db), durable mailbox leases, expiring stigmergy trails
Event WakeupmacOS select.kqueue + File Mtime FallbackmacOS / POSIXSub-millisecond wakeup notifications on .fusion/board.wakeup without polling spin-loops
Workspace IsolationGit Worktrees + macOS APFS clonefile(2)Git 2.30+ / APFSZero-copy CoW clones (cp -c) and isolated worktree lanes with pre/post SHA-256 scope manifests
Web Cockpithttp.server + Server-Sent Events (SSE) + Vanilla ES6HTTP/1.1Live /api/stream push telemetry, SVG DAG renderer, stigmergy table, interactive steering form
Terminal Cockpitcurses (python/fusion_swarm/tui.py)Python stdlib4-pane terminal monitor (Active Lanes, Live Board Feed, Stigmergy Trails, Run Cost/Health)
MCP Integrationmcps/fusion-coordination/server.pyMCP stdioExposes 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) + kqueue accelerated), Linux, or Windows (Git Bash / WSL / PowerShell).
  • Python: Python 3.10 or newer (uses only the Python standard library; zero pip install packages 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:
FamilyBinaryHeadless FlagNotes
Claudeclaudeclaude -p --output-format textDefault judge / synthesizer when off the panel
Codexcodexcodex exec --skip-git-repo-checkStrongest code auditor and implementation worker
Geminigeminigemini -p -o textFast 1M-context architectural scout
Grokgrokgrok -pIndependent xAI reasoning family
Copilotcopilotcopilot -p -sGitHub Copilot CLI adapter
OpenCodeopencodeopencode runMulti-provider terminal coding agent
AndrewCodeandrewcodenode .../main.mjs --print --prompt-fileNested Hive worker & captain harness
Localollamaollama 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.sh registers the local marketplace (fusion-local) and installs fusion@fusion-local, or run /plugin marketplace add ./agent-fusion followed by /plugin install fusion@fusion-local.
  • OpenAI Codex CLI: See CODEX.md — ./install.sh links ~/.codex/plugins/fusion, ~/.codex/skills/fusion*, and ~/.agents/skills/fusion*.
  • AndrewCode / Kimi Code: See KIMI.md — kimi.plugin.json at the repo root (mirrored at .kimi-plugin/plugin.json) exposes ./skills/, ./commands/, and ./SYSTEM.md. Run python3 scripts/install-kimi.py to install into ~/.andrewcode/plugins/fusion.
  • Windows: Run .\install.ps1 in PowerShell or double-click install.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

VariableRequiredDefaultDescription
FUSION_TIMEOUTNo180 (900 in ureview)Per-provider subprocess execution timeout in seconds
FUSION_JUDGENoclaudeDefault synthesizer / judge family (automatically rotated off the panel when possible)
FUSION_BOARDNo.fusion/board.dbPath to the SQLite WAL coordination message board
FUSION_AGENT_IDNoRole-derivedUnique agent identifier injected into spawned Hive/Team subprocesses
FUSION_PARENT_IDNo""Parent agent identifier in nested Hive trees (architect → captain → child)
FUSION_SWARM_IDNoRun timestampUnique identifier for the active swarm run
FUSION_CLAUDE_MODELNoCLI defaultOverride model flag passed to claude adapter
FUSION_CODEX_MODELNoCLI defaultOverride model flag passed to codex adapter
FUSION_GEMINI_MODELNoCLI defaultOverride model flag passed to gemini adapter
FUSION_GROK_MODELNoCLI defaultOverride model flag passed to grok adapter
FUSION_LOCAL_MODELNoAuto-detectedOllama model tag used by scripts/providers/local.sh
ANDREWCODE_BINNoAuto-discoveredExplicit 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>.

ModeTopologyWhat happensUse when
solo1Host answers directly. Zero sub-agent overhead.Obvious, low-risk, reversible tasks.
panelN → 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.
councilN → N → 1Round 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.
debateA ⇄ B → JProponent vs. Skeptic steelman & rebuttal rounds → Judge rules on the surviving argument.Binary technology choices, RFC stress-testing.
voteN → tallyIndependent structured JSON ballots + confidence-weighted tally.Priority ranking, option triage, go/no-go gates.
swarmplan → [W₁…Wₖ] → verifyLead 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

ModeSlash CommandTopologyWhat happensUse when
hive/fusion:hiveArchitect → Captains → Children ⇄ BoardArchitect 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:designerTask → Architect → SwarmSpecArchitect (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:boardAgents ⇄ 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 / CLIInvocationInspirationWhat happens
raceswarm.sh race --competitors claude,codex,gemini --test-cmd "pytest"everything-claude-code / claude-octopusSpawns $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).
hardenswarm.sh harden --waves 3 --test-cmd "pytest"clean-harbor / superpowers-vIterative adversarial wave loop: [Red-Team Critic ‖ Edge-Case Mutator] → Implementer Fix → Verification Command. Terminates early when zero high-severity findings remain and tests pass.
evolveswarm.sh evolve --target file.py --generations 4 --islands 2openevolve / ShinkaEvolveQuality-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-moeswarm.sh ledger-moe --task-type code --role workerclaude-flow / awesome-claude-code-subagentsParses .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.
stigmergypython -m fusion_swarm.board --db "$FUSION_BOARD" stigmergy ...claude-flow Stigmergic EnvironmentAgents 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.
tuiswarm.sh tui --db .fusion/board.dbTerminal Swarm MonitorZero-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 CommandCLI SubcommandPattern & Mechanics
/fusion:moaswarm.sh moaLayered Mixture-of-Agents — $L$ proposer layers where each layer sees all prior layer outputs, feeding a final aggregator.
/fusion:heavyswarm.sh heavyHeavySwarm — Research director decomposes question into $K$ angles → parallel scouts → synthesis + verification pass.
/fusion:discussswarm.sh discussFacilitated GroupChat — Multi-turn roundtable with turn-taking modes (round_robin, director, speak_when_new) and convergence check.
/fusion:ladderswarm.sh ladderDifficulty-Escalation Ladder — Tier 0 (solo) → Tier 1 (best-of-3) → Tier 2 (moa) → Tier 3 (heavy), escalating only on failed quality checks.
/fusion:speclockswarm.sh speclockSpec-Locked Parallel Builders — Freezes shared interface contracts first, then dispatches file-disjoint parallel builders + contract verifier.
/fusion:breakerswarm.sh breakerAdversarial Builder / Breaker Loop — Builder writes patch → Breaker crafts concrete failing reproducers → Builder hardens → Referee gates.
/fusion:ballotswarm.sh ballotBlind Multi-Criteria Ballot — Independent rubric scoring with Borda count + Condorcet winner detection + minority report preservation.
/fusion:gateswarm.sh gateExecute-Then-Verify Loop — Propose patch → run real shell verification (pytest, cargo test, tsc) → feed stderr back into repair loop.
/fusion:metaloopswarm.sh metaloopChief Operator + Board Advisor Loop — Iterative multi-turn coding loop with worktree scope gates and non-voting cross-family Board Advisor.
/fusion:graphswarm.sh graph / kgTask & Knowledge Graphs — Dataflow DAG scheduler with critical-path linting (fake_edge, one_writer_per_file) + bitemporal Knowledge Graph (kg).
/fusion:ultraswarmswarm.sh ultraswarmMulti-Variant Worktree Competition — Parallel full implementations in isolated worktrees followed by comparative synthesis.
/fusion:ultimate-reviewureview.shAutonomous 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$, and count per role $\le 8$.
  • Total spawned agents never exceed SpawnLimits.max_total_agents (default 16), nested children per captain never exceed max_children (default 8), and recursion depth never exceeds max_depth (default 3).
  • Non-architect roles never talk to the human directly; all inter-agent communication flows through .fusion/board.db.
  • Every andrewcode subprocess 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 nested andrewcode children on glm-5.3 and muse-spark-1.3.
  • Captain 2 (andrewcode / glm-5.3) leads API handlers & validation, spawning nested andrewcode children.
  • 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

  1. Discover (fusion.sh discover) — Probes which provider CLIs exist on PATH and can execute non-interactively.
  2. Route (route.sh or swarm.sh ledger-moe) — Classifies task risk and complexity, optionally consulting empirical Wilson confidence scores in .fusion/runs.jsonl.
  3. Isolate (workspaces.py) — Creates per-lane workspaces using zero-copy macOS APFS cp -c (clonefile(2)) or git worktree add --detach, recording a baseline SHA-256 scope manifest (scope.py).
  4. Dispatch (fusion.sh / python/fusion_swarm) — Spawns real OS subprocesses with start_new_session=True, heartbeat supervision (supervision.py), and --dry-run preview support.
  5. Verify (ureview.sh / gate / scope_gate) — Runs the project's test suite, checks file-scope boundaries (outside_allowed, protected_touched), and verifies reviewer REPO_RECEIPT file hashes.
  6. 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-run to 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_RECEIPT verification — In /fusion:ultimate-review, cross-family reviewers must emit a REPO_RECEIPT: path=<relpath> sha256=<prefix8+> line1=<text> proving they read the repository files on disk. ureview.sh verify-receipt recomputes the SHA-256 digest and downgrades unverified claims to REPO_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 council and ultimate-review, peer drafts are anonymized (Response A, Response B, ...) and each reviewer must identify at least one concrete flaw (name-the-flaw rule) before agreeing.

Available Scripts & Entrypoints

EntrypointSubcommands / FlagsDescription
python3 fusion.pydiscover, route, panel, council, hive, race, harden, evolve, ledger-moe, tuiUnified cross-platform CLI dispatcher
bash scripts/fusion.shdiscover, route, panel, council, verify, ledger, doctorCore bash orchestrator for blind fan-out, cross-review, and ledger stats
bash scripts/swarm.shhive, designer, board, team, race, harden, evolve, ledger-moe, tui, moa, heavy, discuss, flow, reason, ladder, speclock, breaker, ballot, gate, metaloop, graph, kg, ultraswarmEntrypoint for all python/fusion_swarm topologies
bash scripts/ureview.shinit, plan-review, impl-review, verify-receipt, statusAutonomous cross-family review harness and REPO_RECEIPT verifier
python3 scripts/dashboard_server.py--root .fusion --port 8765Live HTTP + Server-Sent Events (/api/stream) Web Cockpit server
python3 scripts/fusion_install.py--target {all,claude,codex,andrewcode}, --verify, --dry-runCross-platform slim plugin installer and integrity checker
python3 scripts/install-kimi.py--home ~/.andrewcode, --dry-runIdempotent 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 & PathResponse TypeDescription
GET /text/htmlServes the single-file live Web Cockpit (scripts/dashboard_static.html)
GET /api/streamtext/event-streamServer-Sent Events stream pushing snapshot frames whenever .fusion/ state changes
GET /api/overviewapplication/jsonAggregate run counts, active lanes, provider health, and recent activity
GET /api/runsapplication/jsonNormalized list of swarm runs with status, mode, duration, and lane breakdowns
GET /api/dag?run_id=<id>application/jsonLive DAG nodes (id, label, status) and directed edges for SVG rendering
GET /api/stigmergyapplication/jsonActive non-expired stigmergic pheromone traces from .fusion/board.db
POST /api/board/postapplication/jsonPosts 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:

  1. 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.
  2. Slim Surface Guarantee: scripts/fusion_install.py copies 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.
  3. MCP Coordination Server: .mcp.json and mcp.json register mcps/fusion-coordination/server.py as a stdio MCP server so host agents can call fusion_board_post, fusion_board_poll, fusion_task_claim, and fusion_heartbeat natively.

Troubleshooting

SymptomRoot CauseResolution
fusion.sh discover shows fewer than 2 providersProvider CLIs are not on PATH or require loginRun 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 WindowsCodex Windows sandbox blocks nested CreateProcessAsUserW callsRun 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-reviewReviewer hallucinated a file SHA-256 or read a stale branchRe-run bash scripts/ureview.sh verify-receipt <session_dir> <review_file> or re-dispatch the reviewer with worktree access
sqlite3.OperationalError: database is lockedStale process holding .fusion/board.db outside WAL timeoutInspect 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 SIGKILLHost process was hard-killed before context-manager cleanupRun git worktree prune and remove orphaned directories under .fusion/worktrees/

Contributing

  1. Fork & Branch: Create a feature branch from main.
  2. Zero External Dependencies: All code under python/fusion_swarm/ and scripts/ must use the Python 3.10+ standard library and POSIX bash—never add third-party PyPI or npm runtime dependencies.
  3. Preserve Honesty Invariants: Never weaken the anti-simulation rules (Real dispatch only, Absent ≠ agreement, REPO_RECEIPT verification, or fail-closed SwarmSpec validation).
  4. Verify Before Submitting: Ensure both bash tests/validate.sh and PYTHONPATH=python python3 -m unittest discover -s tests pass 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:


License

MIT licensed. See LICENSE for full text.