bitrouter 1.0.0-alpha.34

BitRouter: an LLM API router. CLI + assembly library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! Reports for the daemon-lifecycle (`start` / `stop` / `restart` / `reload` /
//! `status`) and `route` commands.

use crate::actions::route::{ResolvedVia, RouteReport};
use crate::actions::status::StatusReport;
use bitrouter_sdk::invocation;
use serde::Serialize;

use crate::output::CliReport;
use crate::output::human::{Health, Human};

/// Result of a daemon lifecycle action (`start` / `stop` / `restart` /
/// `reload`). `pid`/`listen`/`models`/`log` are present only when the action
/// produced a live daemon (start / restart).
#[derive(Serialize)]
pub struct DaemonActionReport {
    /// The action performed: `start` | `stop` | `restart` | `reload`.
    pub action: &'static str,
    /// The resulting state: `started` | `stopped` | `restarted` | `reloaded` |
    /// `not_ready`.
    pub status: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub listen: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub models: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub log: Option<String>,
}

impl DaemonActionReport {
    /// A daemon came up and answered its control socket.
    pub fn started(
        action: &'static str,
        status: &'static str,
        pid: u32,
        listen: String,
        models: usize,
        log: String,
    ) -> Self {
        Self {
            action,
            status,
            pid: Some(pid),
            listen: Some(listen),
            models: Some(models),
            log: Some(log),
        }
    }

    /// The daemon is alive but slow to answer (still migrating / fetching).
    pub fn not_ready(action: &'static str, pid: u32, log: String) -> Self {
        Self {
            action,
            status: "not_ready",
            pid: Some(pid),
            listen: None,
            models: None,
            log: Some(log),
        }
    }

    /// A payload-less outcome (stop / reload).
    pub fn simple(action: &'static str, status: &'static str) -> Self {
        Self {
            action,
            status,
            pid: None,
            listen: None,
            models: None,
            log: None,
        }
    }
}

impl CliReport for DaemonActionReport {
    fn render(&self, h: &mut Human<'_>) -> std::io::Result<()> {
        match self.pid {
            Some(pid) => {
                let health = if self.status == "not_ready" {
                    Health::Unknown
                } else {
                    Health::Up
                };
                h.status_block(health, &format!("bitrouter daemon {}", self.status))?;
                h.field("pid", pid)?;
                if let Some(listen) = &self.listen {
                    h.field("listen", listen)?;
                }
                if let Some(models) = self.models {
                    h.field("models", format!("{models} routable"))?;
                }
                if let Some(log) = &self.log {
                    h.field("log", log)?;
                }
                Ok(())
            }
            None => h.line(&format!("daemon {}", self.status)),
        }
    }
}

/// The human view of `bro status`. Exit code stays 0 whether running or
/// stopped — "stopped" is an answer, not a failure.
///
/// The report type itself is
/// [`crate::actions::status::StatusReport`]: the `status`
/// tool returns the same type, so `bro status --json` and the tool's
/// structured content are the same bytes. Rendering stays here — a local trait
/// on a foreign type is legal, and it keeps [`Human`] out of the crate.
impl CliReport for StatusReport {
    fn render(&self, h: &mut Human<'_>) -> std::io::Result<()> {
        if !self.running {
            h.status_block(Health::Down, "bitrouter is stopped")?;
            if let Some(version) = &self.installed_version {
                h.field("installed version", version)?;
            }
            if let Some(socket) = &self.socket {
                h.field("socket", socket)?;
            }
            render_configuration_state(self, h)?;
            render_router_state(self, h)?;
            // Spend outlives the daemon: what a past daemon spent is on disk
            // and stays true after it exits, so it is shown here too.
            render_spend(self.spend.as_ref(), h)?;
            return h.note(&format!(
                "Run `{} start` to launch the daemon.",
                invocation::name()
            ));
        }
        h.status_block(Health::Up, "bitrouter is running")?;
        if let Some(pid) = self.pid {
            h.field("pid", pid)?;
        }
        if let Some(version) = &self.installed_version {
            h.field("installed version", version)?;
        }
        if self.socket.is_some() {
            h.field(
                "daemon version",
                self.daemon_version.as_deref().unwrap_or("unknown"),
            )?;
        }
        if let Some(listen) = &self.listen {
            h.field("listen", listen)?;
        }
        if let Some(models) = self.models {
            h.field("models", format!("{models} routable"))?;
        }
        if !self.providers.is_empty() {
            h.field("providers", self.providers.join(", "))?;
        }
        if let Some(socket) = &self.socket {
            h.field("socket", socket)?;
        }
        if let Some(compatibility) = &self.compatibility {
            h.field("compatibility", compatibility)?;
            if let Some(activity) = &self.handoff_activity {
                h.field("active operations", activity.operations)?;
                h.field(
                    "supervised runs",
                    activity
                        .supervised_runs
                        .map_or_else(|| "unknown".to_string(), |runs| runs.to_string()),
                )?;
                h.field("ACP route leases", activity.route_leases)?;
                h.field(
                    "ACP recordings",
                    activity.acp_recordings.map_or_else(
                        || "unknown".to_string(),
                        |recordings| recordings.to_string(),
                    ),
                )?;
            } else {
                h.field("active work", "unknown")?;
            }
            match compatibility.as_str() {
                "legacy_unknown" => h.note("Finish active work, then run `bro restart`; this daemon cannot prove it is idle.")?,
                "externally_managed" => h.note("Restart this daemon with its service manager after active work finishes.")?,
                "handoff_required" => h.note("The next supervised command attempts a safe handoff if idle and the database preflight passes.")?,
                "daemon_newer" => h.note("Install a matching or newer bro binary before using this daemon.")?,
                _ => {}
            }
        }
        render_configuration_state(self, h)?;
        render_router_state(self, h)?;
        render_spend(self.spend.as_ref(), h)
    }
}

fn render_configuration_state(report: &StatusReport, h: &mut Human<'_>) -> std::io::Result<()> {
    use crate::reload::{
        AuxiliaryConfigState, ConfigSourceKind, RunningConfigState, SavedConfigState,
    };

    let Some(state) = &report.config_state else {
        if report.pid.is_some() || report.socket.is_some() {
            return h.field("configuration", "saved/running state unavailable");
        }
        return Ok(());
    };
    h.field(
        "config source",
        match state.source {
            ConfigSourceKind::File => "file",
            ConfigSourceKind::Default => "generated default",
        },
    )?;
    h.field(
        "config saved",
        match state.saved {
            SavedConfigState::Available => "available",
            SavedConfigState::Generated => "generated",
            SavedConfigState::Missing => "missing",
            SavedConfigState::Invalid => "invalid",
            SavedConfigState::Unavailable => "unavailable",
        },
    )?;
    h.field(
        "config running",
        match state.running {
            RunningConfigState::InSync => "saved configuration inputs in sync",
            RunningConfigState::ReloadRequired => "reload required",
            RunningConfigState::RestartRequired => "restart required",
            RunningConfigState::Mixed => "mixed; inspect last reload",
            RunningConfigState::Unknown => "unknown",
        },
    )?;
    if !state.reload_required_fields.is_empty() {
        h.field("reload fields", state.reload_required_fields.join(", "))?;
    }
    if !state.restart_required_fields.is_empty() {
        h.field("restart fields", state.restart_required_fields.join(", "))?;
    }
    let auxiliary = |state| match state {
        AuxiliaryConfigState::InSync => "in sync",
        AuxiliaryConfigState::ReloadRequired => "reload required",
        AuxiliaryConfigState::NotConfigured => "not configured",
        AuxiliaryConfigState::Missing => "missing",
        AuxiliaryConfigState::Invalid => "invalid",
        AuxiliaryConfigState::Unavailable => "unavailable",
        AuxiliaryConfigState::Unknown => "unknown",
    };
    h.field("named policy", auxiliary(state.named_policy))?;
    h.field("access policies", auxiliary(state.access_policies))?;
    if matches!(state.running, RunningConfigState::Mixed)
        && let Some(latest) = state.mixed_state_history.last()
    {
        let outcome = match latest.outcome {
            crate::reload::ReloadOutcome::Succeeded => "succeeded",
            crate::reload::ReloadOutcome::Failed => "failed",
            crate::reload::ReloadOutcome::PartiallyApplied => "partially applied",
            crate::reload::ReloadOutcome::Unknown => "unknown",
        };
        h.field(
            "mixed reload history",
            format!(
                "{} retained; latest generation {} {outcome}; inspect JSON participant results",
                state.mixed_state_history.len(),
                latest.generation
            ),
        )?;
    }
    if let Some(generation) = state.generation {
        h.field("config generation", generation)?;
    }
    Ok(())
}

fn render_router_state(report: &StatusReport, h: &mut Human<'_>) -> std::io::Result<()> {
    match (&report.saved_routers, &report.running_routers) {
        (Some(saved), Some(running)) => {
            h.field(
                "routers",
                format!("{} saved, {} running", saved.len(), running.len()),
            )?;
        }
        (Some(saved), None) => {
            h.field(
                "routers",
                format!("{} saved; running view unavailable", saved.len()),
            )?;
        }
        (None, Some(running)) => {
            h.field(
                "routers",
                format!("{} running; saved view unavailable", running.len()),
            )?;
        }
        (None, None) => {}
    }
    match (
        report.config_state.is_none(),
        report.router_restart_required,
    ) {
        (true, Some(true)) => h.field("router config", "restart required"),
        (true, Some(false)) => h.field("router config", "saved and running match"),
        _ => Ok(()),
    }
}

/// The `spend` block of [`StatusReport`], in the human view.
///
/// Two lines at most, because they are two independent facts: `spend` is money
/// already gone, `credits` is what a capped deployment will still let you
/// spend. A deployment that answers only one prints only one.
///
/// `unpriced` is never rounded away or averaged in. When some requests in the
/// window carried no charge evidence the total is labelled a **floor** and the
/// count is shown, because the one place being wrong about this costs the
/// reader money is exactly here.
fn render_spend(
    spend: Option<&crate::actions::status::Spend>,
    h: &mut Human<'_>,
) -> std::io::Result<()> {
    let Some(spend) = spend else {
        return Ok(());
    };
    if let Some(spent) = &spend.spent {
        let amount = crate::metering::fmt_usd(spent.estimated_micro_usd);
        let line = match spent.unpriced {
            0 => format!("{amount} {} ({} requests)", spent.window, spent.requests),
            unpriced => format!(
                "{amount}+ {} ({} requests, {unpriced} unpriced — floor, not a total)",
                spent.window, spent.requests
            ),
        };
        h.field("spend", line)?;
    }
    if let Some(limit) = &spend.limit {
        // Not `metering::fmt_usd`: that takes an unsigned amount and hard-
        // codes a `$`, neither of which holds for a signed balance in a
        // currency the account declares.
        h.field(
            "credits",
            format!(
                "{:.2} {} remaining",
                limit.remaining_micro_usd as f64 / 1_000_000.0,
                spend.currency
            ),
        )?;
    }
    Ok(())
}

/// Human rendering for the shared `route` report.
///
/// The type and `Human` rendering both live app-side; typed HTTP and CLI
/// adapters reuse the report without duplicating business logic.
impl CliReport for RouteReport {
    fn render(&self, h: &mut Human<'_>) -> std::io::Result<()> {
        // The wire words, so the human view and `--json` name the path the
        // same way.
        let via = match self.resolved_via {
            ResolvedVia::Live => "live",
            ResolvedVia::Config => "config",
            ResolvedVia::ZeroConfig => "zero_config",
        };
        h.line(&format!(
            "model: {}  (resolved via: {via})",
            self.requested_model
        ))?;
        if let Some(router) = &self.router {
            let source = match self.router_source {
                Some(crate::actions::models::RouterSource::User) => "user",
                Some(crate::actions::models::RouterSource::Legacy) => "legacy",
                Some(crate::actions::models::RouterSource::Default) => "default",
                None => "unknown",
            };
            h.line(&format!(
                "  router: {} ({source}, {})",
                router.router_id, router.binding_digest
            ))?;
        }
        if let Some(policy) = &self.bound_policy {
            h.line(&format!(
                "  policy: {policy} (decision not executed; base model: {})",
                self.effective_model
            ))?;
            if !self.candidate_models.is_empty() {
                h.line(&format!(
                    "  candidates: {}",
                    self.candidate_models.join(", ")
                ))?;
            }
        } else if self.effective_model != self.requested_model || self.effective_effort.is_some() {
            let effort = match self.effective_effort {
                Some(effort) => format!("  (effort: {effort})"),
                None => String::new(),
            };
            h.line(&format!("  policy → {}{effort}", self.effective_model))?;
        }
        if self.provider_chain.is_empty() {
            if self.bound_policy.is_some() && self.policy_decision_executed == Some(false) {
                return h.line("  (no provider chain selected without a policy decision)");
            }
            return h.line("  (empty chain — no provider declares this model)");
        }
        for (i, hop) in self.provider_chain.iter().enumerate() {
            h.line(&format!(
                "  {}. {} → {} ({})",
                i + 1,
                hop.provider,
                hop.service_id,
                hop.api_protocol
            ))?;
        }
        if let Some(cost) = &self.estimated_cost {
            // Rates, not a total: nothing was sent, so there is nothing to
            // multiply by. The bracket count is the honest warning that the
            // base rates are not the whole story for this model.
            h.line(&format!(
                "  rates: in {} / out {} µUSD per token{}",
                rate(cost.input_micro_usd_per_token),
                rate(cost.output_micro_usd_per_token),
                match cost.context_tiers.len() {
                    0 => String::new(),
                    n => format!(" (+{n} long-context bracket(s))"),
                }
            ))?;
        }
        Ok(())
    }
}

/// A per-token rate, or `?` where the registry prices nothing.
fn rate(value: Option<f64>) -> String {
    match value {
        Some(v) => format!("{v}"),
        None => "?".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::{Format, Output};

    fn json(r: &dyn CliReport) -> serde_json::Value {
        serde_json::from_slice(&Output::new(Format::Json).render_to_vec(r)).unwrap()
    }

    use crate::actions::status::{Spend, SpendLimit, Spent};

    /// What the local path builds: the `spent` half only.
    fn local_spend(estimated_micro_usd: u64, requests: u64, unpriced: u64) -> Spend {
        Spend {
            currency: "USD".into(),
            spent: Some(Spent {
                window: "today".into(),
                estimated_micro_usd,
                requests,
                unpriced,
            }),
            limit: None,
        }
    }

    #[test]
    fn status_running_json_and_human() {
        let r = StatusReport::running(
            7,
            "127.0.0.1:4356".into(),
            42,
            vec!["anthropic".into(), "openai".into()],
            "/x.sock".into(),
            Some(local_spend(1_230_000, 9, 0)),
        );
        assert_eq!(
            json(&r),
            serde_json::json!({
                "running": true, "pid": 7, "listen": "127.0.0.1:4356", "models": 42,
                "providers": ["anthropic", "openai"], "socket": "/x.sock",
                "spend": {
                    "currency": "USD",
                    "spent": {
                        "window": "today", "estimated_micro_usd": 1_230_000,
                        "requests": 9, "unpriced": 0
                    }
                }
            })
        );
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("● bitrouter is running"), "{h:?}");
        assert!(h.contains("  models    42 routable"), "{h:?}");
        assert!(h.contains("anthropic, openai"), "{h:?}");
        assert!(
            h.contains("configuration  saved/running state unavailable"),
            "{h:?}"
        );
        assert!(h.contains("$1.23 today (9 requests)"), "{h:?}");
    }

    #[test]
    fn status_renders_whole_configuration_state_without_values() -> anyhow::Result<()> {
        use crate::reload::{
            AuxiliaryConfigState, ConfigSourceKind, ConfigurationState, RunningConfigState,
            SavedConfigState,
        };

        let report = StatusReport::running(
            7,
            "127.0.0.1:4356".into(),
            1,
            vec!["demo".into()],
            "/x.sock".into(),
            None,
        )
        .with_config_state(Some(ConfigurationState {
            server_instance_id: Some("fixture-instance".into()),
            generation: Some(4),
            source: ConfigSourceKind::File,
            saved: SavedConfigState::Available,
            running: RunningConfigState::RestartRequired,
            reload_required_fields: vec!["providers".into()],
            restart_required_fields: vec!["server".into()],
            named_policy: AuxiliaryConfigState::ReloadRequired,
            access_policies: AuxiliaryConfigState::Unknown,
            last_reload: None,
            mixed_state_history: Vec::new(),
        }));

        let value = serde_json::to_value(&report)?;
        assert_eq!(value["config_state"]["running"], "restart_required");
        assert_eq!(
            value["config_state"]["restart_required_fields"],
            serde_json::json!(["server"])
        );
        let human = String::from_utf8(Output::new(Format::Human).render_to_vec(&report))?;
        assert!(
            human.contains("config running  restart required"),
            "{human}"
        );
        assert!(human.contains("reload fields  providers"), "{human}");
        assert!(human.contains("restart fields  server"), "{human}");
        assert!(human.contains("named policy  reload required"), "{human}");
        assert!(human.contains("access policies  unknown"), "{human}");
        assert!(!human.contains("fixture-instance"), "{human}");
        Ok(())
    }

    #[test]
    fn mixed_status_points_to_the_retained_participant_cause() -> anyhow::Result<()> {
        use crate::reload::{
            AuxiliaryConfigState, ConfigSourceKind, ConfigurationState, ReloadOutcome,
            ReloadReport, RunningConfigState, SavedConfigState,
        };

        let report = StatusReport::running(
            7,
            "127.0.0.1:4356".into(),
            1,
            vec!["demo".into()],
            "/x.sock".into(),
            None,
        )
        .with_config_state(Some(ConfigurationState {
            server_instance_id: Some("fixture-instance".into()),
            generation: Some(4),
            source: ConfigSourceKind::File,
            saved: SavedConfigState::Available,
            running: RunningConfigState::Mixed,
            reload_required_fields: Vec::new(),
            restart_required_fields: Vec::new(),
            named_policy: AuxiliaryConfigState::InSync,
            access_policies: AuxiliaryConfigState::InSync,
            last_reload: None,
            mixed_state_history: vec![ReloadReport {
                server_instance_id: "fixture-instance".into(),
                generation: 3,
                outcome: ReloadOutcome::PartiallyApplied,
                participants: Vec::new(),
                restart_required_fields: Vec::new(),
                started_at: "2026-09-15T00:00:00Z".into(),
                completed_at: "2026-09-15T00:00:01Z".into(),
            }],
        }));

        let value = serde_json::to_value(&report)?;
        assert_eq!(
            value["config_state"]["mixed_state_history"][0]["outcome"],
            "partially_applied"
        );
        let human = String::from_utf8(Output::new(Format::Human).render_to_vec(&report))?;
        assert!(
            human.contains(
                "mixed reload history  1 retained; latest generation 3 partially applied"
            ),
            "{human}"
        );
        assert!(
            human.contains("inspect JSON participant results"),
            "{human}"
        );
        Ok(())
    }

    #[test]
    fn in_sync_human_label_is_scoped_to_saved_configuration_inputs() -> anyhow::Result<()> {
        let report: StatusReport = serde_json::from_value(serde_json::json!({
            "running": true,
            "providers": [],
            "config_state": {
                "source": "file",
                "saved": "available",
                "running": "in_sync",
                "named_policy": "in_sync",
                "access_policies": "in_sync"
            }
        }))?;

        let human = String::from_utf8(Output::new(Format::Human).render_to_vec(&report))?;
        assert!(
            human.contains("config running  saved configuration inputs in sync"),
            "{human}"
        );
        Ok(())
    }

    #[test]
    fn status_distinguishes_saved_and_running_router_state() -> anyhow::Result<()> {
        use crate::actions::models::{RouterReadiness, RouterSource, RouterStatus};

        let router = |id: &str| RouterStatus {
            id: id.to_string(),
            address: format!("bitrouter/{id}"),
            source: RouterSource::User,
            readiness: RouterReadiness::Ready,
            reason: None,
            selection: None,
            system_prompt_default: true,
            parameter_defaults: vec!["temperature".to_string()],
            binding_digest: Some("router-v1:sha256:test".to_string()),
        };
        let report = StatusReport::running(
            7,
            "127.0.0.1:4356".into(),
            1,
            vec!["demo".into()],
            "/x.sock".into(),
            None,
        )
        .with_router_views(
            Some(vec![router("coding"), router("review")]),
            Some(vec![router("coding")]),
            Some(true),
        );

        let value = json(&report);
        assert_eq!(value["router_restart_required"], true);
        assert_eq!(value["saved_routers"].as_array().map(Vec::len), Some(2));
        assert_eq!(value["running_routers"].as_array().map(Vec::len), Some(1));
        let human = String::from_utf8(Output::new(Format::Human).render_to_vec(&report))?;
        assert!(human.contains("2 saved, 1 running"), "{human}");
        assert!(human.contains("restart required"), "{human}");
        Ok(())
    }

    /// The invariant that costs money to get wrong: a partial figure must
    /// never read like a total. `unpriced` reaches JSON verbatim and the human
    /// view marks the number a floor.
    #[test]
    fn status_spend_never_hides_unpriced_requests() {
        let r = StatusReport::running(
            7,
            "127.0.0.1:4356".into(),
            1,
            vec!["openai".into()],
            "/x.sock".into(),
            Some(local_spend(500_000, 10, 4)),
        );
        assert_eq!(json(&r)["spend"]["spent"]["unpriced"], 4);
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("4 unpriced"), "{h:?}");
        assert!(h.contains("floor, not a total"), "{h:?}");
    }

    /// Spend is not a liveness fact. The metering database records what a past
    /// daemon spent and reads fine with nothing listening, so a stopped report
    /// still answers "am I OK to spend?".
    #[test]
    fn status_stopped_still_reports_spend() {
        let r = StatusReport::stopped("/x.sock".into(), Some(local_spend(0, 0, 0)));
        assert_eq!(
            json(&r),
            serde_json::json!({
                "running": false, "providers": [], "socket": "/x.sock",
                "spend": {
                    "currency": "USD",
                    "spent": {
                        "window": "today", "estimated_micro_usd": 0,
                        "requests": 0, "unpriced": 0
                    }
                }
            })
        );
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("○ bitrouter is stopped"), "{h:?}");
        assert!(h.contains("$0.00 today (0 requests)"), "{h:?}");
    }

    #[test]
    fn status_stopped_omits_optional_fields() {
        let r = StatusReport::stopped("/x.sock".into(), None);
        assert_eq!(
            json(&r),
            serde_json::json!({"running": false, "providers": [], "socket": "/x.sock"})
        );
    }

    /// The cloud half: a cap with no spend-to-date. The two halves render
    /// independently, so a report carrying only `limit` prints only `credits`.
    #[test]
    fn status_renders_a_limit_without_a_spent_figure() {
        let r = StatusReport::metered(Spend {
            currency: "USD".into(),
            spent: None,
            limit: Some(SpendLimit {
                balance_micro_usd: 5_000_000,
                pending_micro_usd: 769_000,
                remaining_micro_usd: 4_231_000,
            }),
        });
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("credits   4.23 USD remaining"), "{h:?}");
        assert!(!h.contains("spend"), "{h:?}");
    }

    /// The whole point of the shared type: what the CLI prints is what the MCP
    /// tool returns, so the tool's structured content deserializes straight
    /// back into the report the CLI emitted.
    #[test]
    fn status_json_round_trips_through_the_shared_type() {
        let r = StatusReport::running(
            7,
            "127.0.0.1:4356".into(),
            42,
            vec!["openai".into()],
            "/x.sock".into(),
            Some(local_spend(42, 1, 1)),
        );
        let back: StatusReport = serde_json::from_value(json(&r)).expect("round trip");
        assert_eq!(serde_json::to_value(&back).unwrap(), json(&r));
    }

    /// An unroutable model is an empty array, not a missing key: a consumer
    /// indexing `provider_chain` must not have to special-case absence.
    #[test]
    fn route_empty_chain_is_empty_array() {
        let r = RouteReport {
            requested_model: "m".into(),
            effective_model: "m".into(),
            effective_effort: None,
            resolved_via: ResolvedVia::Config,
            policy_decision: None,
            router: None,
            router_source: None,
            bound_policy: None,
            policy_decision_executed: None,
            candidate_models: Vec::new(),
            provider_chain: vec![],
            estimated_cost: None,
        };
        assert_eq!(json(&r)["provider_chain"], serde_json::json!([]));
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("no provider declares this model"), "{h}");
    }

    /// The human line has to *say* when the policy table moved the request —
    /// printing only the requested model is how `bro route` used to name
    /// a model the daemon would never pick.
    #[test]
    fn route_human_names_the_effective_model_when_policy_moved_it() {
        use crate::actions::route::ProviderHop;
        let r = RouteReport {
            requested_model: "small".into(),
            effective_model: "big".into(),
            effective_effort: None,
            resolved_via: ResolvedVia::Config,
            policy_decision: None,
            router: None,
            router_source: None,
            bound_policy: None,
            policy_decision_executed: None,
            candidate_models: Vec::new(),
            provider_chain: vec![ProviderHop {
                provider: "demo".into(),
                service_id: "big".into(),
                api_protocol: "openai".into(),
            }],
            estimated_cost: None,
        };
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert!(h.contains("policy → big"), "{h}");
    }

    /// The whole point of the shared type: what `bro route --json` prints
    /// is what the `route_preview` tool returns, so the tool's structured
    /// content deserializes straight back into the report the CLI emitted —
    /// including the enum wire values, which a rename would silently break.
    ///
    /// The wire values are pinned literally too: `resolved_via` is
    /// `live` / `config` / `zero_config`, the same words `bro models`
    /// uses for the same fact, so an agent never sees `live` from one report
    /// and `live daemon` from the other.
    #[test]
    fn route_json_round_trips_through_the_shared_type() {
        use crate::actions::route::{ContextTierRates, EstimatedCost, ProviderHop};
        use bitrouter_ai::types::ReasoningEffort;
        for (via, wire) in [
            (ResolvedVia::Live, "live"),
            (ResolvedVia::Config, "config"),
            (ResolvedVia::ZeroConfig, "zero_config"),
        ] {
            let r = RouteReport {
                requested_model: "small".into(),
                effective_model: "big".into(),
                effective_effort: Some(ReasoningEffort::High),
                resolved_via: via,
                policy_decision: None,
                router: None,
                router_source: None,
                bound_policy: None,
                policy_decision_executed: None,
                candidate_models: Vec::new(),
                provider_chain: vec![ProviderHop {
                    provider: "demo".into(),
                    service_id: "big".into(),
                    api_protocol: "openai".into(),
                }],
                estimated_cost: Some(EstimatedCost::new(
                    Some(1.0),
                    Some(2.0),
                    vec![ContextTierRates {
                        above_input_tokens: 200_000,
                        input_micro_usd_per_token: Some(2.0),
                        output_micro_usd_per_token: Some(4.0),
                    }],
                )),
            };
            let emitted = json(&r);
            assert_eq!(emitted["resolved_via"], wire, "{via:?}");
            let back: RouteReport = serde_json::from_value(emitted.clone()).expect("round trip");
            assert_eq!(serde_json::to_value(&back).unwrap(), emitted);
            // The context tiers survive the trip: dropping them would report a
            // long-context model at its cheapest bracket.
            assert_eq!(
                emitted["estimated_cost"]["context_tiers"][0]["above_input_tokens"],
                200_000
            );
        }
    }

    #[test]
    fn daemon_action_simple_one_liner() {
        let r = DaemonActionReport::simple("stop", "stopped");
        assert_eq!(
            json(&r),
            serde_json::json!({"action": "stop", "status": "stopped"})
        );
        let h = String::from_utf8(Output::new(Format::Human).render_to_vec(&r)).unwrap();
        assert_eq!(h, "daemon stopped\n");
    }
}