Metadata-Version: 2.4
Name: zenon-nebula
Version: 0.2.21
Summary: Autonomous intelligence platform for the Zenon Network
Author: ZenonOrg
License: MIT
Project-URL: Homepage, https://github.com/ZenonOrg/nebula
Project-URL: Documentation, https://github.com/ZenonOrg/nebula/blob/main/README.md
Project-URL: Repository, https://github.com/ZenonOrg/nebula
Project-URL: Issues, https://github.com/ZenonOrg/nebula/issues
Keywords: zenon,blockchain,intelligence,monitoring
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.31.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: networkx>=3.0
Requires-Dist: websocket-client>=1.6.0
Provides-Extra: full
Requires-Dist: Pillow>=10.0.0; extra == "full"
Requires-Dist: PyPDF2>=3.0.0; extra == "full"
Requires-Dist: pdf2image>=1.16.0; extra == "full"
Requires-Dist: pytesseract>=0.3.10; extra == "full"
Requires-Dist: python-docx>=0.8.11; extra == "full"
Requires-Dist: openpyxl>=3.1.0; extra == "full"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-timeout>=2.0.0; extra == "dev"
Requires-Dist: pytest-benchmark>=4.0; extra == "dev"
Requires-Dist: hypothesis>=6.0; extra == "dev"
Requires-Dist: pip-tools>=7.0; extra == "dev"
Requires-Dist: mkdocs-material>=9.0; extra == "dev"
Requires-Dist: mkdocstrings[python]>=0.24; extra == "dev"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5; extra == "docs"
Requires-Dist: mkdocs-material>=9.0; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.24; extra == "docs"
Dynamic: license-file

# Zenon Nebula

```
        ███╗   ██╗███████╗██████╗ ██╗   ██╗██╗      █████╗
        ████╗  ██║██╔════╝██╔══██╗██║   ██║██║     ██╔══██╗
        ██╔██╗ ██║█████╗  ██████╔╝██║   ██║██║     ███████║
        ██║╚██╗██║██╔══╝  ██╔══██╗██║   ██║██║     ██╔══██║
        ██║ ╚████║███████╗██████╔╝╚██████╔╝███████╗██║  ██║
        ╚═╝  ╚═══╝╚══════╝╚═════╝  ╚═════╝ ╚══════╝╚═╝  ╚═╝
             autonomous intelligence for the Network of Momentum
```

<!--
  Badge strategy while the repo is private:
  - Static (shields.io badge endpoint) badges work everywhere.
  - Dynamic badges that query github.com (Tests, CodeQL, Release,
    Last commit) and pypi.org (PyPI version, Python versions) 404
    on private repos. They're commented out here and will be
    re-enabled when the repo goes public.
  - SLSA 3 badge becomes accurate only after the release workflow
    runs the `provenance` job on a tagged release.
-->
<p align="center">
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="License: MIT"></a>
  <img src="https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue" alt="Python 3.10–3.13">
  <img src="https://img.shields.io/badge/status-alpha-orange" alt="Status: alpha">
  <img src="https://img.shields.io/badge/version-v0.2.21-informational" alt="Version v0.2.21">
</p>

<p align="center">
  <a href="docs/SECURITY-THREAT-MODEL.md"><img src="https://img.shields.io/badge/threat%20model-documented-green" alt="Threat model"></a>
  <a href="docs/SIGNING.md"><img src="https://img.shields.io/badge/sigstore-signed-5865F2" alt="sigstore signed"></a>
  <a href="https://slsa.dev"><img src="https://img.shields.io/badge/SLSA-level%203-brightgreen" alt="SLSA 3"></a>
  <a href="CHANGELOG.md"><img src="https://img.shields.io/badge/changelog-Keep%20a%20Changelog-orange" alt="Keep a Changelog"></a>
  <a href="https://conventionalcommits.org"><img src="https://img.shields.io/badge/commits-Conventional-fe5196" alt="Conventional Commits"></a>
  <a href="MAINTAINING.md"><img src="https://img.shields.io/badge/maintainers-AI%2BHuman-9cf" alt="Maintainers: AI+Human"></a>
</p>

<!--
When the repo goes public, uncomment the dynamic badges below and
delete the static Version/Status ones above.

