# Request flow

> One action traced end to end through build, simulation, policy, review, execution, ledger and indexer, plus swaps, bridges, owner Safe batches and refusal shapes.
>
> Describes Orbit 0.1.9. Web page: https://docs.orbit.dialectic.com/0.1.9/contributing/request-flow/

This page follows one agent action through Orbit's write path, from the tool call to the ledger, and then covers the variants: swaps, bridges and owner Safe batches. It ends with how refusals are shaped. It is for contributors changing anything under `src/pipeline/`, `src/writes/` or `src/policy/`. Behaviour is as of Orbit 0.1.8; the code comments cited here are the authority.

## The shape

```
 agent ─ get_swap_quote (swaps only) ─► quote_id (TTL'd QuoteStore)
   │
   ├─ simulate_action ─► resolve ─► build ─► simulate ─► policy ─► result + sim_receipt (fixed window)
   │
   └─ execute_action(sim_receipt, idempotency_key)
          │
          ├─ earlier answer for this key? ─► return it
          ├─ resolve + build again
          ├─ setup preflight gate
          ├─ receipt peek (non-swaps)
          ├─ policy.lock ─► fresh facts simulation ─► policy (current counters)
          │        ├─ Deny ─────────► PolicyDenied refusal, audit "Refused"
          │        ├─ NeedsReview ──► pending_confirmations row, audit "ConfirmationQueued"
          │        └─ Allow
          └─ writes::execute ─► consume receipt ─► pre-send approval ─► send locks
                    ─► makinaX Executor (asks Orbit's hook) ─► broadcast
                    ─► receipt, events, executions + operations rows, audit, portfolio refresh
```

The orchestration lives in `src/pipeline/mod.rs`. Its header states the invariants: `writes` stays policy-free, `policy` is pure given facts, and the pipeline composes them, so there is no production path to `writes::execute` that skips policy. With no mandate, simulation still runs (the mandate error appears in its policy block) but execution refuses. Execution re-evaluates policy with current counters and a fresh simulation: a simulation receipt proves simulation, not permission.

## 1. The tool call

`simulate_action` and `execute_action` are in `src/tools/write_tools.rs`. Both take a `call` (a `CallSpec` from `src/writes/build.rs`) with one of five kinds:

| Kind | Purpose |
| --- | --- |
| `manage_position` | A curated position action by qualified name (for example `aavev3.add_collateral.USDC`), with `mgmt_params`. Amounts in base units. |
| `harvest` | A `kind: "harvest"` action from `list_actions`. One marked `claims_rewards` takes no params; Orbit fills the claim. |
| `swap` | Normally `quote_id` from `get_swap_quote`. A raw `order` without a quote is developer mode only. |
| `bridge` | A cross-chain send (see [Bridges](#bridges)). |
| `raw` | Raw calldata. |

Before the pipeline runs, the tool resolves which Safe is meant, settles symbols and token-unit amounts (`settled_call`, so the receipt matches between simulate and execute), refreshes the curator feed and NAV caches inline, and runs everything under a fixed deadline (the `EVALUATION_DEADLINE` constant in that file). A deadline that fires names the phase it stopped in.

`target` chooses where it runs: omitted means the live chain; `target: "fork"` is a practice run, allowed only in developer mode (`writes::run_on::authorize`). Practice runs read and write a separate rehearsal ledger (`RehearsalLedger` in `PipelineCtx`), so they never touch live budgets, cadence, breaker, reviews, NAV or ledgers. Every result says `ran_on`.

## 2. Resolve and build

`pipeline::resolve_call` turns the request into a concrete call: a swap's `quote_id` becomes an order (see [Swaps](#swaps)), a rewards claim is filled. `build_governed_call` then builds it through `writes::build`, which delegates encoding to makinaX (`makinax::ext`): the instruction is looked up in the Safe's loaded instruction library, its merkle proof is produced against the loaded rootfile, and the result is a `BuiltCall` (target, calldata, value, summary). An action that is not a leaf of the root has no proof and is refused as `unknown_action`; the merkle allowlist is absolute.

The call's identity for receipts is `writes::build::call_key(chain, machine, operator, built)`.

## 3. Simulate

`writes::simulate` has three backends (`SimBackend`): `eth_call` (fast; expected returns and gas), the local **anvil fork** (full balance deltas, snapshot and revert), and **Tenderly** (optional, only when `[tenderly]` is configured).

Backend choice is `pipeline::simulate_backend`:

- Swaps and bridges always need flow evidence, so an `eth_call` request is overridden with the fork.
- A call a mandate governs (other than `raw`) runs on the facts backend, because policy prices actions from balance deltas at the Safe. An explicit `eth_call` is overridden and `backend_override_ignored` says why.
- The facts backend (`pipeline::facts_backend`) is the warm anvil fork by default, which needs nothing but an RPC URL; Tenderly is used instead when it is configured and the chain is known to its API.
- An ungoverned, non-swap, non-bridge call with no requested backend uses `eth_call`.

On the fork, `gas_budget` is a fresh `eth_estimateGas` plus a fixed margin (makinaX's simulation gas budget), and it is the limit both the mined preflight and the later signed transaction use. A failed fork preflight carries its evidence (transaction, limit, receipt, block, terminal trace frame) in `error.details.preflight_evidence`, because the fork snapshot is reverted right after.

A successful simulation returns a `sim_receipt`. Its validity is a fixed wall-clock window, the same on every chain (the `WINDOW_S` constant in `src/writes/receipt_window.rs`, reported as `valid_for_s`); the library's block-based lifetime is set to an unreachable backstop. The result leads with `in_words`, a plain-language verdict the agent relays before executing.

## 4. Policy

`pipeline::policy_for` and `execution_policy` gather facts (prices, NAV, counters, feed severity, staleness, breaker state) and call the pure engine in `src/policy/engine.rs`. First deny wins; review thresholds are checked only after every deny rule passes; every rule that ran is listed in `rules_evaluated`. Rule ids include:

| Family | Example rule ids |
| --- | --- |
| Scope | `scope.denied_position_ids`, `scope.allow_debt_positions` |
| Curator feed | `severity`, `staleness`, `feed.capacity`, `feed.exit_capacity` |
| Caps | `caps.per_tx`, `caps.daily_deployment`, `caps.concentration`, `caps.per_target`, `caps.per_target_daily` |
| Cadence | `cadence.exit_exempt` |
| Breaker | `circuit_breaker`, `circuit_breaker.nav_unknown`, `circuit_breaker.unmeasured` |
| Pricing | `pricing` |

Percentage caps divide by global NAV, using the conservative reading (`src/policy/global_eval.rs`). Exits, repays and deleveraging are not blocked by a degraded denominator or a stale sibling. A cap that cannot be parsed is a deny, never an absent cap. The mandate's semantics are specified in `docs/mandate.md`.

The verdict is one of `Allow`, `Deny { rule, explanation, remediation }` or `NeedsReview { mode, reason }`.

## 5. Execute or enqueue

`pipeline::execute_with_policy` (and `execute_with_policy_inner`) runs in this order:

1. **Earlier answer.** If this `idempotency_key` already produced a result or a send that may be in flight, return that answer before anything else can refuse.
2. **Resolve and build** again, from the request.
3. **Setup preflight** (`setup::preflight::gate`). A verifiably missing precondition (feed routes; bridge encoder, route, recipient or loss cap) refuses as `setup_incomplete` with fix steps. An unverified check proceeds; the on-chain revert is the backstop.
4. **Receipt peek** for non-swaps: a missing or mismatched receipt refuses before any fork work. Swaps are checked later, because a re-quote legitimately changes the call key.
5. **Dev contamination check.** A live action is refused before simulating if `dev_rpc_urls` covers the chain or the warm fork has taken developer-mode executions.
6. **`policy.lock`**, then a **fresh facts simulation** and **policy** with current counters.
   - `Deny` → audit `Refused`, return `PolicyDenied`.
   - `NeedsReview` → insert a `pending_confirmations` row (`pc_…` id, the resolved call, the simulation, mode, `resolve_after`, `expires_unix`, and the original target), a `ReviewCreated` event and an audit `ConfirmationQueued`; return `PendingConfirmation { pending_id, reason, approve_hint }`.
   - `Allow` → continue.
7. A receipt for this exact call that merely outlived its window is replaced by the facts simulation's own receipt (the old id is spent).
8. **`writes::execute`** (`src/writes/execute.rs`, the only path that signs):
   - idempotency on the `executions` table (a duplicate returns the original with `duplicate: true`) and an in-flight check on `operations`;
   - subscription payment checks, where the call pays a subscription;
   - target gate for live sends: a non-dev signer, a governing mandate (or, for an exit only, the mixed-fleet rules: a Safe the signed limits don't name yet still lets exits run), and execution not paused (a declared exit with evidence is exempt from Orbit's soft pause);
   - receipt window check and `verify_and_consume`; then `orbit_hook.approve(key)` admits exactly one send of this call;
   - audit `SignatureRequested` (target, selector, args digest, receipt, key, initiator) before signing;
   - take the send locks (`send_lock` in-process, then `send.lock` across processes, then the fork turn for a dev run), re-check in-flight under the lock, set the nonce explicitly from the pending count and the gas limit from the proven budget;
   - send through `makinax::ext::Executor`, which asks Orbit's pre-send hook (`src/orbit_hook.rs`) before signing and refuses a call with no outstanding approval.
9. If the send hits `SimulationStale` or `SimulationExpired`, re-simulate once on the fork, re-run policy, and execute again with the same idempotency key.
10. **Budget lifecycle.** A reverted send is not charged (a `BudgetReconciled` event is written); a governed spend was reserved from the authorization facts; an ungoverned deployment is recorded after the fact.
11. Record a loss observation for the circuit breaker (`pipeline::breaker::record_observation`), attach any re-quote note, HyperCore order or transfer blocks, and phase timings.

`execute_action` returns a `status`: `success`, `reverted`, `pending`, `unknown_broadcast` or `dropped`. On `pending` or `unknown_broadcast` the answer carries `next`: retry with the same key or check `list_incomplete_operations`, never re-send under a new key. A send whose outcome cannot be established can be cancelled with `cancel_unresolved_send` (an empty self-transfer from the operator at the same nonce), only on the user's quoted approval.

Every attempt, including those that fail before a transaction exists, is recorded as an `operations` row with a decoded reason (`record_operation_outcome`, classified by `src/reliability/`). Reviews are not failures and are not recorded there.

## 6. Owner review

A queued review resolves in one of three ways, all through `pipeline::run_confirmed`:

- **The owner page**: `POST /api/confirmations/{id}/approve` or `/reject` on the owner endpoint.
- **The veto window**: under `veto_window` mode, the acting process's poller executes the item at `resolve_after` (quiet hours pause the clock) unless an objection was recorded. Under `explicit_approval` the item executes only on a recorded approval and expires at `window_s × expiry_multiplier`.
- **Chat**: `record_review_outcome` records the owner's genuine quoted reply (`user_message_quote`, channel, timestamp) as a `ReviewOutcomeRecorded` event. `approved` is accepted only for an action inside the limits the owner signed, one at a time per Safe; anything else must be approved on the owner page. `objected` cancels.

`run_confirmed` checks the resolution's source and authority (`pipeline::agent_approval`), takes `policy.lock`, refuses an expired review (`review_expired`), then atomically claims the row (`claim_pending`) so only one of the three paths can proceed. It re-simulates and re-evaluates policy before sending. A swap is re-quoted at approval time with the approved `min_out` as the floor (lowered only by `[mcp] approval_requote_drop_bps`); the result records `approved_min_out`, `fresh_min_out` and `effective_min_out`.

No MCP tool approves a review on the agent's own authority, and none activates a mandate: `record_review_outcome` only records the owner's own words, inside the limits the owner already signed.

## 7. Ledger, audit log and indexer

| Record | Where | Written by |
| --- | --- | --- |
| Audit log | `audit.jsonl` in the state dir (`[mcp] audit_log`), `src/safety/audit_log.rs` | Every write attempt: `Simulated`, `PolicyEvaluated`, `Refused`, `SignatureRequested`, `Broadcast`, `Executed`, `ConfirmationQueued`, `ConfirmationApproved`, `ConfirmationRejected`, `Attested` and others. Append-only JSONL. |
| `executions` | `positions.db` | The result of a completed send, keyed by idempotency key. |
| `operations`, `operation_attempts` | `positions.db` | Every attempt and its terminal status; pending-bridge records live in `operations.detail_json` with kind `bridge`. |
| `pending_confirmations` | `positions.db` | Queued reviews. |
| `events` | `positions.db` | Decoded module events and synthetic lifecycle rows (`ReviewCreated`, `BudgetReconciled`, bridge transitions). |
| `policy_reservations`, `policy_spend` | `positions.db` | Budget accounting. |

`src/indexer/event_sync.rs` follows the module's events with chunked, checkpointed `eth_getLogs`. A log whose transaction hash is in `executions` inherits that row's initiator (`agent` or `human`); everything else is recorded as `external`. The portfolio poller (`src/portfolio/poller.rs`) runs event sync, snapshots, veto auto-execution, bridge resolution, CCTP claims, reconciliation of pending operations and the heartbeat, in the acting process only.

## Swaps

1. `get_swap_quote` takes `input_token`, `output_token` (address or an unambiguous symbol) and one amount, fetches a quote from the KyberSwap adapter (keyless, from `makinax::ext`), and stores it in `QuoteStore` (`src/quote_store.rs`) under a `quote_id`. It flags `executable` and `missing_feed_routes`; when `executable` is false the agent must not simulate or execute.
2. Quotes are process-local and live for `[mcp] quote_ttl_s` (reported as `expires_in_s`), whose default is chosen so quote → simulate → execute fits by construction. They are not single-use within the TTL.
3. `simulate_action` with `kind: "swap"` and `quote_id`; the fork backend is forced.
4. `execute_action`. If the quote expired between simulation and execution, `resolve_call` re-quotes **once** with identical parameters and attaches `notes.requote` (`auto_requoted`, the previous and fresh adapter, `min_out` and `expected_out`); the answer is flagged `requoted: true`. A quote that cannot be refreshed refuses as `quote_stale`.

The swapper the quote names must map to a configured id (`[safes.<machine>.swappers]`) and be registered on the module; otherwise the refusal is `swapper_not_configured` or `swapper_not_registered`, with the chain's registration state and, only when registration is actually missing, the `set_targets_calldata` to fix it. The on-chain `minOutputAmount` stays the backstop.

## Bridges

Supported as of Orbit 0.1.8: Across (`bridgeId` 1) and Circle CCTP v2 (`bridgeId` 3), with verified signed routes and encoders from packages. LayerZero is refused. Relay is used only for operator gas (`src/gas_route/`), never for Safe funds.

- **Simulation** validates the source send only (`sendOutBridgeTransfer` and its `minOutputAmount` floor). It cannot observe arrival; the policy block's `settlement` field says so.
- **Execution** broadcasts the source-chain send and persists a `PendingBridge` record in `operations.detail_json` (`src/bridges/mod.rs`).
- **Settlement is decided by destination-chain on-chain events only.** Explorer APIs, if ever added, are advisory. States (from makinaX's `BridgeState`): `sent`, `received` (kept for old records, never assigned today), `credited`, `refunded`, `timed_out`, `failed`. Terminal: `credited`, `refunded`, `failed`.
- **Across** fills itself: `sent → credited` on the destination fill (`src/bridges/resolve.rs`).
- **CCTP** burns on the source and mints only when someone submits `receiveMessage` on the destination. Orbit tracks Circle's attestation (`src/bridges/iris.rs`) and submits the claim itself (`src/bridges/cctp_claim.rs`); settled is decided by the destination `MintAndWithdraw` event.
- The poller calls `bridges::resolve::poll_pending` every cycle; one-shot CLI calls and `owner-serve` run a bounded claim pass when no acting process exists (`src/bridges/claim_pass.rs`). `refresh_bridge_operation` re-checks one transfer on request. A read failure never resolves anything; the operation stays pending.

## Owner Safe batches

Anything the owner must sign as a Safe transaction (setup batches, root updates from `compose_root`, migrations, owner changes, settings) is built by `src/owner_tx.rs`: ordered call list → fork simulation **as the Safe** in write builds (makinaX's `SafeForkSession`) → Tx Builder JSON, a per-call summary and a simulation verdict. A batch whose simulation reverts is refused, never delivered. Values are never invented: `generate_onboarding_batch` omits anything with no config or package source and says so.

Delivery has three routes, chosen per chain:

| Route | Tools | What happens |
| --- | --- | --- |
| Safe app queue | `present_proposer_registration`, `submit_proposer_signature`, `use_safe_service_for_setup`, `propose_reviewed_batch` | An owner approves Orbit's propose-only key as a proposer; Orbit then submits the reviewed batch by its `safe_tx_hash` to Safe's transaction service. Owners approve in the Safe app. Orbit never picks another nonce and checks by hash rather than re-sending when the service's answer is unknown. |
| Owner export | `use_owner_export_for_setup`, the batch JSON from the generating tool | The owner imports the Tx Builder JSON in the Safe app. `export_allowed` on `propose_reviewed_batch` says when the file may be used instead. |
| Headless signing | `present_batch_for_signing`, `submit_batch_signature` | For an owner with no browser: Orbit shows the decoded calls and the exact SafeTx digest; owners sign it; at threshold the operator broadcasts `execTransaction` with the owners' signatures. The operator's own signature never counts toward the threshold. |

After a root update executes, `finalize_root_update` verifies the transaction, the on-chain root and the saved preimage, then activates that rootfile locally.

## How refusals are shaped

Internally a refusal is a variant of `Error` in `src/error.rs` (a `thiserror` enum). Many variants carry their remedy as fields, for example:

```rust
PolicyDenied { rule: String, explanation: String, remediation: Option<String> }

SetupIncomplete {
    machine: String,
    summary: String,
    instructions: String, // rendered fix steps
    owners: String,       // who owns each gap: safe_owner, makina, curator, provider
    checks_json: String,  // serialized setup checks
}

SimFailed { code: String, explanation: String, remediation: Option<String>, details: Option<serde_json::Value> }
```

`map_exec_error_payload` in `src/tools/write_tools.rs` converts an `Error` into an MCP error. The message is the error's text with credentials scrubbed (`redact::scrub`). The `data` payload is structured, always with a stable `code`, and where it applies `retry`, `next`, `use_instead`, `rule`, `remediation`:

| `code` | Extra fields |
| --- | --- |
| `simulation_required`, `simulation_stale` | none |
| `mainnet_mandate_required`, `mandate_required` | `use_instead: { tool: "propose_global_mandate" }` |
| `execution_paused`, `mainnet_dev_signer` | none |
| `policy_denied` | `rule`, `remediation` |
| `connection_behind`, `block_already_old` | `retry: true`, `rule`, `remediation` |
| `sim_failed` | `onchain_error_code`, `remediation`, `details`, and `refusal` when the failed step was explained |
| `setup_incomplete` | `machine`, `summary`, `instructions`, `gap_owners`, `owner_actionable`, `claims_about_execution`, `checks` |
| `network_paused` | `retry`, `next`, `use_instead: { tool: "recheck_network_pause" }`, `failed_read` |
| `quote_not_found`, `quote_stale` | none |
| `swapper_not_configured` | `adapter`, `machine`, `router_registration`, `quoted_router`, `module`, `remedy`, and `swapper_id`, `config_snippet`, `set_targets_calldata` when known |
| `review_expired` | `pending_id`, `retry: false`, `next` |
| `unknown_action`, `unknown_param`, `unknown_machine`, `invalid_params`, `package_not_installed` | the offending names |

Refusals of the caller's own input are JSON-RPC `-32602` (invalid params). Errors with no payload stay `-32603` with `server_side_data()`, for example `rpc_error`, or `broadcast_unknown` with `retry: false` and a `next` that forbids re-sending under a new key.

A step refused by the contract it called is explained by `src/refusals.rs` as a `Refusal { code, status_for_the_user, next }`: `status_for_the_user` is relayed to the owner as it stands, `next` is the agent's instruction and is never relayed. A custom error is named only when the governing curator-signed package declares it (`src/step_reason/`); Orbit keeps no list of protocol errors.

When adding a refusal, add the variant with its remedy as fields, map it in `map_exec_error_payload` with a stable `code`, and keep the message and payload saying the same thing; the guards in [Guards and wording](https://docs.orbit.dialectic.com/0.1.9/contributing/guards-and-wording/) check refusal text.
