> ## Documentation Index
> Fetch the complete documentation index at: https://mathematicalcompany.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Hive

> 13 compiled Rust subsystems coordinate a self-evolving fleet of trading agents.

The Hive is the brain of the Horizon swarm. It takes independent trading strategies and turns them into a self-organizing system that evolves, learns, and improves on its own. No proprietary algorithms are exposed.

All 13 core subsystems are **compiled to Rust** via PyO3. When you install the SDK, you get an opaque `.so` binary. No source code ships in the Python package.

## Architecture

<CardGroup cols={2}>
  <Card title="Compiled Core" icon="microchip">
    13 subsystems compiled to native binary via PyO3/maturin. Pheromone fields, evolutionary engines, behavioral cloning, causal discovery. All opaque Rust code.
  </Card>

  <Card title="Python Orchestration" icon="diagram-project">
    `HiveController` is a thin Python wrapper that wires the 13 Rust subsystems together. Configuration, persistence (SQLite), WebSocket server, and the oversight loop stay in Python.
  </Card>

  <Card title="Progressive Autonomy" icon="stairs">
    Five trust modes from `observe` (watch only) to `skynet` (full self-modification). The system earns autonomy through demonstrated performance. Each graduation requires statistical evidence.
  </Card>

  <Card title="No IPC" icon="bolt">
    Direct PyO3 function calls between Python and Rust. No sockets, no serialization overhead, no process boundaries. A Python call to `pheromone.deposit()` executes compiled Rust in the same process.
  </Card>
</CardGroup>

## Quick Start

```python theme={null}
from horizon.hive import HiveController, HiveConfig, AutonomyMode

config = HiveConfig(
    total_capital=100_000,
    max_agents=50,
    initial_mode=AutonomyMode.Observe,  # Start conservative
    host="0.0.0.0",
    port=8780,
    auth_token="your-secret-token",
)

hive = HiveController(config)

# Spawn agents from 9 archetype templates
agent = hive.spawn_agent("momentum", markets=["BTC-YES"], capital=5000.0)

# Full status across all subsystems
status = hive.status()

# Start the oversight loop + WebSocket server (blocking)
hive.run()
```

Remote connections:

```python theme={null}
from horizon.hive import HiveClient

client = HiveClient("ws://hive-server:8780", token="your-secret-token")
client.connect()
print(client.status())
client.spawn(template="arbitrage", markets=["BTC-YES", "ETH-YES"])
```

## 13 Subsystems

Every subsystem listed below runs as compiled Rust. The Python layer is thin wrappers only.

### Coordination

| Subsystem            | Purpose                                                                                                                                                                                                                                              |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **SwarmCoordinator** | Fleet management. Tick loop: fitness scoring, selection pressure (cull underperformers), promotion pipeline (paper to shadow to live), capital rebalancing via fitness-weighted allocation.                                                          |
| **PheromoneField**   | 9-channel stigmergic communication. Agents deposit pheromone (bullish, bearish, volatility, crowding, opportunity, toxicity, liquidity, regime\_trend, regime\_mr). Evaporation + diffusion create emergent market signals without direct messaging. |
| **ConsensusEngine**  | 3-layer collective intelligence. IC-weighted signal combination, internal prediction markets (agents bet on outcomes), and Dempster-Shafer belief aggregation for conflicting views.                                                                 |

### Evolution

| Subsystem            | Purpose                                                                                                                                                                                                           |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **AgentFactory**     | 9 archetype templates (momentum, mean\_reversion, market\_maker, arbitrage, volatility, event\_driven, macro, copy, liquidation) plus 5 additional spawn sources: evolution, clone, user, imprint, opportunistic. |
| **MAPElitesArchive** | 300-cell quality-diversity grid (5x5x3x4) over behavioral descriptors: holding period, directional bias, volatility preference, asset focus. Keeps the swarm diverse by construction.                             |
| **EvolutionEngine**  | NSGA-II multi-objective optimization with island model. Wraps the existing `src/evolution.rs` Rust module. Populations evolve across 5 islands with periodic migration.                                           |

### Intelligence

| Subsystem              | Purpose                                                                                                                                                                                                                                                                      |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **CriticalityMonitor** | 15-indicator systemic risk assessment. Correlation convergence, contagion score, Hurst exponent, two-scale volatility, market entropy, transfer entropy, VPIN, liquidity, spread widening, Amihud ratio, BOCPD, CUSUM. Triggers avalanche reserve deployment on criticality. |
| **CausalEngine**       | Granger causality + transfer entropy + lead-lag detection across all tracked markets. Builds a causal graph that detects when relationships break. Early warning for regime shifts.                                                                                          |
| **SelfImpactModel**    | Almgren-Chriss calibrated impact estimation. OLS regression on observed slippage. Gates orders that would move the market more than the expected alpha. Internal crossing for opposite-side fills.                                                                           |
| **ImprintSystem**      | Behavioral cloning via 3-layer MLP (16 to 64 to 32 to 9 actions). Learns from operator actions with DAgger-style corrections. MaxEnt IRL reward model. Learns your trading style and can suggest or replicate it.                                                            |