<p align="center">
  <a href="https://github.com/ZenonOrg/nebula/actions/workflows/test.yml"><img src="https://github.com/ZenonOrg/nebula/actions/workflows/test.yml/badge.svg" alt="Tests"></a>
  <a href="https://github.com/ZenonOrg/nebula/actions/workflows/codeql.yml"><img src="https://github.com/ZenonOrg/nebula/actions/workflows/codeql.yml/badge.svg" alt="CodeQL"></a>
  <a href="https://github.com/ZenonOrg/nebula/actions/workflows/scorecard.yml"><img src="https://github.com/ZenonOrg/nebula/actions/workflows/scorecard.yml/badge.svg" alt="OSSF Scorecard"></a>
  <a href="https://pypi.org/project/zenon-nebula/"><img src="https://img.shields.io/pypi/v/zenon-nebula.svg" alt="PyPI"></a>
  <a href="https://github.com/ZenonOrg/nebula/releases"><img src="https://img.shields.io/github/v/release/ZenonOrg/nebula.svg" alt="Release"></a>
  <a href="https://github.com/ZenonOrg/nebula/commits/main"><img src="https://img.shields.io/github/last-commit/ZenonOrg/nebula.svg" alt="Last commit"></a>
</p>
-->


<!-- nebula:stats:start -->
<!-- Regenerated by scripts/regen_docs.py. Do not edit by hand. -->

| Metric | Count |
|--------|-------|
| Python files | 343 |
| Lines of code | 98,700 |
| Core modules | 97 |
| Domains | 17 |
| Engines | 86 |
| Test files | 71 |
| Scripts | 15 |
| Schema tables | 87 |
| MCP tools | 8 |

<!-- nebula:stats:end -->

Nebula is an autonomous intelligence platform for the Network of Momentum. It monitors the entire Zenon ecosystem in real time - specs, code, governance, bridge health, liquidity, narratives, and security - cross-references every signal through Bayesian hypothesis evolution and collision detection, and produces mission-aligned battle plans. Nebula is critical Zenon infrastructure: the nervous system that keeps the community informed, the network hardened, and the roadmap honest.

## Mission

The goal that every TminusZ spec keeps pointing at — PTLC, Bitcoin SPV,
Portal, Atomic Swap, Commitments, Sentinel Validator, Governance,
HyperQube — is the same one. Nebula takes that trajectory seriously and
aligns every engine it runs against it:

> **Become the most trustless Bitcoin-adjacent programmable settlement
> layer in crypto.** Enable non-custodial BTC ↔ ZNN movement through
> cryptographic proofs — point-locks, SPV header relays, atomic swaps,
> relayer-bonded bridges — instead of custodians or wrapped tokens.
> Preserve Zenon's sovereign consensus and dual-coin economics while
> extending programmability via embedded contracts and HyperQube
> extension chains. Never introduce admin keys, pause buttons, or
> post-activation upgrade paths. Every new contract is a composable
> building block for a more decentralized, more auditable,
> more Bitcoin-adjacent programmability layer — not a shortcut
> around its own security guarantees.

The five things Nebula grades every engine's output against:

1. **Trustlessness** — does this finding move the system closer to
   zero-custody BTC interop?
2. **Sovereignty** — does it preserve Zenon's own consensus and
   on-chain governance? (no sidechain shortcuts, no L2 custodial
   escape hatches)
3. **Composability** — does it add a building block other contracts
   can compose with, or is it a dead-end feature?
4. **Auditability** — is the change auditable without trusting an
   off-chain oracle, a relayer, or a pause key?
5. **Adoption** — is it something external operators (pillars,
   sentinels, wallets, explorers, SDK consumers) can actually use?

When the spec corpus is available, `core/mission/spec_derivation.py`
re-derives these pillars from what TminusZ is actually writing (so the
mission tracks the specs as they evolve, not whatever we decided to
hardcode). Without the spec repo, the five pillars above are the
fallback. See [ADR-0010](docs/decisions/0010-spec-derived-mission.md)
for the full design.

## Participants

