# Architecture and code map

> The binaries, cargo features, top-level modules, tools layer, guides and owner page that make up the Orbit codebase.
>
> Describes Orbit 0.1.9. Web page: https://docs.orbit.dialectic.com/0.1.9/contributing/architecture/

This page is a map of the Orbit source tree for contributors. It names the two binaries, the cargo features that split the read-write and read-only builds, what each top-level module under `src/` owns, and how tools, guides and the owner page are wired. Paths are repo-relative; behaviour is as of Orbit 0.1.8.

## Binaries

| Binary | Entry point | What it is |
| --- | --- | --- |
| `orbit-mcp` | `src/main.rs` | The MCP server (stdio transport, via `rmcp`), plus a set of subcommands: `init`, `onboard`, `quick-setup` (write build only), `call`, `keystore-create`, `register-api-key`, `owner-serve`, `owner-url`, `self-update`, `support-bundle`, `doctor`, `repair-database`, `recovery-export`, `discover-module`, `hyperliquid-stop`, `help`. Any tool can also be run from a shell as `orbit-mcp <tool> --json` (`src/cli.rs`); `orbit-mcp <tool> --help` is rendered from the tool's own schema (`src/tool_help.rs`). |
| `orbit-watchdog` | `src/bin/watchdog.rs` | The standalone loss-breaker watchdog. No MCP, no policy engine at runtime, no operator key: it holds a guardian keystore, follows the module's events, runs the same detection core as Orbit (`policy::bleed`) and calls `pause()` when it trips. It shares no process, key or config with `orbit-mcp`. Declared with `required-features = ["write"]`, so it exists only in the write build. Example config: `packaging/watchdog.example.toml`. |

The shell CLI does not have its own dispatch. `src/cli.rs` constructs the same `Service`, serves it over an in-memory `tokio::io::duplex` pipe and sends the same `initialize` / `tools/call` JSON-RPC frames a host sends, so argument decoding, gating and serialization are identical by construction.

## Cargo features

Defined in `Cargo.toml`:

| Feature | Default | Effect |
| --- | --- | --- |
| `write` | yes | Signer construction (local keystore and GCP KMS), Tenderly simulation, the owner endpoint (`axum`), the keystore wizard, and every signing tool. Enables `makinax/write`, `makinax/tenderly`, `makinax/fetch-kyber` and the makinaX MCP server library's `write` feature. |
| `acceptance-fixtures` | no | Test only. Lets a paid package's issuer be a loopback fixture curator so a release-shaped binary can run acceptance rows. The binary announces it on stderr and in `--version`; release and CI refuse any artifact carrying its marker (`scripts/assert-no-acceptance-fixtures.sh`). |

The read-only build is `cargo build --no-default-features`. Signing is compiled out, not switched off at runtime: modules behind `#[cfg(feature = "write")]` in `src/lib.rs` include `pipeline`, `policy`, `writes`, `simulation`, `quotes`, `quote_store`, `orbit_hook`, `owner`, `owner_launch`, `safety`, `recovery`, `gas_route`, `keystore_wizard` and the `watchdog_*` settings modules. Read-class code (data-feed signature recovery, CCTP attestation tracking, package install and verification, composition) compiles in both builds.

## Startup and process roles

`src/main.rs` loads settings, then:

1. If config cannot be loaded, it comes up in **diagnostic mode**: a valid MCP server offering one tool (`src/tools/diagnostic.rs`) that explains the problem, and that promotes itself to the full server once a valid config appears (`src/tools/promote.rs`).
2. Otherwise it takes a role from `src/single_instance.rs`: **acting** (holds `<state>/kit.lock`) or **observing**. Only the acting process runs the background poller and serves the owner endpoint; an observing process still serves tool calls and promotes itself if the holder exits.
3. It starts the config watch (both roles follow `config.toml`), the poller and the owner endpoint (acting only), then serves MCP on stdio.