### Safety

| Subsystem               | Purpose                                                                                                                                                                                                            |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **AutonomyController**  | 5-mode progressive autonomy state machine. Each transition requires statistical evidence (acceptance rate, Sharpe comparison, incident-free period). Observe, Suggest, Supervised, Autonomous, Skynet.             |
| **KillChain**           | 6-phase automated incident response: detect, contain, preserve, diagnose, remediate, learn. Python callbacks for each phase. Genome blacklisting prevents failed strategies from re-evolving.                      |
| **MetamorphicExecutor** | Anti-fingerprint execution. Slices orders into randomized child orders with jittered size, exponential timing, beta-distributed aggression, round-robin venues, and Gaussian price offsets. Optional decoy orders. |
| **ReputationSystem**    | Bayesian trust scoring with Beta(alpha, beta) posteriors per agent. Behavioral fingerprinting detects style drift. Reputation weights capital allocation and pheromone deposits.                                   |

## Autonomy Modes

The Hive doesn't start autonomous. It earns trust through demonstrated performance.

| Mode           | Behavior                                                                         | Graduation Criteria                                                              |
| -------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| **Observe**    | Watch only. No actions, no suggestions.                                          | 100+ imprint observations                                                        |
| **Suggest**    | Suggest actions, never execute. Human reviews.                                   | 70%+ acceptance rate over 14 days                                                |
| **Supervised** | Act with human approval for non-routine decisions. Auto-approve routine actions. | 80%+ approval rate over 28 days, Sharpe > threshold                              |
| **Autonomous** | Independent within guardrails. All actions allowed.                              | 6+ months profitable, Hive Sharpe > user Sharpe, 0 critical incidents in 90 days |
| **Skynet**     | Full autonomy with self-modifying guardrails.                                    | Manual promotion only                                                            |

```python theme={null}
# Check current mode
mode = hive.autonomy.status()["mode"]

# Force mode change (bypasses graduation)
hive.autonomy.set_mode(AutonomyMode.Supervised)

# Pending approvals in supervised mode
pending = hive.autonomy.pending()
hive.autonomy.approve(pending[0]["id"])
```

## Pheromone Field

Agents communicate indirectly by depositing pheromone on markets. No direct messaging. Emergent coordination through environmental modification. Same mechanism ant colonies use.

```python theme={null}
from horizon._horizon import PheromoneChannel

# Agent deposits bullish signal on BTC, weighted by its fitness
hive.pheromone.deposit("BTC-YES", PheromoneChannel.Bullish, amount=0.8, agent_fitness=1.5)

# Another agent senses the field before trading
readings = hive.pheromone.sense("BTC-YES")
print(f"Bullish: {readings.bullish}, Crowding: {readings.crowding}")

# Pheromone evaporates over time (old signals fade)
# Diffuses to related markets (BTC signal bleeds to ETH)
# Crowding channel auto-updates based on agent count
hive.pheromone.tick(dt=1.0)

# Full field snapshot
snapshot = hive.pheromone.snapshot()  # market_id -> channel -> value
```

Nine channels:

| Channel                    | What It Signals                                        |
| -------------------------- | ------------------------------------------------------ |
| `Bullish` / `Bearish`      | Directional conviction from agents actively trading    |
| `Volatility`               | Agents detecting unusual price movement                |
| `Crowding`                 | How many agents are on the same market (auto-computed) |
| `Opportunity`              | Untapped edge detected but not yet exploited           |
| `Toxicity`                 | Adverse selection or market manipulation detected      |
| `Liquidity`                | Available depth for execution                          |
| `RegimeTrend` / `RegimeMR` | Current market regime classification                   |

## Kill Chain

Automated incident response. Six phases in sequence with Python callbacks at each step.

```python theme={null}
from horizon._horizon import Severity

# Register response handlers
hive.kill_chain.on_contain(lambda incident: pause_affected_agents(incident))
hive.kill_chain.on_preserve(lambda incident: snapshot_full_state(incident))
hive.kill_chain.on_diagnose(lambda incident: identify_root_cause(incident))
hive.kill_chain.on_remediate(lambda incident: kill_and_blacklist(incident))
hive.kill_chain.on_learn(lambda incident: record_for_evolution(incident))

# Trigger manually or automatically via criticality monitor
hive.kill_chain.trigger(
    Severity.Sev1Critical,
    "portfolio_drawdown_15pct",
    ["agent-001", "agent-002"],
    pnl_impact=-15000.0,
)
```