- **Developers** - spec drift detection, cross-repo ABI consistency, upstream monitoring across the repos you have cloned locally, auto-generated PR descriptions and test vectors.
- **Pillar operators** - Accelerator-Z treasury runway, per-pillar uptime tracking, delegation-drop alerts, voting accountability scorecards.
- **Delegators and stakers** - yield comparison across pillars and sentinels, participation funnel tracking, whale accumulation signals, thesis tracker for supply contraction.
- **Security researchers** - adversarial contract reviews, CVE monitoring for dependency trees, bridge exploit patterns from 10+ real hacks, attack-cost modelling against consensus, governance, and the bridge.
- **Community** - ecosystem health trends, contributor radar, narrative resonance in Bitcoin-adjacent discussion, competitive positioning against other Bitcoin-adjacent L1s and L2s (Stacks, RSK, Botanix, Citrea, BOB — whatever the operator has cloned into their workspace).

## Architecture

```
           +------------------+
           |   Mission Core   |   core/mission/definition.py (5 pillars + aspirations)
           +---------+--------+
                     |
                     v
        +---------------------------+
        |  UnifiedDirector          |   scores every proposal against mission
        |  Breakthrough Engine      |   hunts convergence + anomalies
        |  Aspiration Engine        |   tracks long-lived goals
        |  War Room                 |   daily battle plan
        +-----------+---------------+
                    |
                    v
    +---------+---------+---------+---------+---------+
    | 17 Domains       | 81 Engines         | Evidence DB |
    +---------+---------+---------+---------+---------+
    |                               |
    v                               v
    Schema Registry                Transport
    (single source of truth)       (peer sync, snapshots, MCP)
```

Text-only diagram on purpose: every arrow downstream from the mission core should be traceable to a mission pillar. Nebula never acts on LLM opinion alone; findings flow through Bayesian hypothesis evolution and cross-engine collision detection before they earn confidence.

## Quick Start

```bash
git clone https://github.com/ZenonOrg/nebula && cd nebula
pip install -r requirements.txt
cp env.example.txt .env        # add at least one LLM API key (XAI_API_KEY recommended)
./nebula --cycles 5            # run five cycles, see what it found
./nebula status                # summary of findings, hypotheses, collisions
```

Zero external infrastructure required. Nebula reads a public Zenon RPC node by default (set `ZENON_PUBLIC_RPC` to point at your own). Nine of the 17 domains work with zero keys; adding `XAI_API_KEY` unlocks the strategic synthesis engines (~$0.01/cycle).

## CLI Commands

| Command | Description |
|---------|-------------|
| `./nebula` | Run continuously (24/7) |
| `./nebula --cycles N` | Run N cycles then stop |
| `./nebula --budget N` | Run with a USD budget cap |
| `./nebula --hours N` | Run for N hours |
| `./nebula --domains sec,qual` | Run only selected domains |
| `./nebula status` | Show evidence count, hypotheses, collisions, uptime |
| `./nebula findings` | Show recent findings with lifecycle status |
| `./nebula plan` | Show the latest War Room battle plan |
| `./nebula domains` | List every registered domain and its engines |
| `./nebula hypotheses` | Show Bayesian hypotheses with current confidence |
| `./nebula costs` | LLM cost breakdown by provider and model |
| `./nebula specs` | Spec coverage matrix across go-zenon, SDKs, CLI, wallet |
| `./nebula height` | Evidence-chain height (append-only) |
| `./nebula serve` | Start the MCP server (8 tools) |
| `./nebula rpc` | Start the JSON-RPC server (default: 127.0.0.1:8484) |
| `./nebula snapshot export` | Export evidence snapshot for peer sharing |
| `./nebula snapshot import FILE` | Import a peer snapshot |
| `./nebula sync` | Pull the latest snapshot from configured peers |
| `./nebula ask "question"` | Freeform query against the knowledge graph |

## 17 Domains, 81 Engines

### Building and shipping