Stdout is the protocol wire. `src/stdio.rs` owns file descriptor 1; logs go to stderr, which `src/stderr_scrub.rs` scrubs of credentials, including output from child processes such as the anvil fork. A stdin watchdog makes the server exit when its host disconnects. One structured stderr line at startup (`src/startup_diag.rs`) records names and presence, never environment values.

## Top-level modules

Grouped by concern. Files are under `src/`.

### Write path

| Module | Owns |
| --- | --- |
| `pipeline/` | Orchestration: build → simulate → policy → execute or enqueue for review. `PipelineCtx` carries every collaborator. Both MCP tools and the owner endpoint go through here; `writes::execute` is not reachable in production code without passing policy. Also `breaker` (records loss observations), `agent_approval` (who may resolve a review), `core_perp` / `core_transfer` (HyperCore orders and transfers). See [Request flow](https://docs.orbit.dialectic.com/0.1.9/contributing/request-flow/). |
| `writes/` | The only path that signs. `build` (call specs → calldata, using makinaX), `simulate` (eth_call, anvil fork, Tenderly), `fork` (warm anvil fork manager), `execute` (receipt check, pre-send approval, send locks, broadcast, ledger), `send_gate` (cross-process `send.lock`), `receipt_window` (the fixed receipt window, a constant in that module), `cancel` (`cancel_unresolved_send`), `in_words` (plain-language verdicts), `operator_native` (Orbit's own wallet sends). |
| `policy/` | Mandate model and rule engine. `engine` (pure rule evaluation: first deny wins), `global` / `global_eval` (the global mandate, caps over global NAV), `mandate`, `registry`, `review`, `bleed` (loss circuit breaker detection core, shared with the watchdog), `matrix` (pre-explains the module's WALLED-mode checks; informational, the chain enforces), `sources` (staleness and severity sources). |
| `orbit_hook.rs` | The pre-send hook passed to makinaX's `Executor`: a module call is signed only if this process's pipeline approved it after consuming its simulation receipt. Approvals are counted, one per consumed receipt. |
| `simulation/`, `quotes/`, `quote_store.rs` | Re-exports of makinaX's Tenderly client and quote adapters, plus Orbit's own TTL'd `QuoteStore`. |
| `safety/` | `audit_log`: the append-only JSONL audit log of every write attempt. |
| `owner_tx.rs`, `owner_tx/` | The single pipeline for owner-destined Safe transactions: ordered call list → fork simulation as the Safe (write builds) → Tx Builder JSON, per-call summary and a simulation verdict. |
| `gas_route/` | Operator gas top-ups across networks through Relay, signed by Orbit's own wallet and tracked outside the bridge ledger. The one approved protocol-specific integration. |
| `activation/` | Runs package-declared one-time activation steps once the owner's root is active, at most once per leaf. |
| `pending_collect/` | Request-then-collect exits a package declares (`async_actions`). |

### Chain, packages and composition

| Module | Owns |
| --- | --- |
| `chain/` | Providers, contract bindings (`IMakinaXModule`, `IERC20`, oracle registry), the module factory, block tags, position value reads. |
| `instructions/` | Re-exports the instruction library, builder, proofs and root check from `makinax::ext`, plus Orbit's wrappers: the `Rootedness` and `RootOnChain` truth facts, loader refusals, and operational instruction shapes (gas top-up, ERC-20, Hyperliquid deposit). |
| `packages/` | Curator-signed package manifests: catalog fetch, signature verification, registry, provenance, `audit`, activation steps, async actions. See [Packages for curators](https://docs.orbit.dialectic.com/0.1.9/contributing/packages-for-curators/). |
| `compose/` | Local root composition: persisted caliber → rendered `caliber.yaml` → transpile at the pinned integrations ref → a proven `setAllowedInstrRoot` transaction. |
| `feed/` | Curator data-feed consumer: verifies signed payloads against the configured curator key, caches them, drives staleness. Read-class, in both builds. |
| `bridges/` | Orbit's pending-bridge state machine (persisted in the `operations` ledger), destination-chain settlement resolvers, the CCTP claim path and attestation tracking (`iris`). Codecs and the bridge-id registry live in makinaX. |
| `migrate/` | Module migration: export the current module's config, diff against a new module, emit Tx Builder JSON. Orbit reads and generates; the owner signs. |
| `setup/` | `verify_setup`: derives on-chain requirements from the rootfile and config, probes them, and reports `ok` / `missing` / `unverified`. Also the execute-time `preflight` gate. |
| `onboard/`, `onboarding.rs`, `onboarding_quick_setup.rs`, `cross_surface.rs` | The onboarding state machine and its surfaces: setup batches, layers (`onboard/layers.rs`), funding plans, proposer keys, quick setup. |
| `kit_chain.rs` | Verified network profiles and which networks support new Safes. |
| `owner_targets.rs`, `erc20_allowlist.rs`, `gas_top_up.rs`, `perp_markets.rs`, `settings_consent.rs` | Owner-reviewed settings that become composed leaves or are approved by the owner's batch signature. |
| `hl_agent.rs`, `hl_exchange.rs` | Hyperliquid account changes signed by a registered agent wallet. |

### Reads, ledger and reliability

| Module | Owns |
| --- | --- |
| `reads/` | Balances, prices, HyperCore account reads, pinned calls. |
| `portfolio/` | The `get_portfolio` document, NAV, exposure, and the background poller (snapshots, event sync, veto-window auto-execution, bridge resolution, CCTP claims, heartbeat). |
| `indexer/` | The SQLite store (`positions.db`) and its tables, `event_sync` (chunked, checkpointed `eth_getLogs` follow of module events), integrity check and repair. |
| `reliability/` | Never-silent failure classification into the `operations` table, reconciliation of pending operations at startup and on every poll, and file-based heartbeats. |
| `truth.rs`, `governance.rs`, `broadcast_outcome.rs` | Shared vocabulary: unknown is a value (`Tri`), governance is one produced value, and what the chain said about a broadcast hash. |
| `step_reason/`, `refusals.rs`, `owner_text.rs` | What a failed step returned, the plain owner words for on-chain refusals, and sanitizers for outside text in owner sentences. |

### Configuration, keys and host

| Module | Owns |
| --- | --- |
| `settings.rs` | Config loading and defaults. See [Config and state](https://docs.orbit.dialectic.com/0.1.9/reference/config-and-state/). |
| `credentials.rs`, `key_scope.rs`, `curator_register.rs`, `curator_x402.rs`, `install_mint.rs`, `x402_weth.rs` | Curator feed credentials and how they are obtained and scoped. |
| `keystore_wizard.rs`, `secrets.rs`, `perms.rs`, `held_addresses.rs`, `recovery.rs` | Keystores, passphrase handling (kept out of child processes), file permissions for credential-bearing state, and the user-controlled recovery download. |
| `single_instance.rs`, `file_lock.rs` | Process roles and locks (below). |
| `update_policy.rs`, `host_ops.rs`, `upgrade_011.rs` | Which release the updater may install, prebuilt self-update and disk doctor, and the one-shot upgrade of older state. |
| `watchdog_config.rs`, `watchdog_runtime.rs`, `watchdog_settings.rs`, `watchdog_restart.rs` | Orbit's side of the watchdog: validation, readiness, shared settings, cooperative restart. |
| `support_bundle.rs`, `redact.rs`, `stderr_scrub.rs`, `startup_diag.rs` | Redacted support archives and credential redaction. |
| `guides.rs`, `tool_help.rs`, `cli.rs`, `stdio.rs` | Guides, generated help, the shell surface, stdout ownership. |
| `signing_page.rs` | Links to the static owner signing page on Dialectic's site; what is signed travels in the URL fragment. |

## The tools layer

All MCP tools live in `src/tools/`. `src/tools/mod.rs` defines `Service`, the `rmcp` server handler, and assembles one router from many `#[tool_router(router = …)]` blocks, one per file:

| Router | File |
| --- | --- |
| `tool_router` | `src/tools/mod.rs` |
| `read_tool_router` | `src/tools/read_tools.rs` |
| `write_tool_router` (write build only) | `src/tools/write_tools.rs` |
| `setup_tool_router` | `src/tools/setup_tools.rs` |
| `compose_tool_router` | `src/tools/compose_tools.rs` |
| `package_tool_router` | `src/tools/package_tools.rs` |
| `onboard_tool_router` | `src/tools/onboard_tools.rs` |
| `guide_tool_router` | `src/tools/guide_tools.rs` |
| `gas_tool_router`, `root_update_tool_router` (write build only) | `src/tools/gas_tools.rs` |
| `owner_tool_router` | `src/tools/owner_tools.rs` |
| `migrate_tool_router` | `src/tools/migrate_tools.rs` |
| `allowlist_tool_router` | `src/tools/erc20_tools.rs` |
| `perp_permissions_tool_router` | `src/tools/perp_tools.rs` |
| `perp_market_data_tool_router` | `src/tools/perp_market_data.rs` |
| write build only | `credential_tools.rs`, `first_action_tools.rs`, `package_selection_tools.rs`, `checkout_tools.rs`, `subscription_checkout_tools.rs`, `renewal_tools.rs`, `setup_funding.rs`, `owner_change.rs`, `gas_route_tools.rs`, `funding_plan_tools.rs`, `plan_move_tools.rs`, `unused_wallet_tools.rs`, `owner_chat_steps.rs`, `owner_console_reads.rs`, `core_hype_tools.rs`, `hyperliquid_signer_tools.rs`, `activation_tools.rs`, `hl_account_tools.rs`, `protective_orders.rs`, `perp_order.rs` |

`Service::product_routes()` sums these routers. The read-only build sums only `tool_router`, `guide`, `package`, `onboard`, `gas`, `allowlist`, `perp_permissions`, `perp_market_data`, `migrate`, `read`, `setup`, `compose` and `owner`. `Service::routes()` adds the makinaX allowlist router from `src/tools/makinax_surface.rs` (see [makinaX and the module](https://docs.orbit.dialectic.com/0.1.9/contributing/makinax-and-the-module/)).

Every published tool passes through `Service::combined_router()`, the one funnel used by the advertised list, `tool_names`, `tool_descriptor` and CLI help. It does two things to each route:

- **Annotations.** It sets the MCP annotations from `src/tools/annotations.rs`. That file holds `EFFECTS`, a name-sorted table with one row per tool the build can register, each assigned an `Effect`:

  | `Effect` | Meaning | MCP hints |
  | --- | --- | --- |
  | `Read` | Observes; changes nothing | `readOnlyHint: true` |
  | `ReadLocal` | Observes this host only | `readOnlyHint: true`, `openWorldHint: false` |
  | `LocalWrite` | Writes local state; repeating may write again | not read-only, not destructive, not idempotent |
  | `LocalSettle` | Writes local state; repeating lands the same state | not read-only, not destructive, idempotent |
  | `LocalReplace` | Overwrites or removes local state | destructive, idempotent |
  | `Broadcast` | Signs, broadcasts, or hands a signature to a service that will | destructive, not idempotent |

  The rule written in the file: a call is a read when it neither signs, nor moves value, nor leaves anything a later call consumes as authorization or input. Minting a `quote_id` (`get_swap_quote`, `get_first_action`) is therefore not a read. A tool missing from the table is left unannotated, and `every_tool_declares_what_it_does_to_the_world` in `tests/agent_surface.rs` fails the build.
- **Identity schema.** `src/tools/identity_compat.rs` publishes one Safe identity shape (`safe`) in every input schema, with older shapes kept and marked.

Tool argument types derive their JSON schemas with `schemars`; the doc comments on fields ship to the agent. Errors are mapped to MCP errors with a structured `data` payload; see [Request flow](https://docs.orbit.dialectic.com/0.1.9/contributing/request-flow/#how-refusals-are-shaped).

## Guides

`src/guides.rs` embeds every `skills/*/SKILL.md` at compile time with `include_str!` (the `GUIDES` list must equal the `skills/` directory; a unit test enforces it). The served copy:

- has its frontmatter `version:` stamped with the crate version (`stamp_version`, the same rule as `scripts/stamp-skill-version.py`);
- in the read-only build, has every region between `<!-- write-build-only -->` and `<!-- /write-build-only -->` removed (`strip_write_only`).

Guides reach the agent two ways: the `get_guide` tool (`src/tools/guide_tools.rs`; no `name` returns the index, `stub: true` returns a short SKILL.md that defers to `get_guide`) and MCP resources under `orbit://guides/<name>` (`list_resources` / `read_resource` on `Service`). Orbit never writes a host's skills folder.

## The owner page

The owner page is where confirmations, mandate activation and owner-only settings happen; there is no MCP tool that approves a confirmation or activates a mandate. It exists only in the write build.

- **Frontend.** React + Vite in `src/owner/web/` (wagmi, viem, RainbowKit for in-page wallet signing). `vite-plugin-singlefile` produces one file, `src/owner/web/dist/index.html`, which `src/owner/page.rs` embeds with `include_str!`. The built `dist` is committed; see [Build and test](https://docs.orbit.dialectic.com/0.1.9/contributing/build-and-test/).
- **Server.** `src/owner/mod.rs` (axum). The port is `[owner] port`; `[owner] bind` is `localhost` or `tailscale`, which binds the machine's tailnet IP. Host-header guards accept only names of the bound address. `/api` routes require `Authorization: Bearer <token>`; the token is a 256-bit random value in `<state>/owner-token`, written `0600`. The token is not the boundary for activation: activating or rolling back a mandate requires an EIP-191 signature by a Safe owner. Console routes call the same `#[tool]` methods the MCP server exposes.
- **When it runs.** The acting MCP process serves it; `orbit-mcp owner-serve` serves it with no MCP session. `<state>/owner-endpoint.lock` ensures only one process serves it.
- **Launch codes.** `open_owner_wizard` does not put the bearer token on a command line. `src/owner_launch.rs` issues a one-time code, stored only as a SHA-256 digest in the state dir, valid for a short fixed window (the `LAUNCH_TTL_SECS` constant) and redeemable once; the browser opens `/launch?code=…` and trades it for the session.

## Locks

| Lock | Where | Purpose |
| --- | --- | --- |
| `kit.lock` | `src/single_instance.rs` | One acting Orbit per state directory: pollers, CCTP claim signing, the background veto executor. A record with a liveness check, since pids are reused. |
| `owner-endpoint.lock` | `src/single_instance.rs` | One process serves the owner page. |
| `send.lock` | `src/writes/send_gate.rs` | Advisory lock held exactly around nonce read, signing and broadcast, so a CLI one-shot and a running server take turns at the operator nonce. Always taken after the in-process `PipelineCtx::send_lock`. |
| `policy.lock` | `src/pipeline/mod.rs` (`lock_policy_budget`) | Serializes policy evaluation and budget reservation across processes so two actions cannot both spend the same daily or cadence headroom. |

`tests/lock_discipline.rs` guards lock order, and `Cargo.toml` denies `clippy::await_holding_lock`.

## Library boundary

Shared mechanics (instruction library, merkle proofs, call encoding, fork lifecycle, Tenderly client, quote adapters, bridge codecs, owner batch types, the `Executor`) come from Makina's makinaX library, pinned by tag in `Cargo.toml`. Orbit reaches it only through `makinax::ext`, and many Orbit modules are thin "root shadows" that re-export a makinaX type at its old path and add Orbit's wording and truth facts. See [makinaX and the module](https://docs.orbit.dialectic.com/0.1.9/contributing/makinax-and-the-module/).
