Skip to main content

degenbot_cli/
argv.rs

1//! The clap v4 argv tree and the argv -> [`Command`] mapping (ADR-051 D2).
2//!
3//! This is the ONE place argv is spelled. The mapping below translates clap
4//! matches into the constructor-parsed values of `degenbot-cli-core` and never
5//! re-encodes semantics: every arm, flag, prompt and exit code lives there.
6//!
7//! # Where clap's shape differs from the retired click tree
8//!
9//! - **`exchange` (ADR-051 D5, 34 click verbs -> one data-driven command).**
10//!   Python declared one verb per `(chain, DEX)` pair (`base_aerodrome_v2`,
11//!   `ethereum_uniswap_v3`, …). cli-core models that as
12//!   `exchange activate|deactivate --chain <slug|id> --name <dex>`, resolving
13//!   the pair against [`RETIRED_EXCHANGES`](degenbot_cli_core::RETIRED_EXCHANGES).
14//! - **`aave activate|deactivate`.** Python spelled the market as a verb
15//!   (`aave activate ethereum_aave_v3`); cli-core takes `chain_id` and resolves
16//!   the deployment from [`AAVE_DEPLOYMENTS`](degenbot_cli_core::AAVE_DEPLOYMENTS),
17//!   so the tree is `aave activate [--chain-id <id>]` with Python's Ethereum
18//!   default (1) when no chain layer supplied a value.
19//! - **`aave position show <ADDRESS>`.** The click shape is kept, except that
20//!   its chain selector IS the global `--chain-id` (ADR-051 D8) rather than a
21//!   second, position-local spelling of the same thing; cli-core's arm takes
22//!   the resolved session chain id.
23//! - **`--socket`.** cli-core resolves the operator socket through the cascade
24//!   `--socket` > `DEGENBOT_OPERATOR_SOCKET` > `~/.config/degenbot/operator.sock`
25//!   ([`resolve_socket`](degenbot_cli_core::resolve_socket)); click declared
26//!   `--socket` required. The flag is therefore optional here - cli-core owns
27//!   the cascade.
28//! - **`database reset`.** Python marks it `hidden=True`. The command is
29//!   present and visible here (cli-core carries the arm; hiding it would make
30//!   the Rust tree the only place the arm is unreachable).
31//! - **Flag help text** is the Python help text, so the two surfaces read the
32//!   same. The per-flag click `envvar=` fallbacks (`DEGENBOT_CHUNK_SIZE`, …) are
33//!   NOT re-added: cli-core models these inputs as argv only, and the only env
34//!   vocabulary the console owns is the driver-domain set of ADR-051 D8.
35
36use std::io::Write as _;
37
38use clap::{ArgAction, Args, CommandFactory as _, Parser, Subcommand, ValueEnum};
39use degenbot_cli_core::{
40    AaveCommand, CliContext, CliError, Command, ConfigCommand, DatabaseCommand, ExchangeCommand,
41    FleetCommand, PathCommand, PathDirection, PoolCommand, PoolFamily, PosturePatchEntry,
42    StrategyCommand, StrategyFacet, DEFAULT_CHUNK_SIZE, DEFAULT_MAX_BLOCK_RANGE, DEFAULT_TO_BLOCK,
43    DEFAULT_VERIFY_ALL_INTERVAL,
44};
45use degenbot_config::{EnvVars, NodeTransport, ProcessEnv, DEFAULT_CHAIN_ID_ENV};
46
47use crate::VERSION_LINE;
48
49/// The degenbot console.
50#[derive(Debug, Parser)]
51#[command(
52    name = "degenbot",
53    about = "Perform cli.",
54    version = VERSION_LINE,
55    arg_required_else_help = true,
56    disable_help_subcommand = true
57)]
58pub struct Cli {
59    /// The command to run.
60    #[command(subcommand)]
61    pub command: Option<Commands>,
62
63    /// Path to the SQLite database (`--database` > `DEGENBOT_DB_PATH` >
64    /// `<state_home>/degenbot/db/degenbot.db`).
65    #[arg(long, global = true, value_name = "PATH")]
66    pub database: Option<String>,
67
68    /// Session chain id (`--chain-id` > `DEGENBOT_DEFAULT_CHAIN_ID`).
69    #[arg(long, global = true, value_name = "CHAIN_ID")]
70    pub chain_id: Option<String>,
71
72    /// Node RPC endpoint; the value's own scheme picks its transport
73    /// (`wss://` > ws, `http://` > http, `ipc://` or a socket path > ipc).
74    /// Repeat it to set one endpoint per transport. The explicit layer
75    /// outranks the per-chain endpoint env families and the `nodes.*` file
76    /// tables.
77    #[arg(long = "node", global = true, value_name = "URI", value_parser = parse_node)]
78    pub node: Vec<NodeArg>,
79
80    /// Typed config file the `strategy` verbs read and write (`--config` >
81    /// `DEGENBOT_CONFIG` > the XDG config home).
82    #[arg(long, global = true, value_name = "PATH")]
83    pub config: Option<String>,
84}
85
86/// The command groups.
87#[derive(Debug, Subcommand)]
88pub enum Commands {
89    /// Database commands.
90    Database {
91        /// The database command.
92        #[command(subcommand)]
93        command: DatabaseSub,
94    },
95    /// Exchange commands.
96    Exchange {
97        /// The exchange command.
98        #[command(subcommand)]
99        command: ExchangeSub,
100    },
101    /// Pool commands.
102    Pool {
103        /// The pool command.
104        #[command(subcommand)]
105        command: PoolSub,
106    },
107    /// Aave commands.
108    Aave {
109        /// The aave command.
110        #[command(subcommand)]
111        command: AaveSub,
112    },
113    /// Steer the live worker fleet over the operator command channel.
114    Fleet {
115        /// The fleet command.
116        #[command(subcommand)]
117        command: FleetSub,
118    },
119    /// Steer a live bot over the operator command channel.
120    Path {
121        /// The path command.
122        #[command(subcommand)]
123        command: PathSub,
124    },
125    /// Inspect the operator config file and the values it resolves to.
126    Config {
127        /// The config command.
128        #[command(subcommand)]
129        command: ConfigSub,
130    },
131    /// Inspect the typed strategy facets (ADR-055).
132    Strategy {
133        /// The strategy command.
134        #[command(subcommand)]
135        command: StrategySub,
136    },
137}
138
139/// The `database` command group.
140#[derive(Debug, Subcommand)]
141pub enum DatabaseSub {
142    /// Back up the database.
143    Backup,
144    /// Remove and recreate the database.
145    Reset {
146        /// Skip confirmation prompt.
147        #[arg(long)]
148        force: bool,
149    },
150    /// Upgrade the database to the latest schema (RETIRED: the database
151    /// upgrades itself at open; `database heal` is the explicit repair).
152    Upgrade {
153        /// Skip confirmation prompt.
154        #[arg(long)]
155        force: bool,
156    },
157    /// Compact the database.
158    Compact,
159    /// Flip an Alembic-stamped DB into Rust schema ownership (ADR-010).
160    Cutover {
161        /// Report the schema state + what cutover would do; write nothing.
162        #[arg(long)]
163        dry_run: bool,
164        /// Skip the confirmation prompt and run the cutover.
165        #[arg(long)]
166        force: bool,
167    },
168    /// Rebuild an Alembic-stamped DB into Rust ownership via dump-and-restore
169    /// (ADR-011).
170    Heal {
171        /// Report the schema state + what heal would do; write nothing.
172        #[arg(long)]
173        dry_run: bool,
174        /// Skip the confirmation prompt and run the heal.
175        #[arg(long)]
176        force: bool,
177    },
178    /// Inspect the database schema state (read-only; never writes).
179    Inspect,
180}
181
182/// The `exchange` command group.
183#[derive(Debug, Subcommand)]
184pub enum ExchangeSub {
185    /// Activate the exchange. Liquidity pools for all activated exchanges are
186    /// included when running "pool update".
187    Activate {
188        /// The chain selector: a chain slug (`base`, `ethereum`) or a numeric
189        /// chain id.
190        #[arg(long, value_name = "CHAIN")]
191        chain: String,
192        /// The DEX name slug stored in the database (`aerodrome_v2`,
193        /// `uniswap_v3`, …).
194        #[arg(long, value_name = "NAME")]
195        name: String,
196    },
197    /// Deactivate the exchange. Liquidity pools for all deactivated exchanges
198    /// are not included when running "pool update".
199    Deactivate {
200        /// The chain selector: a chain slug (`base`, `ethereum`) or a numeric
201        /// chain id.
202        #[arg(long, value_name = "CHAIN")]
203        chain: String,
204        /// The DEX name slug stored in the database.
205        #[arg(long, value_name = "NAME")]
206        name: String,
207    },
208    /// List the supported exchanges and their activation state.
209    List {
210        /// Restrict the list to one chain (a chain slug or numeric id).
211        #[arg(long, value_name = "CHAIN")]
212        chain: Option<String>,
213    },
214}
215
216/// The `pool` command group.
217#[derive(Debug, Subcommand)]
218pub enum PoolSub {
219    /// Update liquidity pool information for activated exchanges.
220    Update {
221        /// The maximum number of blocks to process before committing changes to
222        /// the database.
223        #[arg(long = "chunk", value_name = "BLOCKS", default_value_t = DEFAULT_CHUNK_SIZE)]
224        chunk_size: u64,
225        /// The maximum number of blocks a single `eth_getLogs` request may
226        /// span, independent of `--chunk`. Lower it for RPC providers that
227        /// cap the `eth_getLogs` block range (e.g. dRPC's free plan).
228        #[arg(long = "max-block-range", value_name = "BLOCKS", default_value_t = DEFAULT_MAX_BLOCK_RANGE)]
229        max_block_range: u64,
230        /// The last block in the update range. Must be a valid block
231        /// identifier: 'earliest', 'finalized', 'safe', 'latest', 'pending'.
232        /// An identifier can be given with an optional offset, e.g. 'latest:-64'
233        /// stops 64 blocks before the chain tip, 'safe:128' stops 128 blocks
234        /// after the last 'safe' block.
235        #[arg(long = "to-block", value_name = "BLOCK", default_value = DEFAULT_TO_BLOCK)]
236        to_block: String,
237        /// The pre-commit verification gates.
238        #[command(flatten)]
239        verify: VerifyFlags,
240        /// Block interval for the `--verify-all` full-verification gate. A chunk
241        /// that crosses or lands-on a multiple of this interval triggers a
242        /// pre-commit market-wide verify. Ignored unless `--verify-all` is set.
243        #[arg(
244            long = "verify-all-interval",
245            value_name = "BLOCKS",
246            default_value_t = DEFAULT_VERIFY_ALL_INTERVAL
247        )]
248        verify_all_interval: u64,
249    },
250    /// Verify a pool's committed liquidity map against on-chain truth.
251    Verify {
252        /// The HTTP RPC endpoint to read on-chain truth from.
253        #[arg(long = "rpc-url", value_name = "URL", required = true)]
254        rpc_url: String,
255        /// The chain id the pool lives on. The Rust field is named
256        /// `pool_chain_id` so its clap arg id cannot collide with the global
257        /// `--chain-id` driver flag; the argv spelling stays `--chain`.
258        #[arg(long = "chain", value_name = "CHAIN_ID", required = true)]
259        pool_chain_id: i64,
260        /// The block number to read on-chain truth at.
261        #[arg(long = "block", value_name = "BLOCK", required = true)]
262        block_number: u64,
263        #[arg(
264            long = "pool",
265            value_name = "POOL",
266            required = true,
267            help = "The pool to verify. V3: the pool contract address. V4: the PoolId (pool_hash, bytes32 hex 0x…)."
268        )]
269        pool: String,
270        #[arg(
271            long = "family",
272            value_enum,
273            required = true,
274            help = "The pool family (selects ticks()/tickBitmap() vs PoolManager extsload)."
275        )]
276        family: FamilyArg,
277        #[arg(
278            long = "pool-manager",
279            value_name = "ADDRESS",
280            help = "(V4 only) The deployed V4 PoolManager singleton address (the V4 exchange's factory). Required for --family v4."
281        )]
282        pool_manager: Option<String>,
283    },
284}
285
286/// The `--verify-chunk` / `--verify-all` gate pairs shared by both updaters.
287#[derive(Debug, Clone, Args)]
288#[expect(
289    clippy::struct_excessive_bools,
290    reason = "the two on/off gate pairs are argv vocabulary, not state: each pair is two mutually-overriding flags"
291)]
292pub struct VerifyFlags {
293    /// Run the pre-commit per-chunk on-chain-truth gate before each chunk's
294    /// persist commits. A divergence rolls back the chunk + does NOT advance
295    /// `last_update_block`.
296    #[arg(long = "verify-chunk", action = ArgAction::SetTrue, overrides_with = "no_verify_chunk")]
297    pub verify_chunk: bool,
298    /// Disable the pre-commit per-chunk on-chain-truth gate.
299    #[arg(long = "no-verify-chunk", action = ArgAction::SetTrue, overrides_with = "verify_chunk")]
300    pub no_verify_chunk: bool,
301    /// Run a pre-commit FULL verification at the block boundary set by
302    /// `--verify-all-interval` AND when the run completes its last block. Off
303    /// by default (operator opt-in).
304    #[arg(long = "verify-all", action = ArgAction::SetTrue, overrides_with = "no_verify_all")]
305    pub verify_all: bool,
306    /// Disable the market-wide `--verify-all` gate.
307    #[arg(long = "no-verify-all", action = ArgAction::SetTrue, overrides_with = "verify_all")]
308    pub no_verify_all: bool,
309}
310
311impl VerifyFlags {
312    /// The per-chunk gate value: default ON, `--no-verify-chunk` turns it off.
313    #[must_use]
314    pub const fn chunk_gate(&self) -> bool {
315        self.verify_chunk || !self.no_verify_chunk
316    }
317
318    /// The market-wide gate value: default OFF, `--verify-all` turns it on.
319    #[must_use]
320    pub const fn all_gate(&self) -> bool {
321        self.verify_all && !self.no_verify_all
322    }
323}
324
325/// The pool family selector.
326#[derive(Debug, Clone, Copy, ValueEnum)]
327pub enum FamilyArg {
328    /// V3 (`ticks()`/`tickBitmap()`).
329    V3,
330    /// V4 (`PoolManager` `extsload`).
331    V4,
332}
333
334/// The `aave` command group.
335#[derive(Debug, Subcommand)]
336pub enum AaveSub {
337    /// Activate an Aave market. Positions for activated markets are included
338    /// when running `degenbot aave position update`.
339    Activate,
340    /// Deactivate an Aave market. Positions for deactivated markets are not
341    /// included when running `degenbot aave position update`.
342    Deactivate {
343        /// Market name to flip (default: Aave Ethereum Market).
344        #[arg(
345            long = "name",
346            value_name = "MARKET",
347            default_value = "Aave Ethereum Market"
348        )]
349        market_name: String,
350    },
351    /// Print one market's completed-market record: per-table row counts +
352    /// digests over the market tables, as the manifest JSON (redirect
353    /// stdout to pin it).
354    Digest {
355        /// Market name to digest (default: the chain's only registered
356        /// market).
357        #[arg(long = "market-name", value_name = "MARKET")]
358        market_name: Option<String>,
359        /// A previous completed-market record whose `market.drive` block is
360        /// carried into the output verbatim (the drive facts are the
361        /// drive's own bookkeeping, not DB state).
362        #[arg(long = "drive-manifest", value_name = "PATH")]
363        drive_manifest: Option<std::path::PathBuf>,
364    },
365    /// Update positions for active Aave markets.
366    Update {
367        /// The maximum number of blocks to process before committing changes to
368        /// the database.
369        #[arg(long = "chunk", value_name = "BLOCKS", default_value_t = DEFAULT_CHUNK_SIZE)]
370        chunk_size: u64,
371        /// The maximum number of blocks a single `eth_getLogs` request may
372        /// span, independent of `--chunk`. Lower it for RPC providers that
373        /// cap the `eth_getLogs` block range (e.g. dRPC's free plan).
374        #[arg(long = "max-block-range", value_name = "BLOCKS", default_value_t = DEFAULT_MAX_BLOCK_RANGE)]
375        max_block_range: u64,
376        /// The last block in the update range. Must be a valid block
377        /// identifier: 'earliest', 'finalized', 'safe', 'latest', 'pending'.
378        /// An identifier can be given with an optional offset, e.g. 'latest:-64'
379        /// stops 64 blocks before the chain tip, 'safe:128' stops 128 blocks
380        /// after the last 'safe' block.
381        #[arg(long = "to-block", value_name = "BLOCK", default_value = DEFAULT_TO_BLOCK)]
382        to_block: String,
383        /// The pre-commit verification gates.
384        #[command(flatten)]
385        verify: VerifyFlags,
386        /// Block interval for the `--verify-all` full-verification gate. A chunk
387        /// that crosses or lands-on a multiple of this interval triggers a
388        /// pre-commit market-wide verify. Ignored unless `--verify-all` is set.
389        #[arg(
390            long = "verify-all-interval",
391            value_name = "BLOCKS",
392            default_value_t = DEFAULT_VERIFY_ALL_INTERVAL
393        )]
394        verify_all_interval: u64,
395        /// Stop processing after the first chunk.
396        #[arg(long = "one-chunk", action = ArgAction::SetTrue)]
397        stop_after_one_chunk: bool,
398        /// Preview changes without committing to the database.
399        #[arg(long = "dry-run", action = ArgAction::SetTrue)]
400        dry_run: bool,
401        /// Create a database backup after the completion verification runs
402        /// (once per market, at the end of the run).
403        #[arg(long = "backup", action = ArgAction::SetTrue, overrides_with = "no_backup")]
404        backup: bool,
405        /// Disable the completion backup.
406        #[arg(long = "no-backup", action = ArgAction::SetTrue, overrides_with = "backup")]
407        no_backup: bool,
408    },
409    /// Reset one market: purge its populated state, then re-run the cold-boot
410    /// update a fresh empty database takes for it.
411    Reset {
412        /// Market name to reset (default: Aave Ethereum Market).
413        #[arg(
414            long = "name",
415            value_name = "MARKET",
416            default_value = "Aave Ethereum Market"
417        )]
418        market_name: String,
419        /// Preview the purge's per-relation counts without deleting anything.
420        #[arg(long = "dry-run", action = ArgAction::SetTrue)]
421        dry_run: bool,
422    },
423    /// Position commands.
424    Position {
425        /// The position command.
426        #[command(subcommand)]
427        command: AavePositionSub,
428    },
429}
430
431/// The `aave position` command group.
432#[derive(Debug, Subcommand)]
433pub enum AavePositionSub {
434    /// Display current Aave positions for a user.
435    Show {
436        /// The user address.
437        #[arg(value_name = "ADDRESS")]
438        address: String,
439        /// Market name to query (default: Aave Ethereum Market).
440        #[arg(
441            long = "market",
442            value_name = "MARKET",
443            default_value = "Aave Ethereum Market"
444        )]
445        market: String,
446    },
447}
448
449/// The `fleet` command group.
450#[derive(Debug, Subcommand)]
451pub enum FleetSub {
452    /// Inspect or re-tune the live cordon posture thresholds.
453    Posture {
454        /// The posture command.
455        #[command(subcommand)]
456        command: FleetPostureSub,
457    },
458}
459
460/// The `fleet posture` command group.
461#[derive(Debug, Subcommand)]
462pub enum FleetPostureSub {
463    /// Show the LIVE cordon posture: thresholds + Nominal|Cordoned.
464    Show {
465        #[arg(
466            long,
467            value_name = "PATH",
468            help = "Unix domain socket path of the running bot's OperatorServer."
469        )]
470        socket: Option<String>,
471    },
472    /// Re-tune the LIVE cordon thresholds (a partial patch).
473    Set {
474        #[arg(
475            long,
476            value_name = "PATH",
477            help = "Unix domain socket path of the running bot's OperatorServer."
478        )]
479        socket: Option<String>,
480        /// Throttle events within the enter window that cordon the fleet.
481        #[arg(long = "cordon-enter-events", value_name = "COUNT")]
482        cordon_enter_events: Option<u64>,
483        /// Throttled-time duty percent over the duty window that cordons the
484        /// fleet.
485        #[arg(long = "cordon-duty-percent", value_name = "PERCENT")]
486        cordon_duty_percent: Option<f64>,
487        /// Rolling window (ms) for the throttle-event burst enter trigger.
488        #[arg(long = "cordon-enter-window-ms", value_name = "MS")]
489        cordon_enter_window_ms: Option<u64>,
490        /// Trailing window (ms) over which throttled-time duty is evaluated.
491        #[arg(long = "cordon-duty-window-ms", value_name = "MS")]
492        cordon_duty_window_ms: Option<u64>,
493        /// Clean-window hysteresis (ms) required before cordon exits.
494        #[arg(long = "cordon-exit-clean-ms", value_name = "MS")]
495        cordon_exit_clean_ms: Option<u64>,
496        #[arg(
497            long = "cordon-sim-intake-floor",
498            value_name = "COUNT|null",
499            help = "SimDriver new-lease cap while cordoned. The literal null restores half the slot cap."
500        )]
501        cordon_sim_intake_floor: Option<String>,
502    },
503}
504
505/// The `path` command group.
506#[derive(Debug, Subcommand)]
507pub enum PathSub {
508    /// Add ONE specific path to the live bot mid-run.
509    Add {
510        #[arg(
511            long,
512            value_name = "PATH",
513            help = "Unix domain socket path of the running bot's OperatorServer."
514        )]
515        socket: Option<String>,
516        /// A path hop as FAMILY:ADDRESS, or V4:ADDRESS:HASH (pool id). Repeat
517        /// for each hop, in path order.
518        #[arg(long = "hop", value_name = "HOP", required = true)]
519        hops: Vec<String>,
520        /// Applied to every hop when set: 'zfo' (zero-for-one, True for each
521        /// hop) or 'ozf' (one-for-zero, False for each hop). Omit to let the bot
522        /// auto-resolve directions.
523        #[arg(long = "direction", value_enum)]
524        direction: Option<DirectionArg>,
525    },
526    /// Trigger a bounded on-demand discovery sweep on the live bot.
527    Discover {
528        #[arg(
529            long,
530            value_name = "PATH",
531            help = "Unix domain socket path of the running bot's OperatorServer."
532        )]
533        socket: Option<String>,
534        /// Maximum number of paths to process in this discovery sweep.
535        #[arg(long = "bound", value_name = "COUNT")]
536        bound: Option<u64>,
537    },
538}
539
540/// The `--direction` choice on `path add`.
541#[derive(Debug, Clone, Copy, ValueEnum)]
542pub enum DirectionArg {
543    /// Zero-for-one.
544    Zfo,
545    /// One-for-zero.
546    Ozf,
547}
548
549/// The `strategy` command group (ADR-055 facets): the strategy activation
550/// and parameter surface over the typed config.
551#[derive(Debug, Subcommand)]
552pub enum StrategySub {
553    /// List the declared strategy facets.
554    List,
555    /// Show one strategy facet: declared keys, activation, and the settled
556    /// endpoint posture.
557    Show {
558        /// The facet to show.
559        #[arg(value_enum)]
560        facet: FacetArg,
561    },
562    /// Activate a strategy and settle its endpoint posture. Exactly one of
563    /// `--endpoints` / `--endpoints-default` unless the facet already carries
564    /// a settled choice.
565    Activate {
566        /// The facet to activate.
567        #[arg(value_enum)]
568        facet: FacetArg,
569        /// The explicit endpoint set (comma-separated URLs).
570        #[arg(
571            long = "endpoints",
572            value_name = "URLS",
573            conflicts_with = "endpoints_default"
574        )]
575        endpoints: Option<String>,
576        /// Adopt the documented default endpoint set.
577        #[arg(long = "endpoints-default")]
578        endpoints_default: bool,
579    },
580    /// Deactivate a strategy (its recorded endpoint choice is kept).
581    Deactivate {
582        /// The facet to deactivate.
583        #[arg(value_enum)]
584        facet: FacetArg,
585    },
586    /// Set one declared facet key.
587    Set {
588        /// The facet to mutate.
589        #[arg(value_enum)]
590        facet: FacetArg,
591        /// The config key name.
592        key: String,
593        /// The raw value.
594        value: String,
595    },
596    /// Drop one key's override so the declared default applies again
597    /// ("set the default if you have no preference").
598    Default {
599        /// The facet to mutate.
600        #[arg(value_enum)]
601        facet: FacetArg,
602        /// The config key name.
603        key: String,
604    },
605    /// The `default` verb's traditional spelling.
606    Remove {
607        /// The facet to mutate.
608        #[arg(value_enum)]
609        facet: FacetArg,
610        /// The config key name.
611        key: String,
612    },
613}
614
615/// The `config` command group: the read-only view of the operator file.
616#[derive(Debug, Subcommand)]
617pub enum ConfigSub {
618    /// Show the driver-domain values: the file's own with no flag, or every
619    /// layer's winning value (with its source) under `--resolved`.
620    Show {
621        /// Render each value with the layer that supplied it.
622        #[arg(long)]
623        resolved: bool,
624    },
625    /// Print the config file the mutating arms read and write.
626    Path,
627    /// Print one resolved driver-domain value and the layer that supplied it.
628    Get {
629        /// The dotted key or `table.entry` path (e.g. `nodes.http.1`).
630        key: String,
631    },
632    /// Write one declared key or `str_map` entry through the config writer.
633    Set {
634        /// The dotted key or `table.entry` path.
635        key: String,
636        /// The raw value.
637        value: String,
638        /// Skip the confirmation prompt.
639        #[arg(long)]
640        force: bool,
641    },
642    /// Remove one key or `str_map` entry override so the default applies.
643    Unset {
644        /// The dotted key or `table.entry` path.
645        key: String,
646        /// Skip the confirmation prompt.
647        #[arg(long)]
648        force: bool,
649    },
650}
651
652/// The strategy facet selector.
653#[derive(Debug, Clone, Copy, ValueEnum)]
654pub enum FacetArg {
655    /// The settled-block strategy.
656    Settlement,
657    /// The MEVBlocker-ecosystem pending-transaction strategy.
658    #[value(name = "mevblocker_backrun")]
659    MevblockerBackrun,
660    /// The public-mempool pending-transaction strategy.
661    #[value(name = "txpool_backrun")]
662    TxpoolBackrun,
663}
664
665/// One `--node` occurrence: the endpoint, plus the transport its own value
666/// classified as (ADR-062 D6). clap carries the classification so a value no
667/// transport can serve is a usage error at parse time, not a later refusal.
668#[derive(Debug, Clone, PartialEq, Eq)]
669pub struct NodeArg {
670    /// The endpoint verbatim.
671    pub uri: String,
672    /// The transport the value serves.
673    pub transport: NodeTransport,
674}
675
676/// Classify one `--node` value into its transport.
677///
678/// # Errors
679///
680/// A usage message naming the three accepted forms, which clap renders as an
681/// invalid-value error (exit 2).
682fn parse_node(raw: &str) -> Result<NodeArg, String> {
683    let Some(transport) = NodeTransport::classify(raw) else {
684        let forms: Vec<String> = NodeTransport::ALL
685            .iter()
686            .map(|transport| format!("{} — {}", transport.key_path(), transport.expected()))
687            .collect();
688        return Err(format!(
689            "{raw:?} names no node transport; accepted forms: {}",
690            forms.join("; ")
691        ));
692    };
693    Ok(NodeArg {
694        uri: raw.to_string(),
695        transport,
696    })
697}
698
699/// The [`CliContext`] the argv overrides describe (ADR-051 D8).
700#[must_use]
701pub fn context<'a>(cli: &Cli, env: &'a dyn EnvVars) -> CliContext<'a> {
702    let mut ctx = CliContext::new(env);
703    if let Some(database) = &cli.database {
704        ctx = ctx.with_database(database.clone());
705    }
706    if let Some(chain_id) = &cli.chain_id {
707        ctx = ctx.with_chain_id(chain_id.clone());
708    }
709    for node in &cli.node {
710        ctx = ctx.with_node(node.uri.clone(), node.transport);
711    }
712    if let Some(config) = &cli.config {
713        ctx = ctx.with_config(config.clone());
714    }
715    ctx
716}
717
718/// Map argv into a [`Command`], reading the driver-domain env through the real
719/// process environment.
720///
721/// # Errors
722///
723/// [`CliError`] when an arm needs a driver-domain value no layer supplied, or a
724/// malformed `--chain-id` / `cordon_sim_intake_floor`.
725pub fn resolve(cli: &Cli) -> Result<Command, CliError> {
726    resolve_with_env(cli, &ProcessEnv)
727}
728
729/// Map argv into a [`Command`] over an injectable env seam (tests never mutate
730/// the process environment).
731///
732/// # Errors
733///
734/// As [`resolve`].
735///
736/// # Panics
737///
738/// Never: a missing subcommand is a typed [`CliError::InvalidArgument`].
739pub fn resolve_with_env(cli: &Cli, env: &dyn EnvVars) -> Result<Command, CliError> {
740    let ctx = context(cli, env);
741    let Some(command) = &cli.command else {
742        return Err(CliError::InvalidArgument(
743            "a subcommand is required".to_string(),
744        ));
745    };
746    match command {
747        Commands::Database { command } => Ok(Command::Database(database(command))),
748        Commands::Exchange { command } => Ok(Command::Exchange(exchange(command))),
749        Commands::Pool { command } => Ok(Command::Pool(pool(command))),
750        Commands::Aave { command } => Ok(Command::Aave(aave(command, cli, &ctx)?)),
751        Commands::Fleet { command } => Ok(Command::Fleet(fleet(command)?)),
752        Commands::Path { command } => Ok(Command::Path(path(command))),
753        Commands::Strategy { command } => Ok(Command::Strategy(strategy(command))),
754        Commands::Config { command } => Ok(Command::Config(config(command))),
755    }
756}
757
758/// Print clap's own usage block for the no-subcommand-but-args case.
759pub fn write_missing_subcommand_error() {
760    let mut command = Cli::command();
761    let usage = command.render_usage().to_string();
762    let _ = writeln!(
763        std::io::stderr().lock(),
764        "error: a subcommand is required\n\n{usage}"
765    );
766}
767
768fn database(command: &DatabaseSub) -> DatabaseCommand {
769    match command {
770        DatabaseSub::Backup => DatabaseCommand::Backup,
771        DatabaseSub::Reset { force } => DatabaseCommand::Reset { force: *force },
772        DatabaseSub::Upgrade { force } => DatabaseCommand::Upgrade { force: *force },
773        DatabaseSub::Compact => DatabaseCommand::Compact,
774        DatabaseSub::Cutover { dry_run, force } => DatabaseCommand::Cutover {
775            dry_run: *dry_run,
776            force: *force,
777        },
778        DatabaseSub::Heal { dry_run, force } => DatabaseCommand::Heal {
779            dry_run: *dry_run,
780            force: *force,
781        },
782        DatabaseSub::Inspect => DatabaseCommand::Inspect,
783    }
784}
785
786fn exchange(command: &ExchangeSub) -> ExchangeCommand {
787    match command {
788        ExchangeSub::Activate { chain, name } => ExchangeCommand::Activate {
789            chain: chain.clone(),
790            name: name.clone(),
791        },
792        ExchangeSub::Deactivate { chain, name } => ExchangeCommand::Deactivate {
793            chain: chain.clone(),
794            name: name.clone(),
795        },
796        ExchangeSub::List { chain } => ExchangeCommand::List {
797            chain: chain.clone(),
798        },
799    }
800}
801
802fn pool(command: &PoolSub) -> PoolCommand {
803    match command {
804        PoolSub::Update {
805            chunk_size,
806            max_block_range,
807            to_block,
808            verify,
809            verify_all_interval,
810        } => PoolCommand::Update {
811            chunk_size: *chunk_size,
812            max_block_range: *max_block_range,
813            to_block: to_block.clone(),
814            verify_chunk: verify.chunk_gate(),
815            verify_all: verify.all_gate(),
816            verify_all_interval: *verify_all_interval,
817        },
818        PoolSub::Verify {
819            rpc_url,
820            pool_chain_id,
821            block_number,
822            pool,
823            family,
824            pool_manager,
825        } => PoolCommand::Verify {
826            rpc_url: rpc_url.clone(),
827            chain_id: *pool_chain_id,
828            block_number: *block_number,
829            pool: pool.clone(),
830            family: match family {
831                FamilyArg::V3 => PoolFamily::V3,
832                FamilyArg::V4 => PoolFamily::V4,
833            },
834            pool_manager: pool_manager.clone(),
835        },
836    }
837}
838
839fn aave(command: &AaveSub, cli: &Cli, ctx: &CliContext<'_>) -> Result<AaveCommand, CliError> {
840    match command {
841        AaveSub::Activate => Ok(AaveCommand::Activate {
842            chain_id: chain_or_default(cli, ctx, 1)?,
843        }),
844        AaveSub::Deactivate { market_name } => Ok(AaveCommand::Deactivate {
845            chain_id: chain_or_default(cli, ctx, 1)?,
846            market_name: market_name.clone(),
847        }),
848        AaveSub::Digest {
849            market_name,
850            drive_manifest,
851        } => Ok(AaveCommand::Digest {
852            chain_id: chain_or_default(cli, ctx, 1)?,
853            market_name: market_name.clone(),
854            drive_manifest: drive_manifest.clone(),
855        }),
856        AaveSub::Update {
857            chunk_size,
858            max_block_range,
859            to_block,
860            verify,
861            verify_all_interval,
862            stop_after_one_chunk,
863            dry_run,
864            backup,
865            no_backup,
866        } => Ok(AaveCommand::Update {
867            chunk_size: *chunk_size,
868            max_block_range: *max_block_range,
869            to_block: to_block.clone(),
870            verify_chunk: verify.chunk_gate(),
871            verify_all: verify.all_gate(),
872            verify_all_interval: *verify_all_interval,
873            stop_after_one_chunk: *stop_after_one_chunk,
874            dry_run: *dry_run,
875            enable_backup: *backup && !*no_backup,
876        }),
877        AaveSub::Reset {
878            market_name,
879            dry_run,
880        } => Ok(AaveCommand::Reset {
881            chain_id: chain_or_default(cli, ctx, 1)?,
882            market_name: Some(market_name.clone()),
883            dry_run: *dry_run,
884        }),
885        AaveSub::Position { command } => match command {
886            AavePositionSub::Show { address, market } => Ok(AaveCommand::PositionShow {
887                address: address.clone(),
888                market: market.clone(),
889                chain_id: chain_or_default(cli, ctx, 1)?,
890            }),
891        },
892    }
893}
894
895fn fleet(command: &FleetSub) -> Result<FleetCommand, CliError> {
896    match command {
897        FleetSub::Posture { command } => match command {
898            FleetPostureSub::Show { socket } => Ok(FleetCommand::PostureShow {
899                socket: socket.clone(),
900            }),
901            FleetPostureSub::Set {
902                socket,
903                cordon_enter_events,
904                cordon_duty_percent,
905                cordon_enter_window_ms,
906                cordon_duty_window_ms,
907                cordon_exit_clean_ms,
908                cordon_sim_intake_floor,
909            } => {
910                let mut patch = Vec::new();
911                if let Some(value) = cordon_enter_events {
912                    patch.push(PosturePatchEntry::int("cordon_enter_events", *value));
913                }
914                if let Some(value) = cordon_duty_percent {
915                    patch.push(PosturePatchEntry::float("cordon_duty_percent", *value));
916                }
917                if let Some(value) = cordon_enter_window_ms {
918                    patch.push(PosturePatchEntry::int("cordon_enter_window_ms", *value));
919                }
920                if let Some(value) = cordon_duty_window_ms {
921                    patch.push(PosturePatchEntry::int("cordon_duty_window_ms", *value));
922                }
923                if let Some(value) = cordon_exit_clean_ms {
924                    patch.push(PosturePatchEntry::int("cordon_exit_clean_ms", *value));
925                }
926                if let Some(value) = cordon_sim_intake_floor {
927                    patch.push(PosturePatchEntry::new(
928                        "cordon_sim_intake_floor",
929                        degenbot_cli_core::parse_sim_intake_floor(value)?,
930                    ));
931                }
932                Ok(FleetCommand::PostureSet {
933                    socket: socket.clone(),
934                    patch,
935                })
936            }
937        },
938    }
939}
940
941fn path(command: &PathSub) -> PathCommand {
942    match command {
943        PathSub::Add {
944            socket,
945            hops,
946            direction,
947        } => PathCommand::Add {
948            socket: socket.clone(),
949            hops: hops.clone(),
950            direction: direction.map(|direction| match direction {
951                DirectionArg::Zfo => PathDirection::Zfo,
952                DirectionArg::Ozf => PathDirection::Ozf,
953            }),
954        },
955        PathSub::Discover { socket, bound } => PathCommand::Discover {
956            socket: socket.clone(),
957            bound: *bound,
958        },
959    }
960}
961
962fn strategy(command: &StrategySub) -> StrategyCommand {
963    match command {
964        StrategySub::List => StrategyCommand::List,
965        StrategySub::Show { facet } => StrategyCommand::Show {
966            facet: facet_of(*facet),
967        },
968        StrategySub::Activate {
969            facet,
970            endpoints,
971            endpoints_default,
972        } => StrategyCommand::Activate {
973            facet: facet_of(*facet),
974            endpoints: endpoints.clone(),
975            endpoints_default: *endpoints_default,
976        },
977        StrategySub::Deactivate { facet } => StrategyCommand::Deactivate {
978            facet: facet_of(*facet),
979        },
980        StrategySub::Set { facet, key, value } => StrategyCommand::Set {
981            facet: facet_of(*facet),
982            key: key.clone(),
983            value: value.clone(),
984        },
985        StrategySub::Default { facet, key } => StrategyCommand::Default {
986            facet: facet_of(*facet),
987            key: key.clone(),
988        },
989        StrategySub::Remove { facet, key } => StrategyCommand::Remove {
990            facet: facet_of(*facet),
991            key: key.clone(),
992        },
993    }
994}
995
996fn config(command: &ConfigSub) -> ConfigCommand {
997    match command {
998        ConfigSub::Show { resolved } => ConfigCommand::Show {
999            resolved: *resolved,
1000        },
1001        ConfigSub::Path => ConfigCommand::Path,
1002        ConfigSub::Get { key } => ConfigCommand::Get { key: key.clone() },
1003        ConfigSub::Set { key, value, force } => ConfigCommand::Set {
1004            key: key.clone(),
1005            value: value.clone(),
1006            force: *force,
1007        },
1008        ConfigSub::Unset { key, force } => ConfigCommand::Unset {
1009            key: key.clone(),
1010            force: *force,
1011        },
1012    }
1013}
1014
1015fn facet_of(arg: FacetArg) -> StrategyFacet {
1016    match arg {
1017        FacetArg::Settlement => StrategyFacet::Settlement,
1018        FacetArg::MevblockerBackrun => StrategyFacet::MevblockerBackrun,
1019        FacetArg::TxpoolBackrun => StrategyFacet::TxpoolBackrun,
1020    }
1021}
1022
1023/// The session chain id for the aave arms, which carry Python's Ethereum
1024/// default when NO chain layer named a value. A layer that IS present and
1025/// malformed stays an error.
1026fn chain_or_default(cli: &Cli, ctx: &CliContext<'_>, default: u64) -> Result<u64, CliError> {
1027    let cli_layer = cli
1028        .chain_id
1029        .as_deref()
1030        .is_some_and(|value| !value.is_empty());
1031    let env_layer = ctx
1032        .env()
1033        .get(DEFAULT_CHAIN_ID_ENV)
1034        .is_some_and(|value| !value.is_empty());
1035    // The loaded config knows every layer, so the operator file's
1036    // `session.chain_id` counts exactly like the two argument/env layers.
1037    let file_layer = ctx.loaded_config()?.config.session.chain_id.is_some();
1038    if cli_layer || env_layer || file_layer {
1039        return Ok(ctx.chain_id()?.value);
1040    }
1041    Ok(default)
1042}