| Domain | Engines | Purpose |
|--------|---------|---------|
| development | spec_tracker, impl_coverage, upstream_monitor, dependency_chain, spec_drift | Spec tracking, implementation coverage, upstream change detection |
| quality | spec_verifier, build_verifier, cross_repo_checker, test_coverage, sdk_verifier | ABI byte-level comparison, build verification, SDK field checks |
| security | adversarial_reviewer, vuln_scanner, static_analyzer, report_generator, attack_simulator, bridge_scanner, cve_monitor, exploit_scanner | Attack surface analysis, CVE tracking, fund-safety reviews |
| standards | bip_zip_tracker, deployment_pipeline, crypto_compliance | BIP/ZIP tracking, release pipeline, crypto primitive compliance |
| devops | devnet_manager, rpc_client, integration_tests, test_runner | Devnet orchestration, JSON-RPC smoke tests, integration runners |
| contribution | pr_readiness, pr_description_gen, tminusz_contributor, auto_contributor | PR checklist, description generation, test vector extraction |

### Understanding the network

| Domain | Engines | Purpose |
|--------|---------|---------|
| intelligence | upstream_watcher, signal_detector, signal_router, ecosystem_health, community_scanner | Git firehose, commit classification, signal routing |
| governance | treasury_monitor, proposal_analyzer, voting_patterns, governance_intel, pillar_accountability | Accelerator-Z runway, proposal lifecycle, per-pillar voting |
| network_health | node_census, decentralization_scorer, bridge_health, pillar_monitor | Nakamoto / HHI / Gini, bridge TVL, pillar uptime |
| economics | supply_tracker, staking_analyzer, liquidity_monitor, funnel_tracker, hype_detector, whale_watcher, yield_calculator, thesis_tracker | Emission, staking, DEX depth, participation funnel, supply-contraction thesis |

### Strategy and narrative

| Domain | Engines | Purpose |
|--------|---------|---------|
| product_market_fit | landscape_scanner, technical_positioning, roadmap_predictor, adoption_tracker, comparative_engine, future_detector, prediction_engine, product_surface, ecosystem_gap, fork_detector | Competitive mapping against Bitcoin-adjacent programmability projects (Stacks, RSK, Botanix, Citrea, etc.) and any reference chain in the workspace |
| investigation | architecture_analyzer, vision_tracker, historical_scanner, literature_engine | Code archaeology, architectural patterns, historical context |
| marketing | narrative_analyzer, ecosystem_positioning, narrative_dominance, bitcoin_narrative_builder | Narrative resonance, BTC-adjacent story hunting |

### Self-awareness

| Domain | Engines | Purpose |
|--------|---------|---------|
| education | doc_quality, onboarding_tracker | Wiki completeness per contract, developer onboarding grading |
| community | contributor_tracker, health_scorer, sig_tracker, talent_radar, sentiment_tracker | Contributor activity, SIG tracking, sentiment |
| interoperability | bridge_compat, evm_readiness, consensus_monitor | Bridge versioning, HyperQube/Supernova, cross-chain consensus |
| self_maintenance | engine_health, config_drift | Engine success-rate monitoring, config drift detection |

## Core Modules

Nebula separates orchestration from discovery. The core layer is deliberately small and deterministic so domain engines can rely on it without worrying about ordering or state leaks.

**Mission and priorities** - mission.py, director.py, war_room.py, strategy_evolver.py, aspiration_engine.py, breakthrough_engine.py, red_team.py, persona_panel.py

**Evidence and hypotheses** - persist_to_db.py, schema_registry.py, evidence_vault.py, feedback_bus.py, collision_engine.py, knowledge_graph.py, validation_spiral.py, synthesis_engine.py, cascade_detector.py, hypothesis_engine.py, hypothesis_hardener.py, peer_corroboration.py

**Orchestration** - domain_registry.py, engine_scheduler.py, parallel_runner.py, run_context.py, template_dag.py, adaptive_router.py

**LLM routing** - model_router.py, llm_provider.py, prompt_builder.py, cost_optimizer.py

**Discovery** - discovery_base.py, curiosity.py, workspace_discovery.py, corpus.py, experiment_manager.py, self_extension.py, self_improver.py

**Network and data** - zenon_data.py (HTTP JSON-RPC to the Zenon chain), node_rpc.py (WebSocket to local znnd), nebula_rpc.py (HTTP server for peer Nebulas), explorer_api.py, market_data.py, github_api.py, universal_rpc.py, vuln_feed.py

**Transport and peers** - transport.py, sync.py, mcp_bridge.py, commons.py, integrations/