## Configuration

`HiveConfig` is a Python dataclass with 42 fields. Key settings:

| Setting                      | Default      | Purpose                                        |
| ---------------------------- | ------------ | ---------------------------------------------- |
| `total_capital`              | 100,000      | Total AUM across all agents                    |
| `max_agents`                 | 50           | Maximum concurrent agents                      |
| `initial_mode`               | `Observe`    | Starting autonomy mode                         |
| `max_drawdown_pct`           | 0.20         | Portfolio-wide drawdown limit                  |
| `max_capital_per_agent_pct`  | 0.15         | No single agent gets more than 15%             |
| `pheromone_tick_interval`    | 1.0s         | Pheromone evaporation/diffusion rate           |
| `criticality_check_interval` | 60s          | How often to run the 15-indicator check        |
| `avalanche_reserve_pct`      | 0.15         | Capital held in reserve for crises             |
| `dream_enabled`              | True         | Offline accelerated evolution between sessions |
| `imprint_enabled`            | True         | Learn from operator behavior                   |
| `metamorphic_enabled`        | True         | Anti-fingerprint execution                     |
| `host` / `port`              | 0.0.0.0:8780 | WebSocket server for remote connections        |
| `auth_token`                 | None         | Required for remote client auth                |

## CLI

25 commands under `horizon hive`:

```bash theme={null}
# Status
horizon hive status
horizon hive agents
horizon hive agent <agent-id>

# Lifecycle
horizon hive spawn --template momentum --markets BTC-YES --capital 5000
horizon hive kill <agent-id> --reason "negative sharpe"
horizon hive pause <agent-id>
horizon hive resume <agent-id>
horizon hive scale <agent-id> --capital 10000

# Autonomy
horizon hive mode                    # Current mode
horizon hive pending                 # Decisions awaiting approval
horizon hive approve <decision-id>
horizon hive reject <decision-id>

# Intelligence
horizon hive evolve --generations 100
horizon hive dream --generations 10000
horizon hive pheromone BTC-YES
horizon hive reputation
horizon hive consensus BTC-YES
horizon hive criticality
horizon hive incidents

# Emergency
horizon hive kill-switch             # Pause everything immediately

# Remote
horizon hive connect ws://server:8780 --token secret
horizon hive server --port 8780      # Start WebSocket server
```

## MCP Server

22 tools for LLM-driven Hive management via `horizon.mcp_hive`:

```bash theme={null}
# Start the MCP server
python -m horizon.mcp_hive

# Or with auth
HIVE_MCP_TOKEN=secret python -m horizon.mcp_hive
```

Tools include: `hive_status`, `hive_spawn`, `hive_kill`, `hive_evolve`, `hive_dream`, `hive_pheromone`, `hive_consensus`, `hive_criticality`, `hive_incidents`, `hive_kill_switch`, and more. Full tool definitions are in `python/horizon/mcp_hive.py`.

## What the Hive Cannot Do

<CardGroup cols={2}>
  <Card title="Cannot Override Rust Risk" icon="lock">
    The Rust engine's 8-point risk pipeline sits below the Hive. Every order goes through compiled checks regardless of what the Hive decides.
  </Card>

  <Card title="Cannot Skip Kill Chain" icon="ban">
    Once a kill chain triggers, all 6 phases execute. The Hive can't suppress an incident or skip remediation. Genome blacklisting is permanent.
  </Card>

  <Card title="Cannot Reverse Graduation" icon="arrow-up">
    Autonomy modes only go forward. The system can't demote itself from Autonomous back to Supervised without human intervention.
  </Card>

  <Card title="Cannot Exceed Capital Limits" icon="vault">
    Total allocation across all agents can't exceed `total_capital`. The coordinator enforces this in compiled Rust. No Python code can bypass it.
  </Card>
</CardGroup>

## IP Protection

The proprietary algorithms (pheromone fields, evolutionary engines, behavioral cloning, causal discovery, impact modeling, metamorphic execution) are all compiled to native binary. When you publish the SDK:

* Users get `_horizon.cpython-312-darwin.so` (or equivalent for their platform)
* No `.py` files contain algorithm implementations
* The Python `hive/` directory contains only configuration, persistence, and thin wrappers
* Decompiling the `.so` produces assembly, not readable algorithms
