Skip to main content

degenbot_cli_core/
report.rs

1//! Typed command reports (ADR-051 D1: execution returns typed results; the
2//! facade renders them — Q1).
3
4use std::path::PathBuf;
5
6use alloy::primitives::U256;
7use degenbot_db::ops::HealReport;
8use degenbot_db::{
9    render_completed_market_manifest, AaveMarketPurgeCount, CompletedMarketManifest, SchemaState,
10};
11
12use crate::error::{CliError, ExitCode};
13use crate::pool::PoolFamily;
14use crate::strategy::StrategyFacetDescriptor;
15
16/// The typed result of one command execution.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum CommandReport {
19    /// A `database` command report.
20    Database(DatabaseReport),
21    /// An `exchange` command report.
22    Exchange(ExchangeReport),
23    /// A `pool` command report.
24    Pool(PoolReport),
25    /// An `aave` command report.
26    Aave(AaveReport),
27    /// A `fleet` command report.
28    Fleet(FleetReport),
29    /// A `path` command report.
30    Path(PathReport),
31    /// A `strategy` command report (ADR-055 facets).
32    Strategy(StrategyReport),
33    /// A `config` command report.
34    Config(ConfigReport),
35}
36
37impl CommandReport {
38    /// The operator-facing lines the argv facade renders.
39    #[must_use]
40    pub fn render_lines(&self) -> Vec<String> {
41        match self {
42            Self::Database(report) => report.render_lines(),
43            Self::Exchange(report) => report.render_lines(),
44            Self::Pool(report) => report.render_lines(),
45            Self::Aave(report) => report.render_lines(),
46            Self::Fleet(report) => report.render_lines(),
47            Self::Path(report) => report.render_lines(),
48            Self::Strategy(report) => report.render_lines(),
49            Self::Config(report) => report.render_lines(),
50        }
51    }
52}
53
54/// One resolved (or absent) driver-domain value, as `config show` renders it.
55///
56/// The key is the operator's own spelling: a declared key
57/// (`session.chain_id`, `database.path`), a per-chain endpoint entry
58/// (`nodes.ws[8453]`), or a whole transport's explicit slot (`nodes.ws`).
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct ConfigValue {
61    /// The key as the operator writes it.
62    pub key: String,
63    /// The value, verbatim; `(unresolved)` is carried by the absent source
64    /// rather than a sentinel string.
65    pub value: String,
66    /// The layer that supplied the value, or `None` when no layer did.
67    pub source: Option<degenbot_config::Source>,
68}
69
70impl ConfigValue {
71    /// A value with its winning layer.
72    #[must_use]
73    pub fn new(key: &str, value: String, source: degenbot_config::Source) -> Self {
74        Self {
75            key: key.to_string(),
76            value,
77            source: Some(source),
78        }
79    }
80
81    /// A key no layer supplied: reported, never guessed and never omitted.
82    #[must_use]
83    pub fn unresolved(key: &str) -> Self {
84        Self {
85            key: key.to_string(),
86            value: String::new(),
87            source: None,
88        }
89    }
90
91    /// The `key = value` line (the file view). The value is redacted at
92    /// render time: the file keeps the operator's bytes, but a rendered line
93    /// never prints a credential (ADR-062 D12).
94    #[must_use]
95    pub fn line(&self) -> String {
96        match self.source {
97            Some(_) => format!(
98                "{} = {}",
99                self.key,
100                degenbot_config::redact_uri(&self.value)
101            ),
102            None => format!("{} = (unresolved)", self.key),
103        }
104    }
105
106    /// The `key = value (source)` line (`config show --resolved`), redacted.
107    #[must_use]
108    pub fn resolved_line(&self) -> String {
109        match self.source {
110            Some(source) => format!(
111                "{} = {} ({source})",
112                self.key,
113                degenbot_config::redact_uri(&self.value)
114            ),
115            None => format!("{} = (unresolved)", self.key),
116        }
117    }
118}
119
120/// The typed result of a `config` command.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum ConfigReport {
123    /// `config show`: the driver-domain values, annotated with their winning
124    /// layer when `resolved` was asked for.
125    Shown {
126        /// The config file in play, absent when no location resolves.
127        file: Option<PathBuf>,
128        /// The values, in the operator's key order.
129        values: Vec<ConfigValue>,
130        /// Whether each line carries its winning layer (`--resolved`).
131        resolved: bool,
132    },
133    /// `config path`: the config file the mutating arms read and write.
134    Path(PathBuf),
135    /// `config get <key>`: one resolved value and its winning layer (or the
136    /// absent layer for an unresolved key).
137    Got {
138        /// The key as the operator spelled it.
139        key: String,
140        /// The resolved value, verbatim (redacted at render time).
141        value: String,
142        /// The layer that supplied it, or `None` when none did.
143        source: Option<degenbot_config::Source>,
144    },
145    /// `config set <key> <value>`: the override was written.
146    Set {
147        /// The key as the operator spelled it.
148        key: String,
149        /// The value written, verbatim (redacted at render time).
150        value: String,
151        /// Whether the write applies or an env var shadows it.
152        outcome: crate::strategy::MutationOutcome,
153    },
154    /// `config unset <key>`: the override was dropped.
155    Unset {
156        /// The key as the operator spelled it.
157        key: String,
158        /// Whether an env var still supplies the key at load time.
159        outcome: crate::strategy::MutationOutcome,
160    },
161}
162
163impl ConfigReport {
164    /// The operator-facing lines for this report.
165    #[must_use]
166    pub fn render_lines(&self) -> Vec<String> {
167        match self {
168            Self::Shown {
169                file,
170                values,
171                resolved,
172            } => {
173                // The file in play is also the mutating arms' write target, so
174                // an absent file is named as such rather than presented as a
175                // file the values were read from.
176                let mut lines = vec![match file {
177                    Some(path) if path.exists() => format!("config = {}", path.display()),
178                    Some(path) => format!("config = {} (not yet created)", path.display()),
179                    None => "config = (no config file location)".to_string(),
180                }];
181                lines.extend(values.iter().map(|value| {
182                    if *resolved {
183                        value.resolved_line()
184                    } else {
185                        value.line()
186                    }
187                }));
188                lines
189            }
190            Self::Path(path) => vec![path.display().to_string()],
191            Self::Got { key, value, source } => vec![match source {
192                Some(source) => {
193                    format!("{key} = {} ({source})", degenbot_config::redact_uri(value))
194                }
195                None => format!("{key} = (unresolved)"),
196            }],
197            Self::Set {
198                key,
199                value,
200                outcome,
201            } => vec![
202                format!("set {key} = {}", degenbot_config::redact_uri(value)),
203                shadow_line(outcome),
204            ],
205            Self::Unset { key, outcome } => {
206                vec![format!("removed {key}"), shadow_line(outcome)]
207            }
208        }
209    }
210}
211
212/// The typed result of the execution entry.
213#[derive(Debug)]
214pub struct CommandOutcome {
215    result: Result<CommandReport, CliError>,
216    /// The process exit code derived at the single `From<&CliError>` site.
217    pub exit_code: ExitCode,
218}
219
220impl CommandOutcome {
221    /// Bundle a result with its derived exit code.
222    #[must_use]
223    pub(crate) const fn new(result: Result<CommandReport, CliError>, exit_code: ExitCode) -> Self {
224        Self { result, exit_code }
225    }
226
227    /// The typed report, when the command completed.
228    #[must_use]
229    pub fn report(&self) -> Option<&CommandReport> {
230        self.result.as_ref().ok()
231    }
232
233    /// The typed failure, when the command did not complete.
234    #[must_use]
235    pub fn error(&self) -> Option<&CliError> {
236        self.result.as_ref().err()
237    }
238}
239
240/// Which dry-run arm produced a [`DatabaseReport::DryRun`].
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242pub enum DryRunKind {
243    /// `database cutover --dry-run`.
244    Cutover,
245    /// `database heal --dry-run`.
246    Heal,
247}
248
249/// The outcome of a successful `database cutover` (pre-state derived).
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251pub enum CutoverOutcome {
252    /// The DB was Alembic-stamped and is now Rust-owned.
253    Converted,
254    /// The DB was already Rust-owned; the cutover was a no-op.
255    AlreadyRustOwned,
256}
257
258/// The typed result of a `database` command.
259#[derive(Debug, Clone, PartialEq, Eq)]
260pub enum DatabaseReport {
261    /// `backup` completed.
262    BackedUp {
263        /// The source database path.
264        source: PathBuf,
265        /// The written backup path.
266        backup: PathBuf,
267    },
268    /// `reset` recreated the database.
269    Reset {
270        /// The database path.
271        path: PathBuf,
272    },
273    /// `compact` vacuumed the database.
274    Compacted {
275        /// The database path.
276        path: PathBuf,
277    },
278    /// `inspect` read the schema state (writes nothing).
279    Inspected {
280        /// The database path.
281        path: PathBuf,
282        /// The observed schema state.
283        state: SchemaState,
284    },
285    /// `cutover` flipped schema ownership.
286    Cutover {
287        /// The database path.
288        path: PathBuf,
289        /// The observed pre-cutover schema state.
290        state: SchemaState,
291        /// Whether the cutover converted or no-op'd.
292        outcome: CutoverOutcome,
293    },
294    /// `heal` rebuilt the database out-of-place.
295    Healed {
296        /// The database path.
297        path: PathBuf,
298        /// The heal report (rows copied, `.bak` path, warnings).
299        report: HealReport,
300    },
301    /// A `--dry-run` observed the schema state and wrote nothing.
302    DryRun {
303        /// The database path.
304        path: PathBuf,
305        /// The observed schema state.
306        state: SchemaState,
307        /// Which dry-run arm ran.
308        kind: DryRunKind,
309    },
310}
311
312impl DatabaseReport {
313    /// The operator-facing lines for this report (the ported click `echo` text).
314    #[must_use]
315    pub fn render_lines(&self) -> Vec<String> {
316        match self {
317            Self::BackedUp { backup, .. } => {
318                vec![format!("Backed up SQLite database to {}", backup.display())]
319            }
320            Self::Reset { path } => {
321                vec![format!(
322                    "Initialized new SQLite database at {}",
323                    path.display()
324                )]
325            }
326            Self::Compacted { path } => {
327                vec![format!("Compacted SQLite database at {}", path.display())]
328            }
329            Self::Inspected { state, .. } => {
330                vec![format!("Schema state: {}.", schema_state_label(state))]
331            }
332            Self::Cutover { path, outcome, .. } => match outcome {
333                CutoverOutcome::Converted => vec![format!(
334                    "Cut over database at {} from Alembic to Rust ownership (the \
335                     `alembic_version` table was dropped and `_degenbot_db_schema_version` \
336                     was stamped).",
337                    path.display()
338                )],
339                CutoverOutcome::AlreadyRustOwned => {
340                    vec!["The database is already Rust-owned; cutover was a no-op.".to_string()]
341                }
342            },
343            Self::Healed { path, report } => healed_lines(path, report),
344            Self::DryRun { state, kind, .. } => vec![match kind {
345                DryRunKind::Cutover => cutover_dry_run_line(state),
346                DryRunKind::Heal => heal_dry_run_line(state),
347            }],
348        }
349    }
350}
351
352/// Whether an `exchange activate` flipped the row or found it already active.
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354pub enum ActivateOutcome {
355    /// The row was newly activated (or re-activated from inactive).
356    Activated,
357    /// The row was already active; nothing was written.
358    AlreadyActive,
359}
360
361/// Whither an `exchange deactivate`.
362#[derive(Debug, Clone, Copy, PartialEq, Eq)]
363pub enum DeactivateOutcome {
364    /// The row was newly deactivated.
365    Deactivated,
366    /// The row was already inactive.
367    AlreadyDeactivated,
368    /// The DB has no row for the pair.
369    NoEntry,
370}
371
372/// Whether an `exchange list` row's DB entry exists, and its active state.
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum ExchangeActiveState {
375    /// The DB row exists with `active = true`.
376    Active,
377    /// The DB row exists with `active = false`.
378    Inactive,
379    /// The DB has no row for the pair (never activated).
380    NoEntry,
381}
382
383impl ExchangeActiveState {
384    /// The operator-facing state word in the `exchange list` lines.
385    #[must_use]
386    pub const fn as_str(self) -> &'static str {
387        match self {
388            Self::Active => "active",
389            Self::Inactive => "inactive",
390            Self::NoEntry => "not in database",
391        }
392    }
393}
394
395/// One `exchange list` row: a supported `(chain, DEX)` pair and its DB state.
396#[derive(Debug, Clone, PartialEq, Eq)]
397pub struct ExchangeListRow {
398    /// The chain id.
399    pub chain_id: u64,
400    /// The human chain label.
401    pub chain_label: &'static str,
402    /// The human DEX label.
403    pub display_name: &'static str,
404    /// The DEX name slug.
405    pub dex_slug: &'static str,
406    /// The exchange factory (V4: the `PoolManager`), checksummed.
407    pub factory: String,
408    /// The DB active state.
409    pub state: ExchangeActiveState,
410}
411
412/// The typed result of an `exchange` command.
413#[derive(Debug, Clone, PartialEq, Eq)]
414pub enum ExchangeReport {
415    /// `exchange activate`.
416    Activated {
417        /// The resolved chain id.
418        chain_id: u64,
419        /// The human chain label.
420        chain_label: &'static str,
421        /// The human DEX label.
422        display_name: &'static str,
423        /// The DEX name slug.
424        dex_slug: &'static str,
425        /// Whether the row flipped or was already active.
426        outcome: ActivateOutcome,
427    },
428    /// `exchange deactivate`.
429    Deactivated {
430        /// The resolved chain id.
431        chain_id: u64,
432        /// The human chain label.
433        chain_label: &'static str,
434        /// The human DEX label.
435        display_name: &'static str,
436        /// The DEX name slug.
437        dex_slug: &'static str,
438        /// The deactivation outcome.
439        outcome: DeactivateOutcome,
440    },
441    /// `exchange list`.
442    Listed {
443        /// One row per supported `(chain, DEX)` pair, in declaration order.
444        rows: Vec<ExchangeListRow>,
445    },
446}
447
448impl ExchangeReport {
449    /// The operator-facing lines for this report.
450    #[must_use]
451    pub fn render_lines(&self) -> Vec<String> {
452        match self {
453            Self::Activated {
454                chain_id,
455                chain_label,
456                display_name,
457                outcome,
458                ..
459            } => match outcome {
460                ActivateOutcome::Activated => vec![format!(
461                    "Activated {display_name} on {chain_label} (chain ID {chain_id})."
462                )],
463                ActivateOutcome::AlreadyActive => {
464                    vec!["Exchange is already activated.".to_string()]
465                }
466            },
467            Self::Deactivated {
468                chain_id,
469                chain_label,
470                display_name,
471                outcome,
472                ..
473            } => match outcome {
474                DeactivateOutcome::Deactivated => vec![format!(
475                    "Deactivated {display_name} on {chain_label} (chain ID {chain_id})."
476                )],
477                DeactivateOutcome::AlreadyDeactivated => {
478                    vec!["Exchange is already deactivated.".to_string()]
479                }
480                DeactivateOutcome::NoEntry => vec![format!(
481                    "The database has no entry for {display_name} on {chain_label} \
482                     (chain ID {chain_id})."
483                )],
484            },
485            Self::Listed { rows } => rows
486                .iter()
487                .map(|row| {
488                    format!(
489                        "{} on {} (chain ID {}): {}",
490                        row.display_name,
491                        row.chain_label,
492                        row.chain_id,
493                        row.state.as_str()
494                    )
495                })
496                .collect(),
497        }
498    }
499}
500
501/// The typed result of a `pool` command.
502#[derive(Debug, Clone, PartialEq, Eq)]
503pub enum PoolReport {
504    /// `pool update` advanced the chain.
505    Updated {
506        /// The chain advanced.
507        chain_id: i64,
508        /// The first block processed.
509        from_block: u64,
510        /// The last block advanced to.
511        to_block: u64,
512        /// Chunks committed.
513        chunks_committed: usize,
514        /// Pool rows written.
515        total_pools_written: usize,
516        /// Per-pool liquidity applies.
517        total_liquidity_applies: usize,
518    },
519    /// `pool update` was cooperatively cancelled; committed chunks stay durable.
520    UpdateCancelled {
521        /// The chain.
522        chain_id: i64,
523    },
524    /// `pool verify` compared the committed map against on-chain truth.
525    Verified {
526        /// The pool identifier.
527        pool: String,
528        /// The family.
529        family: PoolFamily,
530        /// The block the truth was read at.
531        block_number: u64,
532        /// The named divergences (empty = GREEN).
533        divergences: Vec<degenbot_pool_updater::LiquidityDivergence>,
534    },
535}
536
537impl PoolReport {
538    /// The operator-facing lines for this report.
539    #[must_use]
540    pub fn render_lines(&self) -> Vec<String> {
541        match self {
542            Self::Updated {
543                chain_id,
544                from_block,
545                to_block,
546                chunks_committed,
547                total_pools_written,
548                total_liquidity_applies,
549            } => vec![format!(
550                "Chain {chain_id}: advanced {from_block}->{to_block} in {chunks_committed} \
551                 chunks ({total_pools_written} pools written, {total_liquidity_applies} \
552                 liquidity applies)."
553            )],
554            Self::UpdateCancelled { chain_id } => vec![format!(
555                "Chain {chain_id}: cancelled (committed chunks stay durable)."
556            )],
557            Self::Verified {
558                pool,
559                family,
560                block_number,
561                divergences,
562            } => verification_lines(pool, *family, *block_number, divergences),
563        }
564    }
565}
566
567/// The typed result of a `fleet` command (ADR-051 D6).
568#[derive(Debug, Clone, PartialEq, Eq)]
569pub enum FleetReport {
570    /// The live posture echo: the six `cordon_*` values plus `posture`,
571    /// rendered as one compact JSON object with sorted keys (the Python
572    /// `json.dumps(effective, sort_keys=True)` line).
573    Posture {
574        /// The rendered effective policy (`{}` when the host echoed none).
575        effective: String,
576    },
577}
578
579impl FleetReport {
580    /// The operator-facing lines for this report.
581    #[must_use]
582    pub fn render_lines(&self) -> Vec<String> {
583        match self {
584            Self::Posture { effective } => vec![effective.clone()],
585        }
586    }
587}
588
589/// The typed result of a `path` command (ADR-051 D6).
590#[derive(Debug, Clone, PartialEq, Eq)]
591pub enum PathReport {
592    /// `path add` enqueued the path.
593    Added {
594        /// The host's `detail` receipt.
595        detail: String,
596    },
597    /// `path discover` completed a bounded sweep.
598    Discovered {
599        /// The host's `detail` receipt.
600        detail: String,
601    },
602}
603
604impl PathReport {
605    /// The operator-facing lines for this report.
606    #[must_use]
607    pub fn render_lines(&self) -> Vec<String> {
608        match self {
609            Self::Added { detail } | Self::Discovered { detail } => vec![detail.clone()],
610        }
611    }
612}
613
614/// The typed result of a `strategy` command.
615#[derive(Debug, Clone, PartialEq, Eq)]
616pub enum StrategyReport {
617    /// `strategy list`: every declared facet.
618    Listed {
619        /// One descriptor per facet, in declaration order.
620        rows: Vec<StrategyFacetDescriptor>,
621    },
622    /// `strategy show`: one facet's descriptor plus its activation posture.
623    Shown {
624        /// The facet descriptor.
625        descriptor: StrategyFacetDescriptor,
626        /// The facet's activation + endpoint posture (`None` when no config
627        /// file could be read).
628        activation: Option<crate::strategy::EndpointSummary>,
629    },
630    /// `strategy activate`: the facet was activated with the settled posture.
631    Activated {
632        /// The activated facet.
633        facet: crate::strategy::StrategyFacet,
634        /// The settled endpoint posture.
635        summary: crate::strategy::EndpointSummary,
636        /// Whether the write applies or an env var shadows it.
637        outcome: crate::strategy::MutationOutcome,
638    },
639    /// `strategy deactivate`: the facet was deactivated.
640    Deactivated {
641        /// The deactivated facet.
642        facet: crate::strategy::StrategyFacet,
643        /// Whether the write applies or an env var shadows it.
644        outcome: crate::strategy::MutationOutcome,
645    },
646    /// `strategy set`: a facet key's override was written.
647    Set {
648        /// The mutated facet.
649        facet: crate::strategy::StrategyFacet,
650        /// The written key's field name.
651        key: &'static str,
652        /// Whether the write applies or an env var shadows it.
653        outcome: crate::strategy::MutationOutcome,
654    },
655    /// `strategy default` / `strategy remove`: the override was dropped so the
656    /// schema default applies again.
657    Defaulted {
658        /// The mutated facet.
659        facet: crate::strategy::StrategyFacet,
660        /// The restored key's field name.
661        key: &'static str,
662    },
663}
664
665impl StrategyReport {
666    /// The operator-facing lines for this report.
667    #[must_use]
668    pub fn render_lines(&self) -> Vec<String> {
669        match self {
670            Self::Listed { rows } => rows
671                .iter()
672                .map(|descriptor| {
673                    format!(
674                        "{} ({}) -> {} [{} declared key(s)]",
675                        descriptor.facet.as_str(),
676                        descriptor.trigger_kind,
677                        descriptor.config_section,
678                        descriptor.fields.len()
679                    )
680                })
681                .collect(),
682            Self::Shown {
683                descriptor,
684                activation,
685            } => {
686                let mut lines = vec![format!(
687                    "{}: {} strategy",
688                    descriptor.config_section, descriptor.trigger_kind
689                )];
690                lines.push(format!("  selector: {}", descriptor.facet.as_str()));
691                if let Some(summary) = activation {
692                    lines.push(format!("  posture: {}", posture_line(summary)));
693                }
694                if descriptor.fields.is_empty() {
695                    lines.push("  declared keys: (none yet)".to_string());
696                } else {
697                    for (field, env) in descriptor.fields.iter().zip(&descriptor.envs) {
698                        lines.push(format!("  {field} ({env})"));
699                    }
700                }
701                lines
702            }
703            Self::Activated {
704                facet,
705                summary,
706                outcome,
707            } => vec![
708                format!("activated strategy {}", facet.as_str()),
709                format!("  endpoints: {}", posture_line(summary)),
710                shadow_line(outcome),
711            ],
712            Self::Deactivated { facet, outcome } => vec![
713                format!(
714                    "deactivated strategy {} (recorded endpoints kept)",
715                    facet.as_str()
716                ),
717                shadow_line(outcome),
718            ],
719            Self::Set {
720                facet,
721                key,
722                outcome,
723            } => vec![
724                format!("set {}.{}", facet.config_section(), key),
725                shadow_line(outcome),
726            ],
727            Self::Defaulted { facet, key } => vec![format!(
728                "restored {}.{} to its declared default",
729                facet.config_section(),
730                key
731            )],
732        }
733    }
734}
735
736/// One line describing a facet's settled endpoint posture.
737fn posture_line(summary: &crate::strategy::EndpointSummary) -> String {
738    match summary {
739        crate::strategy::EndpointSummary::Inactive => "inactive".to_string(),
740        crate::strategy::EndpointSummary::Unset => {
741            "UNSET (activation requires --endpoints or --endpoints-default)".to_string()
742        }
743        crate::strategy::EndpointSummary::Default(urls) => {
744            format!("default ({})", urls.join(", "))
745        }
746        crate::strategy::EndpointSummary::Explicit(urls) => urls.join(", "),
747    }
748}
749
750/// The loud line when the env layer shadows a written key.
751fn shadow_line(outcome: &crate::strategy::MutationOutcome) -> String {
752    match outcome {
753        crate::strategy::MutationOutcome::Applied => "  applies at load time".to_string(),
754        crate::strategy::MutationOutcome::Shadowed { env } => {
755            format!("  WARNING: {env} is set in the environment and will shadow this write")
756        }
757    }
758}
759
760/// The green / red `pool verify` text.
761fn verification_lines(
762    pool: &str,
763    family: PoolFamily,
764    block_number: u64,
765    divergences: &[degenbot_pool_updater::LiquidityDivergence],
766) -> Vec<String> {
767    use degenbot_pool_updater::LiquidityDivergence;
768    if divergences.is_empty() {
769        return vec![format!(
770            "GREEN: {} pool {pool} matches on-chain truth at block {block_number}.",
771            family.as_str()
772        )];
773    }
774    let mut lines = vec![format!(
775        "RED: {} divergence(s) for {} pool {pool} at block {block_number}:",
776        divergences.len(),
777        family.as_str()
778    )];
779    for divergence in divergences {
780        lines.push(match divergence {
781            LiquidityDivergence::TickGross {
782                tick,
783                expected,
784                actual,
785            } => format!("  tick {tick}: TickGross expected={expected} actual={actual}"),
786            LiquidityDivergence::TickNet {
787                tick,
788                expected,
789                actual,
790            } => format!("  tick {tick}: TickNet expected={expected} actual={actual}"),
791            LiquidityDivergence::BitmapWord {
792                word,
793                expected,
794                actual,
795            } => format!("  word {word}: BitmapWord expected={expected} actual={actual}"),
796            LiquidityDivergence::TickPresence {
797                tick,
798                stored,
799                observed,
800            } => format!("  tick {tick}: TickPresence stored={stored} observed={observed}"),
801        });
802    }
803    lines
804}
805
806/// One `aave update` market's outcome.
807#[derive(Debug, Clone, PartialEq, Eq)]
808pub enum AaveUpdateOutcome {
809    /// The market advanced.
810    Advanced {
811        /// First block processed.
812        from_block: u64,
813        /// Last block advanced to.
814        to_block: u64,
815        /// Chunks committed.
816        chunks_committed: usize,
817        /// Events applied.
818        total_events_applied: usize,
819    },
820    /// The market's run was cooperatively cancelled.
821    Cancelled,
822    /// The market has no `last_update_block`; it is skipped (must be bootstrapped).
823    NeedsBootstrap,
824    /// `--dry-run`: the would-be advance, with nothing committed.
825    DryRun {
826        /// The market's `last_update_block`.
827        last_update_block: i64,
828        /// The resolved target (`None` = chain tip).
829        to_block: Option<u64>,
830    },
831}
832
833/// The facts `aave reset` renders: what the market-reset module read back
834/// from the reset transaction — the market row's `active` flag, the
835/// `POOL_ADDRESS_PROVIDER` contract row's presence, and the cursor the reset
836/// left. They are read, never assumed. The command does NOT run an update;
837/// the next `aave update` cold-boots from this cursor.
838#[derive(Debug, Clone, PartialEq, Eq)]
839pub struct AaveReinit {
840    /// The market row's `active` flag after the reset, read from the row.
841    pub market_activated: bool,
842    /// Whether the `POOL_ADDRESS_PROVIDER` contract row is present after the
843    /// reset (the bootstrap's fetch anchor).
844    pub contract_row_present: bool,
845    /// The `last_update_block` the reset left — the bootstrap block on the
846    /// shipped mainnet deployment.
847    pub last_update_block: Option<i64>,
848}
849
850/// One `aave update` market row.
851#[derive(Debug, Clone, PartialEq, Eq)]
852pub struct AaveUpdateEntry {
853    /// The chain.
854    pub chain_id: i64,
855    /// The market id.
856    pub market_id: i64,
857    /// The market name.
858    pub market_name: String,
859    /// The outcome.
860    pub outcome: AaveUpdateOutcome,
861}
862
863/// One position row (scaled balance + token symbol).
864#[derive(Debug, Clone, PartialEq, Eq)]
865pub struct AavePositionLine {
866    /// The underlying token symbol (`Unknown` when unresolved).
867    pub symbol: String,
868    /// The scaled balance.
869    pub balance: U256,
870}
871
872/// The typed result of an `aave` command.
873#[derive(Debug, Clone, PartialEq, Eq)]
874pub enum AaveReport {
875    /// `aave activate`.
876    Activated {
877        /// The chain id.
878        chain_id: u64,
879        /// The human chain label.
880        chain_label: &'static str,
881        /// The market id.
882        market_id: i64,
883        /// The on-chain market name.
884        market_name: String,
885        /// Whether the market was newly created.
886        created: bool,
887    },
888    /// `aave deactivate`.
889    Deactivated {
890        /// The chain id.
891        chain_id: u64,
892        /// The market id, when a row was found.
893        market_id: Option<i64>,
894        /// The outcome.
895        outcome: DeactivateOutcome,
896    },
897    /// `aave digest`.
898    Digest {
899        /// The typed completed-market record; the facade renders its
900        /// canonical manifest bytes (one JSON document the operator
901        /// redirects stdout to pin).
902        manifest: CompletedMarketManifest,
903    },
904    /// `aave update`.
905    Updated {
906        /// Per-market outcomes.
907        entries: Vec<AaveUpdateEntry>,
908    },
909    /// `aave reset`.
910    Reset {
911        /// The chain id.
912        chain_id: u64,
913        /// The market id.
914        market_id: i64,
915        /// The market name.
916        market_name: String,
917        /// The per-relation row counts the purge removed, or would remove on a
918        /// preview.
919        counts: Vec<AaveMarketPurgeCount>,
920        /// `true` when the arm previewed the purge and touched nothing.
921        dry_run: bool,
922        /// The facts the reset transaction verified; `None` on a preview.
923        reinit: Option<AaveReinit>,
924    },
925    /// `aave position show`.
926    Position {
927        /// The user address (checksummed).
928        user_address: String,
929        /// The market name.
930        market: String,
931        /// The chain id.
932        chain_id: u64,
933        /// Collateral positions.
934        collateral: Vec<AavePositionLine>,
935        /// Debt positions.
936        debt: Vec<AavePositionLine>,
937    },
938    /// `aave position show` found no market.
939    PositionNoMarket {
940        /// The market name.
941        market: String,
942        /// The chain id.
943        chain_id: u64,
944    },
945    /// `aave position show` found no user row.
946    PositionNoUser {
947        /// The user address (checksummed).
948        user_address: String,
949        /// The market name.
950        market: String,
951        /// The chain id.
952        chain_id: u64,
953    },
954}
955
956impl AaveReport {
957    /// The operator-facing lines for this report.
958    #[must_use]
959    pub fn render_lines(&self) -> Vec<String> {
960        match self {
961            Self::Activated {
962                chain_id,
963                chain_label,
964                market_id,
965                market_name,
966                created,
967            } => vec![
968                format!("Activated Aave V3 on {chain_label} (chain ID {chain_id})."),
969                format!("  Market: {market_name} (id={market_id}, created={created})."),
970            ],
971            Self::Deactivated {
972                chain_id, outcome, ..
973            } => match outcome {
974                DeactivateOutcome::Deactivated => vec![format!(
975                    "Deactivated Aave V3 on {} (chain ID {chain_id}).",
976                    chain_label_for(*chain_id)
977                )],
978                DeactivateOutcome::AlreadyDeactivated => Vec::new(),
979                DeactivateOutcome::NoEntry => {
980                    vec![format!(
981                        "The database has no entry for Aave V3 on {} (chain ID {chain_id}).",
982                        chain_label_for(*chain_id)
983                    )]
984                }
985            },
986            // The digest arm's payload IS the operator-facing output: the
987            // typed record's canonical bytes, printed verbatim (the drive
988            // pins it by redirecting stdout).
989            Self::Digest { manifest } => vec![render_completed_market_manifest(manifest)],
990            Self::Updated { entries } => entries.iter().flat_map(entry_lines).collect(),
991            Self::Reset {
992                chain_id,
993                market_id,
994                market_name,
995                counts,
996                dry_run,
997                reinit,
998            } => reset_lines(
999                *chain_id,
1000                *market_id,
1001                market_name,
1002                counts,
1003                *dry_run,
1004                reinit.as_ref(),
1005            ),
1006            Self::Position {
1007                user_address,
1008                market,
1009                chain_id,
1010                collateral,
1011                debt,
1012            } => position_lines(user_address, market, *chain_id, collateral, debt),
1013            Self::PositionNoMarket { market, chain_id } => {
1014                vec![format!(
1015                    "No market found with name '{market}' on chain {chain_id}."
1016                )]
1017            }
1018            Self::PositionNoUser {
1019                user_address,
1020                market,
1021                chain_id,
1022            } => vec![format!(
1023                "No Aave user found for address {user_address} in market '{market}' on chain \
1024                 {chain_id}."
1025            )],
1026        }
1027    }
1028}
1029
1030/// The human chain label used in the aave report lines.
1031fn chain_label_for(chain_id: u64) -> String {
1032    match chain_id {
1033        1 => "Ethereum".to_string(),
1034        8453 => "Base".to_string(),
1035        other => other.to_string(),
1036    }
1037}
1038
1039/// The lines for one `aave update` market.
1040fn entry_lines(entry: &AaveUpdateEntry) -> Vec<String> {
1041    let AaveUpdateEntry {
1042        chain_id,
1043        market_id,
1044        market_name,
1045        outcome,
1046    } = entry;
1047    match outcome {
1048        AaveUpdateOutcome::Advanced {
1049            from_block,
1050            to_block,
1051            chunks_committed,
1052            total_events_applied,
1053        } => vec![format!(
1054            "Chain {chain_id} market {market_id} ({market_name}): advanced {from_block}-> \
1055             {to_block} in {chunks_committed} chunks ({total_events_applied} events applied)."
1056        )],
1057        AaveUpdateOutcome::Cancelled => vec![format!(
1058            "Chain {chain_id} market {market_id}: cancelled (committed chunks stay durable)."
1059        )],
1060        AaveUpdateOutcome::NeedsBootstrap => vec![format!(
1061            "Chain {chain_id} market {market_id} ({market_name}): needs bootstrapping \
1062             (last_update_block is None); skipping. Bootstrap the stamp before running."
1063        )],
1064        AaveUpdateOutcome::DryRun {
1065            last_update_block,
1066            to_block,
1067        } => vec![format!(
1068            "Dry run: would advance chain {chain_id} market {market_id} ({market_name}) from \
1069             block {last_update_block} to {} (no changes committed).",
1070            render_opt_block(*to_block)
1071        )],
1072    }
1073}
1074
1075/// The lines for an `aave reset`: the purge plan the operator sees BEFORE
1076/// anything is written, then the verified facts the reset transaction left.
1077fn reset_lines(
1078    chain_id: u64,
1079    market_id: i64,
1080    market_name: &str,
1081    counts: &[AaveMarketPurgeCount],
1082    dry_run: bool,
1083    reinit: Option<&AaveReinit>,
1084) -> Vec<String> {
1085    let mut lines = Vec::with_capacity(counts.len() + 3);
1086    if dry_run {
1087        lines.push(format!(
1088            "Dry run: would reset chain {chain_id} market {market_id} ({market_name}); \
1089             nothing deleted."
1090        ));
1091    } else {
1092        lines.push(format!(
1093            "Reset chain {chain_id} market {market_id} ({market_name})."
1094        ));
1095    }
1096    for count in counts {
1097        lines.push(format!("  {}: {} row(s)", count.table, count.rows));
1098    }
1099    match reinit {
1100        Some(reinit) => lines.push(format!(
1101            "  re-initialized via the activate seam: market row active = {}, \
1102             POOL_ADDRESS_PROVIDER row = {}, last_update_block = {}",
1103            reinit.market_activated,
1104            reinit.contract_row_present,
1105            render_opt_block(
1106                reinit
1107                    .last_update_block
1108                    .map(|b| u64::try_from(b).unwrap_or(0))
1109            )
1110        )),
1111        None if dry_run => lines.push(
1112            "  re-init skipped: the purge was previewed, so the market's state is unchanged."
1113                .to_string(),
1114        ),
1115        None => {}
1116    }
1117    lines
1118}
1119
1120/// Render an optional resolved block the way Python's `{value!r}` does.
1121fn render_opt_block(block: Option<u64>) -> String {
1122    block.map_or_else(|| "None".to_string(), |n| n.to_string())
1123}
1124
1125/// The ported `aave position show` body.
1126fn position_lines(
1127    user_address: &str,
1128    market: &str,
1129    chain_id: u64,
1130    collateral: &[AavePositionLine],
1131    debt: &[AavePositionLine],
1132) -> Vec<String> {
1133    let mut lines = vec![
1134        format!("Aave V3 Positions for {user_address}"),
1135        format!("Market: {market} (Chain: {chain_id})"),
1136        "=".repeat(60),
1137    ];
1138    if collateral.is_empty() {
1139        lines.push("No collateral positions found.".to_string());
1140    } else {
1141        lines.push("Collateral Positions:".to_string());
1142        lines.push("-".repeat(60));
1143        lines.extend(
1144            collateral
1145                .iter()
1146                .map(|p| format!("  {}: {} (scaled)", p.symbol, p.balance)),
1147        );
1148    }
1149    if debt.is_empty() {
1150        lines.push("No debt positions found.".to_string());
1151    } else {
1152        lines.push("Debt Positions:".to_string());
1153        lines.push("-".repeat(60));
1154        lines.extend(
1155            debt.iter()
1156                .map(|p| format!("  {}: {} (scaled)", p.symbol, p.balance)),
1157        );
1158    }
1159    lines
1160}
1161
1162/// The ported `heal` success / no-op text.
1163fn healed_lines(path: &std::path::Path, report: &HealReport) -> Vec<String> {
1164    if matches!(report.old_state, SchemaState::RustOwned { .. }) {
1165        return vec![format!(
1166            "Database at {} is already Rust-owned; heal is a no-op (no copy, no .bak).",
1167            path.display()
1168        )];
1169    }
1170    let total_rows: u64 = report.rows_copied.values().sum();
1171    let n_tables = report.rows_copied.len();
1172    let mut lines = vec![format!(
1173        "Healed database at {}: {total_rows} rows across {n_tables} tables copied; old DB \
1174         preserved at {}; new state: {}.",
1175        path.display(),
1176        report.bak_path.display(),
1177        schema_state_label(&report.new_state)
1178    )];
1179    if !report.warnings.is_empty() {
1180        lines.push(format!("Warnings: {}", report.warnings.join("; ")));
1181    }
1182    lines
1183}
1184
1185/// The ported `database cutover --dry-run` line for `state`.
1186#[must_use]
1187pub fn cutover_dry_run_line(state: &SchemaState) -> String {
1188    let label = schema_state_label(state);
1189    match state {
1190        SchemaState::LegacyAlembic => format!(
1191            "Schema state: {label}. Would cutover from Alembic to Rust ownership (drop \
1192             `alembic_version`, stamp `_degenbot_db_schema_version`)."
1193        ),
1194        SchemaState::RustOwned { .. } => {
1195            format!("Schema state: {label}. Already Rust-owned — cutover is a no-op.")
1196        }
1197        SchemaState::FreshStandalone { .. } => {
1198            format!("Schema state: {label}. No legacy history — nothing to cutover.")
1199        }
1200        SchemaState::Unrecognized => {
1201            format!("Schema state: {label}. Unrecognized database (foreign file).")
1202        }
1203    }
1204}
1205
1206/// The ported `database heal --dry-run` line for `state`.
1207#[must_use]
1208pub fn heal_dry_run_line(state: &SchemaState) -> String {
1209    let label = schema_state_label(state);
1210    match state {
1211        SchemaState::LegacyAlembic => format!(
1212            "Schema state: {label}. Would heal: rebuild at the Rust head schema, copy all \
1213             rows, drop alembic_version, stamp _degenbot_db_schema_version, atomic-swap with \
1214             a *.bak backup."
1215        ),
1216        SchemaState::RustOwned { .. } => {
1217            format!("Schema state: {label}. Already Rust-owned — heal is a no-op.")
1218        }
1219        SchemaState::FreshStandalone { .. } => format!(
1220            "Schema state: {label}. Empty file — heal produces a fresh RustOwned DB (0 rows \
1221             copied)."
1222        ),
1223        SchemaState::Unrecognized => {
1224            format!(
1225                "Schema state: {label}. Unrecognized database (foreign file) — heal would \
1226                 refuse."
1227            )
1228        }
1229    }
1230}
1231
1232/// The Python-compatible label for a [`SchemaState`] (mirrors the
1233/// `db_inspect_schema_state` return values).
1234#[must_use]
1235pub fn schema_state_label(state: &SchemaState) -> &'static str {
1236    match state {
1237        SchemaState::LegacyAlembic => "legacy_alembic",
1238        SchemaState::FreshStandalone { .. } => "fresh_standalone",
1239        SchemaState::RustOwned { .. } => "rust_owned",
1240        SchemaState::Unrecognized => "unrecognized",
1241    }
1242}