**Safety** - trust.py, opsec.py, hallucination_guard.py, forensic_audit.py, resilience.py, plausibility_gate.py, novelty_checker.py, finding_verifier.py, anomaly_detector.py

**Utilities** - commons.py, workspace.py, git_cache.py, file_extractors.py, api_fingerprint.py, failure_classifier.py

## Data Sources

Nebula pulls from every public source that matters for Zenon, with no special access required:

- **Zenon RPC** - HTTP JSON-RPC (default `https://my.hc1node.com:35997`) or local znnd via WebSocket. Ledger, pillar, sentinel, accelerator, token, bridge, stake, plasma namespaces all covered.
- **Git repositories** - whichever Zenon ecosystem repos are present under `ZENON_WORKSPACE_ROOT`. Nebula scans them every cycle for commits, spec drift, and dependency changes. Repos that aren't cloned locally are skipped (engines that depend on them return empty and log a "workspace missing" note). See "Local vs remote tracking" below.
- **GitHub API** - PR status, issue activity, contributor graphs.
- **CoinGecko** - ZNN / QSR price, market cap, 24h volume, rolling returns.
- **DexScreener** - wZNN/ETH pair depth, liquidity, trader counts.
- **DefiLlama** - bridge and protocol TVL via the `zenon-finance` slug.
- **LunarCrush** - social sentiment metrics when `LUNARCRUSH_API_KEY` is set.
- **OSV.dev** - dependency CVE lookups for go.sum / pubspec.lock.
- **Fear & Greed (alternative.me)** - market sentiment context.
- **Stacker News, HN Algolia, r/Bitcoin** - Bitcoin-narrative scanner inputs.
- **MCP peers** - SETI and any MCP-compatible tool plugged in via `NEBULA_MCP_PEERS`.

Every API integration is documented in the audit report `core/api_templates/` and rechecked by the quality domain on a schedule.

## Schema Registry

Every engine owns its tables. `core/schema_registry.py` walks the core package plus every domain plugin and engine module at startup, collects declared `SCHEMA_SQL` fragments, and applies them in dependency order with `CREATE TABLE IF NOT EXISTS`. Adding a new engine automatically adds its tables; removing one never leaves dead schema.

This replaces the old three-places-to-declare-schema pattern that caused "no such column" errors whenever an engine evolved ahead of `persist_to_db.SCHEMA_SQL`.

## Mission Alignment

`core/mission/definition.py` declares five weighted pillars: technical excellence (0.28), ecosystem expansion (0.20), narrative dominance (0.20), security hardening (0.20), adoption growth (0.12). `mission_alignment()` grades any finding against every pillar deterministically using domain membership, keyword density, and explicit tags. The Director boosts aspirations that rank high on mission alignment. The Breakthrough Engine flags any finding whose overall alignment crosses 0.65 as a `breakthrough_candidate` even without convergence or anomaly support.

## Breakthrough Hunting

`core/breakthrough_engine.py` runs three detectors every 10 cycles:

1. **Cross-engine convergence** - two or more distinct engines reporting the same evidence type inside a 24-hour window promote the signal.
2. **Anomaly amplification** - a single finding more than three sigma above its engine's baseline confidence distribution gets promoted.
3. **Mission-critical surfacing** - a single finding with `mission_alignment.overall >= 0.65` gets promoted.

Breakthrough candidates are persisted with evidence type `breakthrough_candidate` so the War Room can inspect them first. The whole module is deterministic: zero LLM cost.

## Aspiration Engine

`core/aspiration_engine.py` collects aspirations from the mission core and from every domain plugin, grades them on alignment / support / feasibility, and retires the ones that produce no progress for 50 cycles. Aspirations are queryable via `nebula aspirations`. Engines signal progress by persisting evidence with type `aspiration_progress:<title>`.

## MCP Integration

Plug Nebula into Claude Code, Cursor, or any MCP-compatible tool:

```bash
claude mcp add nebula python3 scripts/mcp_server.py
```

Eight tools exposed: `nebula_status`, `nebula_spec_coverage`, `nebula_security_findings`, `nebula_battle_plan`, `nebula_upstream_signals`, `nebula_aspirations`, `nebula_collisions`, `nebula_query`.

Questions like "what does Nebula say about the bridge?" route to the security and network_health evidence. Questions like "what's the next spec to ship?" route through the Director.

## Multi-Instance Sharing

Run multiple Nebula instances and share intelligence:

```bash
# Instance A: publish
./nebula snapshot export            # data/snapshot_<timestamp>.json

# Instance B: consume
./nebula snapshot import data/snapshot_<timestamp>.json
./nebula sync                       # pull from configured peers
```

Evidence records carry SHA-256 integrity hashes and participant attestation. `core/peer_corroboration.py` boosts confidence on findings that independent peers also produced; trust in unknown peers is capped at 0.30 until reputation is earned. Peer corroboration only ever raises confidence - never lowers it.

## Local vs remote tracking — what runs with what you have

Nebula has two kinds of engines: ones that read files on your disk, and
ones that call external APIs. The more repos you have cloned locally, the
more of Nebula's 86 engines actually produce output.

**Engines that REQUIRE a local clone** (silently no-op without it):

| Engine | Needs |
|---|---|
| `upstream_watcher` | `git -C <repo>` — any git repo in the workspace |
| `spec_tracker` · `spec_drift` · `impl_coverage` | `knowledge/developer-commons/docs/specs` + `core/go-zenon` |
| `btc_spec_tracker` | A Bitcoin-family repo with a `bips/` directory |
| `reference_diff` | A reference chain repo (Bitcoin, Ethereum, etc.) + Zenon repos |
| `repo_relationship_mapper` | Any workspace repos with manifests (go.mod, pubspec.yaml, package.json, Cargo.toml) |
| `contributor_tracker` · `architecture_analyzer` · `vision_tracker` | Source repos on disk |
| `protocol_family_classifier` | Any workspace repos (for classification signals) |
| `cross_chain_cve_monitor` | At least one reference chain repo in the workspace |

**Engines that work without any local clones** (API + on-chain only):

`community_scanner`, `ecosystem_health`, `cve_monitor`, `vuln_scanner`,
`node_census`, `decentralization_scorer`, `staking_analyzer`,
`treasury_monitor`, `supply_tracker`, `bridge_health`, `market_data`,
`narrative_analyzer`, `sentiment_tracker`, `consensus_monitor`,
`proposal_analyzer`, `voting_patterns`, `yield_calculator`.

Practical rule: if you only have go-zenon and znn_sdk_dart cloned, about
half of Nebula's engines produce data. Clone more of the ecosystem (see
`knowledge/`, `core/`, and `infrastructure/` sub-trees in the Zenon
workspace layout) and coverage grows linearly.

## Drop reference chains into your workspace to unlock cross-chain analysis

**This is one of Nebula's most powerful features and the easiest win once
you try it.** Zenon's specs, particularly PTLC, Portal, Bitcoin SPV, and
Sentinel Validator, consciously borrow from other protocols. Without a
reference implementation in the same workspace, Nebula can only reason
about Zenon in isolation. With one, a whole class of engines lights up.

### What happens when you add Bitcoin Core

```bash
# Assume your workspace already has go-zenon + SDKs.
cd ~/Repos/Zenon
git clone --depth 50 https://github.com/bitcoin/bitcoin core/bitcoin
```

On the next cycle, Nebula's `workspace_discovery` detects the new repo,
classifies it as `blockchain_node_btc` via the generic signatures in
`core/workspace_discovery.py::REPO_SIGNATURES`, and writes it to the
`workspace_repos` table. Four cross-chain engines then activate:

- **`domains/development/btc_spec_tracker`** — walks the `bips/`
  directory, maps each BIP to a corresponding ZIP in
  `knowledge/developer-commons/docs/zips/` (if present), and flags any
  BIP that has no ZIP counterpart. If BIP-324 is merged upstream but
  there's no ZIP-XX draft for equivalent Zenon work, Nebula surfaces
  the gap with a WHAT/SO WHAT/NOW WHAT finding.
- **`domains/security/cross_chain_cve_monitor`** — cross-references
  historical Bitcoin Core CVEs (CVE-2024-35202 merkle proof
  validation, CVE-2022-44797 btcd taproot signature malleability,
  etc.) against semantically similar function names in go-zenon.
  When `go-zenon/vm/embedded/bitcoin_spv/verify.go` contains a function
  shaped like Bitcoin's patched code path, you get a targeted "review
  this file for the same class of bug" finding.
- **`domains/quality/reference_diff`** — for consensus-critical
  primitives like merkle proof validation and secp256k1 signature
  verification, extracts the function body from both codebases, computes
  a structural diff (line count, cyclomatic complexity, decision
  points), and flags large divergences. A Zenon function that's 3x more
  complex than its Bitcoin reference is a smell worth reviewing.
- **`domains/investigation/protocol_family_classifier`** — classifies
  every workspace repo into a family (UTXO chain, account chain, zk
  rollup, bridge, SDK consumer, tooling) and lets cross-domain queries
  compare peers within a family.

### What happens when you add Ethereum (go-ethereum)

```bash
git clone --depth 50 https://github.com/ethereum/go-ethereum core/geth
```

`protocol_family_classifier` tags it as `blockchain_node_evm`. The same
four engines above re-run against EVM primitives. `reference_diff`
compares Zenon's EVM-adjacent code (the HyperQube extension chain work)
against go-ethereum's reference implementations. `cross_chain_cve_monitor`
pulls the known Geth CVE list as its corroboration baseline.

### What happens when you add Cosmos SDK

```bash
git clone --depth 50 https://github.com/cosmos/cosmos-sdk core/cosmos-sdk
```

Classified as `blockchain_node_cosmos`. Engines then compare Zenon's
governance contract against Cosmos `x/gov`, and (when Sentinel Validator
lands) compare Zenon's validator set management against Cosmos
`x/staking`. This was the Zenon governance spec's cited inspiration —
having the reference on disk lets Nebula actually check alignment.

### Why this is a killer feature

- **Cross-pollinate security fixes.** Bitcoin Core spends millions of
  dollars a year on adversarial review. Every CVE they find is public.
  Nebula can automatically ask "does Zenon have the same bug?" for
  every fix — something no human does continuously.
- **Find spec gaps before TminusZ does.** When Bitcoin adopts BIP-324,
  Nebula flags "no corresponding ZIP." The Zenon community sees the
  signal weeks before manual review would catch it.
- **Prove primitives are correct by triangulation.** `reference_diff`
  won't catch subtle logic bugs, but it will catch "Zenon's merkle proof
  verifier is 200 lines while Bitcoin's is 40" — a red flag that says
  either Bitcoin is missing a check or Zenon added something worth
  auditing. Either answer is valuable.
- **Zero extra LLM cost.** All four engines use stdlib parsing + regex.
  No API calls. Running them forever is free.

**The invitation:** if you run Nebula, spend the 30 seconds to
`git clone --depth 50 bitcoin/bitcoin` into your workspace. You will
start surfacing findings within one cycle that nobody else in the
Zenon ecosystem is looking at.

## The network effect: more instances = sharper signal

**Nebula gets smarter as more people run it.** This isn't marketing — it's a
consequence of how the evidence and hypothesis layers are designed.

Each operator runs their own Nebula instance against their own workspace
(different forks, different API keys, different schedules, different
subsets of the 17 domains). Every instance independently produces findings
and hypotheses. Those findings flow to a shared commons via
`./nebula snapshot export` or the Nexus transport, and every other instance
pulls them via `./nebula sync`.

What happens next is the key:

- **Independent confirmation boosts confidence.** If instance A's
  `vuln_scanner` flags a bug in go-zenon and instance B's
  `adversarial_reviewer` independently flags the same bug, the
  Bayesian hypothesis update in `core/peer_corroboration.py` combines
  those two signals into a higher-confidence hypothesis than either
  alone. Two independent engines from two independent operators is
  much stronger evidence than either one alone.
- **Coverage compounds.** Operator A might have go-zenon on their disk
  but not znn_sdk_dart; operator B has the opposite. A single operator
  can only ever scan what they have. The commons sees the union.
- **Stale signal ages out.** `core/hypotheses/hardener.py` retires
  hypotheses whose supporting evidence is older than the staleness
  window. When multiple instances refresh the same finding on different
  schedules, the commons always has recent evidence.
- **Bias detection gets cheaper.** `hypothesis_hardener.py` flags
  single-source bias ("all supporting evidence came from one engine").
  With more operators running, the probability of single-source bias
  drops toward zero — there are more engines across more instances
  producing evidence against the same hypothesis.
- **Trust model prevents poisoning.** A malicious peer publishing
  garbage can only ever move a finding's confidence by at most their
  trust score, which is capped at 0.30 for unknown peers. Corroboration
  only ever raises confidence — a bad peer can't lower a good peer's
  finding. Trust compounds over time with a proof-of-work-style
  reputation curve.
- **Aggregate metrics become reliable.** Cost tracking, engine health,
  budget pacing — single-instance stats are noisy; commons-wide stats
  are actionable.

The practical implication: if you're the only operator running Nebula, you
get a solid solo-researcher tool. If you're one of ten, the commons is
richer than any of you could produce alone. If you're one of a hundred,
Nebula becomes a real-time distributed intelligence surface for the entire
Zenon ecosystem — which is the design target.

**The easiest way to make Nebula smarter is to run it.** Every new
operator's findings become everyone's signal, subject to the trust model.
See `docs/operations/multi-instance.md` for the transport modes (local
snapshots, Nexus via SpacetimeDB, shared directory) and the OPSEC
guarantees on what leaves your instance.

## Portability

Nebula works the same way whether you checked out the whole Zenon workspace or just cloned Nebula alone:

- `ZENON_WORKSPACE_ROOT` env var controls where Nebula looks for sibling repos.
- Engines that scan sibling repos degrade gracefully to "no data" when the repo isn't present.
- No hardcoded `/Users/...` or `/home/...` paths; everything resolves via `core/workspace.py` helpers.
- `NEBULA_SKIP_WAR_ROOM=1` lets headless runs skip the LLM step for CI scenarios.
- `requirements.txt` covers the core loop; `requirements-full.txt` adds PDF/image/OCR support for file_extractors.

## Cost

Most of Nebula runs free. LLM calls are reserved for strategic reasoning.

| Component | Cost |
|-----------|------|
| Local engines (git scans, filesystem, API queries, RPC) | Free |
| Collision detection, feedback bus, evidence storage | Free |
| Knowledge graph, hypothesis evolution, breakthrough hunt | Free |
| Director synthesis, War Room battle plan | 1-2 LLM calls/cycle |
| Security adversarial review | 1 LLM call per contract |

Nebula uses **xAI Grok exclusively** — chosen for cost. Grok 4.20 is
the cheapest frontier model that can handle the strategic synthesis
work, and `grok-4-1-fast-non-reasoning` is even cheaper for the
classification and routing tasks. The model router picks the right
tier per task. A single cycle averages about $0.01. One hundred cycles
costs roughly one dollar. The prompt cache and the v0.2.18 circuit
breaker keep the bill capped even under bursty load.

Set `XAI_API_KEY` in `.env` (or via `./nebula config api-key`).
Get a key at <https://console.x.ai>.

## Stats

Live counts are in the auto-regenerated block at the top of this README.
Run `python3 scripts/regen_docs.py` after any structural change; a pre-commit
hook also invokes it in `--check` mode.

## Adding a Domain

Domains are auto-discovered at runtime. Drop a plugin in `domains/`, restart. Every engine should declare its own `SCHEMA_SQL` constant so the registry picks the table up automatically.

```python
from core.domain_registry import DomainPlugin, EngineDefinition

class MyDomain(DomainPlugin):
    @property
    def name(self) -> str:
        return "my_domain"

    def get_engines(self) -> list:
        return [EngineDefinition(
            name="my_engine",
            module_path="domains.my_domain.engines.my_engine",
            priority=5,
            status="built",
        )]
```

See `domains/` for seventeen complete examples.

## License

MIT - see [LICENSE](LICENSE).

---

Built with Python 3.10+, SQLite, and xAI Grok.

[Zenon Network](https://zenon.network) / [ZenonOrg](https://github.com/ZenonOrg) / [Developer Commons](https://github.com/TminusZ/zenon-developer-commons)
