trusty-mpm 1.7.7

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
//! `tm statusline` — emit one status-bar line for Claude Code's `statusLine` hook.
//!
//! Why: Claude Code's `statusLine` hook fires on every render cycle and calls this
//! command; this handler parses the hook JSON from stdin and emits a compact
//! ` | `-separated segment string on stdout. All fields degrade gracefully.
//! What: reads a JSON object from stdin and renders the fixed-order layout
//! `TM <ver> ● | <project> ⎇ <branch> | @<gh> | ✻<account> | <model> | ctx% |
//! <cost> | <usage> | <savings>` (#2011, extended #2140 with the trailing
//! account-usage% segment, #6304 dropped the daemon port and added the Claude
//! Code account, #6958 appended the estimated token-savings segment)
//! to stdout. The leading `TM <ver>` text is an OSC 8 hyperlink to the
//! trusty-console on its selected port, so Cmd-click opens the dashboard while
//! the rendered columns stay exactly as wide as before. Missing or invalid
//! fields produce empty/omitted segments; nothing ever panics or blocks the
//! render path.
//! Test: `render_statusline_minimal_input`, `render_statusline_full_payload`,
//! `assemble_statusline_pins_segment_order_with_markers`,
//! `version_segment_links_to_the_console_on_a_non_default_port` in tests.

pub(crate) mod account;
// `pub(crate)` since #5539: `picker_delete_glob` reuses `branch`'s bounded
// `tmux_session_name` probe rather than growing a second copy of it.
pub(crate) mod branch;
pub(crate) mod compaction;
// #6958: the estimated token-savings segment, folded from the usage ledger.
mod savings;
mod usage;

use std::io::Read as _;

use std::path::Path;

use crate::formatters::info_box::DaemonInfo;
use account::{claude_account_segment_probe, claude_json_path};
use branch::project_segment;
use compaction::{ContextWindow, colorize_ctx_segment, compaction_segment};
use savings::{record_session_facts, savings_segment_probe};
use usage::{RateLimits, usage_segment};

/// Claude Code `statusLine` hook input (all fields optional via `#[serde(default)]`).
///
/// Why: Claude Code may add fields in future versions; `deny_unknown_fields` is
/// intentionally absent so new keys do not cause parse failures.
/// What: cwd, model metadata, cost summary, context-window data, and the
/// context-window overflow flag.
/// Test: `render_statusline_minimal_input` (empty input), `render_statusline_full_payload`.
#[derive(Debug, Default, serde::Deserialize)]
pub(crate) struct StatusInput {
    #[serde(default)]
    pub(crate) session_id: String,
    #[serde(default)]
    pub(crate) cwd: String,
    /// #7074: the session's own transcript, the only source of its token
    /// counts. Remembered per session so `tm commit-trailers` can fold it.
    #[serde(default)]
    pub(crate) transcript_path: String,
    #[serde(default)]
    pub(crate) model: ModelInfo,
    #[serde(default)]
    pub(crate) cost: CostInfo,
    #[serde(default)]
    pub(crate) exceeds_200k_tokens: bool,
    #[serde(default)]
    pub(crate) context_window: Option<ContextWindow>,
    #[serde(default)]
    pub(crate) rate_limits: Option<RateLimits>,
}

/// Model metadata from the Claude Code hook input.
///
/// Why: `display_name` carries the human-readable label ("Opus") operators want
/// in the status bar; `id` is the fallback when `display_name` is absent.
/// What: both fields are `String` with `#[serde(default)]` so absent keys are "".
/// Test: `render_statusline_full_payload`.
#[derive(Debug, Default, serde::Deserialize)]
pub(crate) struct ModelInfo {
    #[serde(default)]
    pub(crate) id: String,
    #[serde(default)]
    pub(crate) display_name: String,
}

/// Cost accumulator from the Claude Code hook input.
///
/// Why: operators want running cost in the status bar to monitor spend.
/// What: `total_cost_usd` is the session's accumulated cost; 0.0 when absent.
/// Test: `render_statusline_full_payload`.
#[derive(Debug, Default, serde::Deserialize)]
pub(crate) struct CostInfo {
    #[serde(default)]
    pub(crate) total_cost_usd: f64,
}

/// The stdin JSON fields a verifier needs to reproduce the `💸` savings
/// segment (#7907).
///
/// Why: `tm statusline --help` did not name the fields a hand-built
/// `statusLine` payload has to carry (#7907).
/// What: the field path (dotted for a nested field) and why it matters, in
/// the exact order [`render_statusline_from`] reads them: `session_id` is
/// the ledger fold key `savings_segment_probe` reads;
/// `context_window.total_input_tokens` is optional and feeds the
/// session-actual-tokens counter `compaction_segment` persists for
/// [`compaction::session_actual_tokens_for`] to read — which prices `ctx%`
/// and the commit footer, and since #8063 no longer moves either `💸` figure.
/// What `statusline_help_names_every_savings_stdin_field` guarantees: it
/// fails if `tm statusline --help`'s rendered text and this list disagree in
/// either direction -- a field listed here missing from `--help`, or
/// `--help` naming a field not listed here. What it does NOT guarantee: that
/// this list matches what [`render_statusline_from`] actually reads -- the
/// list is maintained by hand against that function, not derived from it.
/// Test: `statusline_help_names_every_savings_stdin_field` in `tests.rs`.
// #7907: hand-maintained against `render_statusline_from`; `--help`'s text
// is a literal clap doc comment also kept in sync with this list by hand.
#[cfg(test)]
pub(crate) const SAVINGS_SEGMENT_STDIN_FIELDS: &[(&str, &str)] = &[
    (
        "session_id",
        "required -- the ledger fold key `savings_segment_probe` reads",
    ),
    (
        "context_window.total_input_tokens",
        "optional -- feeds the session-actual-tokens counter via \
         compaction_segment, which prices ctx% and the commit footer; it \
         moves no 💸 figure since #8063",
    ),
];

/// Read Claude Code's `statusLine` JSON from stdin and print one compact line.
///
/// Why: Claude Code's `statusLine` hook protocol is "command reads JSON from
/// stdin, prints one line to stdout, exits 0"; this is the single entry point.
/// What: reads all of stdin, parses it as `StatusInput` (empty/invalid → default),
/// renders segments, and prints exactly one line to stdout.
/// Test: `render_statusline_minimal_input`, `render_statusline_full_payload`.
pub(crate) fn run_statusline() -> anyhow::Result<()> {
    let mut raw = String::new();
    let _ = std::io::stdin().read_to_string(&mut raw);
    let input: StatusInput = serde_json::from_str(&raw).unwrap_or_default();
    println!("{}", render_statusline(&input));
    Ok(())
}

/// Render the compact statusline string from parsed hook input.
///
/// Why: keeping rendering pure aside from bounded, timeout-guarded probes makes
/// the layout unit-testable and keeps Claude Code's hot render path fast (#2011:
/// the prior blocking-I/O + path-traversal bug means every probe here must stay
/// non-blocking and infallible). Probing each segment here and handing the
/// results to the pure [`assemble_statusline`] lets the fixed segment ORDER be
/// pinned by a deterministic unit test with hand-supplied strings, independent
/// of real git/gh/daemon state.
/// What: probes each of the nine segments (version+daemon dot, project+branch,
/// gh account, Claude Code account, model, ctx%, cost, account-usage%,
/// estimated savings) in spec order and joins them via [`assemble_statusline`].
/// Test: `render_statusline_minimal_input`, `render_statusline_full_payload`,
/// `render_statusline_full_payload_matches_pipe_format`.
pub(crate) fn render_statusline(input: &StatusInput) -> String {
    render_statusline_from(input, claude_json_path().as_deref())
}

/// [`render_statusline`] against an explicit Claude Code config path.
///
/// Why (#6304): the account segment is the one probe whose source is a single
/// file, so passing that path in makes both of its branches — account present,
/// account underivable — assertable end to end. It has to be an injected path
/// rather than a repointed `CLAUDE_CONFIG_DIR`: `env_isolation_tests` bans this
/// target from writing that variable, since its tests share one process (#5544).
/// What: identical to [`render_statusline`], except the account is read from
/// `account_config` (or omitted when that is `None` or unreadable).
/// Test: `render_statusline_shows_claude_account_when_config_is_present`.
fn render_statusline_from(input: &StatusInput, account_config: Option<&Path>) -> String {
    // Lock-file read only — cheap and non-blocking; no HTTP session-count probe
    // is needed since the reformatted layout (#2011) no longer surfaces a count.
    let daemon = DaemonInfo::from_lock_file();
    let version = version_segment(&daemon);

    let project = project_segment(&input.cwd);
    let gh = gh_account_segment_probe();
    // #6304: the Claude Code account the session runs under; absent from the
    // stdin payload, so it comes from Claude Code's own persisted config.
    let account = claude_account_segment_probe(account_config);
    let model = model_segment(&input.model);
    // #6972: this payload is the only place the authoritative model id reaches
    // `tm`, so remember it here for `tm divert` — a separate process — to price
    // its savings rows at. #7074 adds the transcript path on the same footing,
    // for `tm commit-trailers` to fold a session's token counts out of. Writes
    // only when a value changed.
    // #7424: `cwd` joins the call — the turn-1 startup reading recorded here is
    // only usable scoped to a project, and this payload is where `tm` learns
    // the session's working directory.
    record_session_facts(
        &input.session_id,
        &input.model.id,
        &input.transcript_path,
        &input.cwd,
    );

    // Compaction efficiency / live context fill; falls back to a bare
    // `ctx>200k` marker when no context-window payload was sent at all.
    // `exceeds_200k_tokens` is itself already an over-limit signal (usage
    // fraction 1.0), so the fallback marker is always colored red (#2098).
    let ctx = compaction_segment(&input.session_id, input.context_window.as_ref()).or_else(|| {
        input
            .exceeds_200k_tokens
            .then(|| colorize_ctx_segment("ctx>200k", 1.0))
    });

    let cost = (input.cost.total_cost_usd > 0.0).then(|| cost_segment(input.cost.total_cost_usd));

    // Account-level rate-limit usage (#2140); appended after cost, absent
    // entirely before the first API response of a session or on non-Pro/Max
    // accounts (Claude Code simply omits `rate_limits` in those cases).
    let usage = usage_segment(input.rate_limits.as_ref());

    // #6958: estimated tokens the harness avoided sending for THIS session,
    // folded from the usage ledger at render time. Absent whenever the ledger
    // is missing, unreadable, or sums to nothing.
    let savings = savings_segment_probe(&input.session_id);

    assemble_statusline(
        version, project, gh, account, model, ctx, cost, usage, savings,
    )
}

/// Join the nine statusline segments in spec order, omitting absent ones.
///
/// Why (#2011 follow-up, extended #2140, #6304 and #6958): separating ORDER +
/// JOIN from the I/O-bound probes that produce each segment value is what makes
/// the exact layout — `TM <ver> ● | <project> ⎇ <branch> | @<gh> | ✻<account> |
/// <model> | ctx% | <cost> | <usage> | <savings>` — pinned by a deterministic
/// test using hand-supplied synthetic strings. Without this split, a future
/// refactor could transpose or silently drop a middle segment and no test would
/// catch it.
/// What: takes the nine segments in fixed spec order (`version` is always
/// present; the rest are `Option<String>`), filters out `None`s, and joins the
/// survivors with ` | `. Pure — no I/O, no panics.
/// Test: `assemble_statusline_full_payload_pins_order_and_format`,
/// `assemble_statusline_pins_segment_order_with_markers`,
/// `assemble_statusline_omits_none_segments`.
#[allow(clippy::too_many_arguments)]
fn assemble_statusline(
    version: String,
    project: Option<String>,
    gh: Option<String>,
    account: Option<String>,
    model: Option<String>,
    ctx: Option<String>,
    cost: Option<String>,
    usage: Option<String>,
    savings: Option<String>,
) -> String {
    [
        Some(version),
        project,
        gh,
        account,
        model,
        ctx,
        cost,
        usage,
        savings,
    ]
    .into_iter()
    .flatten()
    .collect::<Vec<_>>()
    .join(" | ")
}

/// Build the leading `TM <ver> ●` segment as a link to the trusty-console.
///
/// Why: the dashboard is one Cmd-click away from a bar the operator is already
/// looking at, and the version text is where they already look for "what am I
/// running". Wrapping that text rather than adding a segment keeps the bar the
/// same width. The link is an OSC 8 hyperlink, so the port lives in the escape
/// sequence and never in a rendered column — #6304 removed the visible daemon
/// port from this segment on the grounds that a printed port invites stale
/// connection attempts, and a hyperlink target resolved fresh on every render
/// does not reintroduce that.
/// What: [`version_text`] for the visible text, [`hyperlink`] for the wrapping,
/// and `discovery::console_base_url()` for the target — the same
/// discovery-file read the `tm` gateway resolver uses, so the URL carries the
/// port the console is actually selected for. No probe, no network call, and a
/// missing console config degrades to the default port.
/// Test: `version_segment_links_to_the_console_on_a_non_default_port`,
/// `version_segment_links_to_the_default_console_port`,
/// `version_segment_keeps_the_version_text_verbatim`.
fn version_segment(daemon: &DaemonInfo) -> String {
    version_segment_linked(daemon, &trusty_mpm::core::discovery::console_base_url())
}

/// [`version_segment`] with the console URL injected.
///
/// Why: lets the link tests pin a non-default port without a running console or
/// a stubbed `$HOME`.
/// What: wraps [`version_text`] in an OSC 8 link to `console_url`.
/// Test: `version_segment_links_to_the_console_on_a_non_default_port`,
/// `version_segment_links_to_the_default_console_port`.
fn version_segment_linked(daemon: &DaemonInfo, console_url: &str) -> String {
    hyperlink(&version_text(daemon), console_url)
}

/// The visible text of the leading segment: `TM <ver> ●`.
///
/// Why (#6304): the port this segment used to append is not something an
/// operator can act on from a status bar, and it invites port-based connection
/// attempts the daemon's transport no longer guarantees. Its only other job was
/// implicit — it appeared ONLY when the daemon was online, so its presence was
/// the reachability indicator. Dropping it outright would take that bit with
/// it, so the port is replaced by a bare `●`, which says the same thing in one
/// column and names nothing that can go stale. (#2011 introduced the
/// `TM <ver> <port>` form this replaces.)
/// What: reads `env!("CARGO_PKG_VERSION")` and appends `●` when
/// `daemon.online`; an offline or absent daemon renders `TM <ver>` alone.
/// Test: `version_segment_online_shows_dot_not_port`,
/// `version_segment_offline_omits_dot`,
/// `render_statusline_never_contains_the_daemon_port`.
fn version_text(daemon: &DaemonInfo) -> String {
    let ver = env!("CARGO_PKG_VERSION");
    if daemon.online {
        format!("TM {ver} \u{25cf}")
    } else {
        format!("TM {ver}")
    }
}

/// Wrap `text` in an OSC 8 terminal hyperlink pointing at `url`.
///
/// Why: Claude Code's status line documents OSC 8 as the supported way to make
/// status text clickable, alongside the SGR colors this module already emits
/// (<https://code.claude.com/docs/en/statusline>, "Links"). A terminal without
/// hyperlink support renders the text and drops the escape, so no fallback URL
/// is printed beside it — printing one would put the port back in a visible
/// column for every operator to pay for.
/// What: `ESC ] 8 ; ; <url> BEL <text> ESC ] 8 ; ; BEL`. BEL (`\x07`) rather
/// than ST terminates each half, matching the form in those docs' own examples.
/// Test: `hyperlink_wraps_text_in_osc8`,
/// `version_segment_keeps_the_version_text_verbatim`.
fn hyperlink(text: &str, url: &str) -> String {
    format!("\u{1b}]8;;{url}\u{7}{text}\u{1b}]8;;\u{7}")
}

// ── Segment builders ──────────────────────────────────────────────────────────
//
// The project-identity + branch-label segment (`project_segment` and its
// tmux/git helpers) lives in the sibling `branch` module (#2031 follow-up,
// split out to stay under the 500-SLOC production file cap).

/// Build the model-label segment.
///
/// Why: operators want to know which model Claude Code is using at a glance.
/// What: returns `display_name` when non-empty, `id` as fallback, `None` when
/// both are empty (segment omitted from the status bar).
/// Test: `render_statusline_full_payload`.
fn model_segment(model: &ModelInfo) -> Option<String> {
    if !model.display_name.is_empty() {
        Some(model.display_name.clone())
    } else if !model.id.is_empty() {
        Some(model.id.clone())
    } else {
        None
    }
}

/// Build the cost segment (`$X.XX`).
///
/// Why: running cost visibility helps operators monitor API spend.
/// What: formats `usd` to two decimal places with a `$` prefix.
/// Test: `render_statusline_full_payload`.
fn cost_segment(usd: f64) -> String {
    format!("${usd:.2}")
}

/// Probe the active `gh` github.com account for the statusline, cheaply and
/// fail-soft, with a 100 ms wall-clock bound.
///
/// Why (#gh-account-awareness): `tm` shells to `gh` constantly (PR merge, issue
/// edits) but the operator had no visibility into WHICH github.com identity was
/// active. A non-admin active account silently broke `gh pr merge --admin`.
/// Surfacing `@<login>` in the status bar — and flagging the multi-account
/// ambiguity that hides the bug — makes the active identity impossible to miss.
/// The bounded-thread pattern (matching the `branch` module's git/tmux probes)
/// keeps a slow config read from ever blocking Claude Code's hot render path.
/// What: spawns a detached thread that reads `gh`'s `hosts.yml` via the cheap,
/// subprocess-free [`trusty_mpm::core::gh_account::gh_account_status_local`],
/// waits ≤100 ms, and renders the segment via [`render_gh_account_segment`].
/// Returns `None` (segment omitted) when `gh` is unconfigured, the read times
/// out, or no active account is set — never errors or blocks.
/// Test: the render is unit-tested via [`render_gh_account_segment`]; the probe
/// itself is thin bounded glue over the tested local reader.
fn gh_account_segment_probe() -> Option<String> {
    use std::sync::mpsc;
    use std::time::Duration;

    let (tx, rx) = mpsc::channel();
    std::thread::spawn(move || {
        let _ = tx.send(trusty_mpm::core::gh_account::gh_account_status_local());
    });
    let status = rx.recv_timeout(Duration::from_millis(100)).ok().flatten()?;
    render_gh_account_segment(status.active.as_deref(), status.logged_in.len())
}

/// Assemble the `@<login>` gh-account segment from a resolved active login.
///
/// Why: keeping the render pure (no file/subprocess I/O) makes the
/// present/absent/multi-account cases unit-testable without touching real `gh`
/// state, and centralises the ambiguity marker.
/// What: returns `None` for an absent/blank active login (segment omitted);
/// `"@<login>"` for a single logged-in account; and `"@<login>⚠"` when more than
/// one account is logged in (`logged_in_count > 1`) so the operator notices they
/// may be on the wrong identity.
/// Test: `render_gh_account_segment_single`, `render_gh_account_segment_multi`,
/// `render_gh_account_segment_absent`.
fn render_gh_account_segment(active: Option<&str>, logged_in_count: usize) -> Option<String> {
    let active = active?.trim();
    if active.is_empty() {
        return None;
    }
    Some(if logged_in_count > 1 {
        format!("@{active}\u{26a0}")
    } else {
        format!("@{active}")
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use compaction::ContextWindow;

    fn full_input() -> StatusInput {
        StatusInput {
            session_id: String::new(),
            cwd: "/home/user/my-project".to_string(),
            transcript_path: String::new(),
            model: ModelInfo {
                id: "claude-sonnet-4-6".to_string(),
                display_name: "Claude Sonnet 4.6".to_string(),
            },
            cost: CostInfo {
                total_cost_usd: 1.23,
            },
            exceeds_200k_tokens: false,
            context_window: None,
            rate_limits: None,
        }
    }

    #[test]
    fn render_statusline_minimal_input() {
        // Empty StatusInput (all defaults) must not panic; the `TM <ver>` lead-in
        // segment always appears (#2011).
        let out = render_statusline(&StatusInput::default());
        assert!(
            visible_text(&out).starts_with("TM "),
            "TM <ver> segment must always lead"
        );
        assert!(!out.is_empty(), "output must not be empty");
    }

    #[test]
    fn render_statusline_full_payload() {
        // Full payload shows model name, cost; project segment when cwd is set.
        // `/home/user/my-project` is not a git repo → basename fallback ("my-project").
        let input = full_input();
        let out = render_statusline(&input);
        assert!(
            out.contains("Claude Sonnet 4.6"),
            "model display name must appear"
        );
        assert!(out.contains("$1.23"), "cost must appear");
        assert!(
            out.contains("my-project"),
            "project name from cwd must appear"
        );
    }

    /// Why (#2011): pins the exact reformatted layout — `TM <ver>` lead-in,
    /// `|`-joined segments (not the old `│` glyph), and no legacy session-count
    /// (`⛁N`) segment.
    /// Test: itself.
    #[test]
    fn render_statusline_full_payload_matches_pipe_format() {
        let input = full_input();
        let out = render_statusline(&input);
        let ver = env!("CARGO_PKG_VERSION");
        assert!(
            visible_text(&out).starts_with(&format!("TM {ver}")),
            "must lead with TM <ver>: {out}"
        );
        assert!(
            out.contains(" | "),
            "segments must be pipe-separated: {out}"
        );
        assert!(
            !out.contains('\u{2502}'),
            "old │ separator must not appear: {out}"
        );
        assert!(
            !out.contains('\u{26c1}'),
            "session-count segment must be dropped: {out}"
        );
    }

    /// Why (#2011 follow-up): `render_statusline_full_payload_matches_pipe_format`
    /// only checks a prefix/substring/absence, so a refactor that transposed or
    /// silently dropped a middle segment (`@gh` / model / ctx% / cost) would
    /// still pass it. This test drives the pure join layer directly with
    /// synthetic, realistic segment strings — no git/gh/daemon I/O — and
    /// asserts the exact joined output, pinning both the format AND the order.
    /// Test: itself.
    #[test]
    fn assemble_statusline_full_payload_pins_order_and_format() {
        let out = assemble_statusline(
            "TM 1.2.3 \u{25cf}".to_string(),
            Some("bobmatnyc/trusty-tools \u{2387} main".to_string()),
            Some("@bobmatnyc".to_string()),
            Some("\u{273b}someone@example.com".to_string()),
            Some("Claude Sonnet 4.6".to_string()),
            Some("ctx 41%".to_string()),
            Some("$1.23".to_string()),
            Some("\u{23f3}24% \u{1f4c5}41%".to_string()),
            Some("\u{1f4b8}~$0.42".to_string()),
        );
        assert_eq!(
            out,
            "TM 1.2.3 \u{25cf} | bobmatnyc/trusty-tools \u{2387} main | @bobmatnyc | \u{273b}someone@example.com | Claude Sonnet 4.6 | ctx 41% | $1.23 | \u{23f3}24% \u{1f4c5}41% | \u{1f4b8}~$0.42"
        );
    }

    /// Why (#2011 follow-up): guards specifically against segment
    /// transposition — using distinct single-letter markers instead of
    /// realistic strings means a swap between any two positions (e.g. gh and
    /// model) produces a different, easily-diffed string rather than two
    /// plausible-looking segments that a reviewer might not notice swapped.
    /// What: asserts both the exact joined string AND the split-on-` | `
    /// vector equal `[version, project, gh, account, model, ctx, cost, usage]`.
    /// Test: itself.
    #[test]
    fn assemble_statusline_pins_segment_order_with_markers() {
        let out = assemble_statusline(
            "VERSION".to_string(),
            Some("PROJECT".to_string()),
            Some("GH".to_string()),
            Some("ACCOUNT".to_string()),
            Some("MODEL".to_string()),
            Some("CTX".to_string()),
            Some("COST".to_string()),
            Some("USAGE".to_string()),
            Some("SAVINGS".to_string()),
        );
        assert_eq!(
            out,
            "VERSION | PROJECT | GH | ACCOUNT | MODEL | CTX | COST | USAGE | SAVINGS"
        );
        assert_eq!(
            out.split(" | ").collect::<Vec<_>>(),
            vec![
                "VERSION", "PROJECT", "GH", "ACCOUNT", "MODEL", "CTX", "COST", "USAGE", "SAVINGS"
            ],
            "segment order must exactly match [version, project, gh, account, model, ctx, cost, usage, savings]"
        );
    }

    /// Why (#2011 follow-up): every segment except `version` must be omittable
    /// independently without leaving a stray/empty ` | ` pair, and omitting all
    /// of them must fall back to just the lead-in segment.
    /// Test: itself.
    #[test]
    fn assemble_statusline_omits_none_segments() {
        // All optional segments absent → only the lead-in segment appears.
        let out = assemble_statusline(
            "TM 1.2.3".to_string(),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        assert_eq!(out, "TM 1.2.3");

        // Gaps in the middle (gh and account absent) must not leave empty
        // separator pairs.
        let out = assemble_statusline(
            "TM 1.2.3".to_string(),
            Some("proj".to_string()),
            None,
            None,
            Some("model".to_string()),
            None,
            Some("$0.50".to_string()),
            None,
            None,
        );
        assert_eq!(out, "TM 1.2.3 | proj | model | $0.50");
    }

    /// Why (#6304, branch a): an online daemon must render the bare `●`
    /// reachability dot and NOT the port — the port is what this issue removes,
    /// and this exact input (`127.0.0.1:7880`, online) is what used to produce
    /// it.
    /// Test: itself.
    #[test]
    fn version_segment_online_shows_dot_not_port() {
        let daemon = DaemonInfo {
            addr: "127.0.0.1:7880".to_string(),
            online: true,
            session_count: None,
        };
        let seg = version_text(&daemon);
        assert_eq!(seg, format!("TM {} \u{25cf}", env!("CARGO_PKG_VERSION")));
        assert!(!seg.contains("7880"), "port must not appear: {seg}");
    }

    /// Why (#2011, kept by #6304): an offline/absent daemon degrades to
    /// `TM <ver>` alone — no dot, and still no port.
    /// Test: itself.
    #[test]
    fn version_segment_offline_omits_dot() {
        let daemon = DaemonInfo::default();
        let seg = version_text(&daemon);
        assert_eq!(seg, format!("TM {}", env!("CARGO_PKG_VERSION")));
        assert!(!seg.contains('\u{25cf}'), "no dot when offline: {seg}");
    }

    /// Strip OSC 8 hyperlink sequences, leaving the text a terminal displays.
    ///
    /// Why: the console link puts a `host:port` URL in the emitted bytes, so a
    /// test about what an operator SEES has to drop the escapes first. Without
    /// this the port assertions below would read the link target and call it a
    /// rendered column.
    /// What: removes every `ESC ] 8 ; ; … BEL` run, keeping everything between
    /// the opener and the closer.
    /// Test: exercised by `render_statusline_never_contains_the_daemon_port`
    /// and `version_segment_keeps_the_version_text_verbatim`.
    fn visible_text(s: &str) -> String {
        let mut out = String::with_capacity(s.len());
        let mut rest = s;
        while let Some(start) = rest.find("\u{1b}]8;;") {
            out.push_str(&rest[..start]);
            let after = &rest[start + "\u{1b}]8;;".len()..];
            match after.find('\u{7}') {
                Some(end) => rest = &after[end + 1..],
                None => return out,
            }
        }
        out.push_str(rest);
        out
    }

    /// Why (#6304, branch a): the closure condition is that NO daemon state
    /// renders a port, so drive the whole line for both states rather than only
    /// the lead-in segment builder. The live daemon's address is supplied
    /// explicitly so the assertion holds on a machine where the daemon is down.
    /// The console link added later moved the assertion onto the VISIBLE text —
    /// a link target is not a rendered column, and the daemon port must not
    /// appear in either.
    /// Test: itself.
    #[test]
    fn render_statusline_never_contains_the_daemon_port() {
        for online in [true, false] {
            let daemon = DaemonInfo {
                addr: "http://127.0.0.1:7880".to_string(),
                online,
                session_count: None,
            };
            let seg = version_text(&daemon);
            assert!(
                !seg.contains("7880") && !seg.contains(':'),
                "no port or host:port remnant (online={online}): {seg}"
            );
            // The linked form must not leak the URL into the visible text
            // either — only the daemon-free `TM <ver> ●` may show.
            let linked = version_segment_linked(&daemon, "http://127.0.0.1:9911");
            assert_eq!(visible_text(&linked), seg);
        }
        // And end to end, with whatever the real lock file says.
        let out = render_statusline(&full_input());
        let seen = visible_text(&out);
        assert!(
            !seen.contains("7880"),
            "no port in the rendered line: {seen}"
        );
        assert!(
            !out.contains("7880"),
            "the daemon port is not the link target either: {out}"
        );
    }

    /// Why: the whole point of the link is the console's SELECTED port — a test
    /// that only pinned the default would still pass against a hardcoded 7788.
    /// Test: itself.
    #[test]
    fn version_segment_links_to_the_console_on_a_non_default_port() {
        let daemon = DaemonInfo {
            addr: "127.0.0.1:7880".to_string(),
            online: true,
            session_count: None,
        };
        let seg = version_segment_linked(&daemon, "http://127.0.0.1:9911");
        assert!(
            seg.contains("http://127.0.0.1:9911"),
            "the configured port must be the link target: {seg:?}"
        );
        assert!(
            !seg.contains("7788"),
            "the default port must not be substituted: {seg:?}"
        );
    }

    /// Why: with no console configured the link must still resolve — to the
    /// default port, never to an empty or malformed URL.
    /// Test: itself.
    #[test]
    fn version_segment_links_to_the_default_console_port() {
        let url = format!(
            "http://{}",
            trusty_mpm::core::discovery::DEFAULT_CONSOLE_ADDR
        );
        assert_eq!(url, "http://127.0.0.1:7788");
        let seg = version_segment_linked(&DaemonInfo::default(), &url);
        assert!(
            seg.contains("http://127.0.0.1:7788"),
            "default console port must be the link target: {seg:?}"
        );
    }

    /// Why: the link must not alter what an operator reads — the version text
    /// stays byte-for-byte what it was before the wrapping.
    /// Test: itself.
    #[test]
    fn version_segment_keeps_the_version_text_verbatim() {
        let daemon = DaemonInfo {
            addr: String::new(),
            online: true,
            session_count: None,
        };
        let text = version_text(&daemon);
        let seg = version_segment_linked(&daemon, "http://127.0.0.1:9911");
        assert!(
            seg.contains(&text),
            "version text must survive verbatim: {seg:?}"
        );
        assert_eq!(visible_text(&seg), text);
        assert_eq!(
            visible_text(&seg),
            format!("TM {} \u{25cf}", env!("CARGO_PKG_VERSION"))
        );
    }

    /// Why: the escape framing is a wire format a terminal parses — one wrong
    /// byte and the line renders as garbage rather than a link.
    /// Test: itself.
    #[test]
    fn hyperlink_wraps_text_in_osc8() {
        assert_eq!(
            hyperlink("TM 1.2.3", "http://127.0.0.1:9911"),
            "\u{1b}]8;;http://127.0.0.1:9911\u{7}TM 1.2.3\u{1b}]8;;\u{7}"
        );
    }

    /// Why: the console link rides on the first segment, so the rendered line
    /// must still lead with the version text and still be pipe-separated.
    /// Test: itself.
    #[test]
    fn render_statusline_leads_with_the_linked_version_segment() {
        let out = render_statusline(&full_input());
        assert!(
            out.starts_with("\u{1b}]8;;http://"),
            "the line must open with the console link: {out:?}"
        );
        assert!(
            visible_text(&out).starts_with(&format!("TM {}", env!("CARGO_PKG_VERSION"))),
            "visible text must still lead with TM <ver>: {out:?}"
        );
    }

    /// Why: a single logged-in account renders `@<login>` with no warning mark.
    /// Test: itself.
    #[test]
    fn render_gh_account_segment_single() {
        assert_eq!(
            render_gh_account_segment(Some("bobmatnyc"), 1).as_deref(),
            Some("@bobmatnyc")
        );
        // Zero count is treated the same as one (unambiguous single identity).
        assert_eq!(
            render_gh_account_segment(Some("bobmatnyc"), 0).as_deref(),
            Some("@bobmatnyc")
        );
    }

    /// Why: multiple logged-in accounts must append the `⚠` ambiguity marker so
    /// the operator notices they may be merging as the wrong identity (the bug).
    /// Test: itself.
    #[test]
    fn render_gh_account_segment_multi() {
        let seg = render_gh_account_segment(Some("bob-duetto"), 2).expect("segment");
        assert_eq!(seg, "@bob-duetto\u{26a0}");
        assert!(seg.contains('\u{26a0}'), "multi-account marker must appear");
    }

    /// Why: an absent/blank active login must omit the segment entirely rather
    /// than emit a stray `@`.
    /// Test: itself.
    #[test]
    fn render_gh_account_segment_absent() {
        assert_eq!(render_gh_account_segment(None, 0), None);
        assert_eq!(render_gh_account_segment(Some("   "), 3), None);
        assert_eq!(render_gh_account_segment(Some(""), 1), None);
    }

    #[test]
    fn render_statusline_missing_model_omits_segment() {
        // When both model.id and model.display_name are empty, no model segment.
        let mut input = full_input();
        input.model = ModelInfo::default();
        let out = render_statusline(&input);
        // #6304: assert the absence of the model strings themselves rather than
        // the substring "claude" — the line now also carries the Claude Code
        // account, whose email is outside this test's control.
        assert!(
            !out.contains("claude-sonnet-4-6") && !out.contains("Claude Sonnet 4.6"),
            "model segment must be omitted: {out}"
        );
        assert!(
            visible_text(&out).starts_with("TM "),
            "TM <ver> segment must still appear"
        );
        assert!(out.contains("$1.23"), "cost must still appear");
    }

    #[test]
    fn render_statusline_exceeds_200k_shows_ctx_segment() {
        let mut input = full_input();
        input.exceeds_200k_tokens = true;
        let out = render_statusline(&input);
        assert!(out.contains("ctx>200k"), "ctx>200k segment must appear");
    }

    #[test]
    fn render_statusline_zero_cost_omits_cost_segment() {
        let mut input = full_input();
        input.cost.total_cost_usd = 0.0;
        let out = render_statusline(&input);
        assert!(!out.contains('$'), "cost segment must be omitted when zero");
    }

    #[test]
    fn render_statusline_invalid_json_falls_back_gracefully() {
        // Simulates invalid/empty JSON by using StatusInput::default() — same path
        // as run_statusline's unwrap_or_default on parse failure.
        let out = render_statusline(&StatusInput::default());
        assert!(
            visible_text(&out).starts_with("TM "),
            "graceful fallback must still emit the TM <ver> segment"
        );
        assert!(
            !out.contains("| |"),
            "must not produce empty separator pairs"
        );
    }

    #[test]
    fn render_statusline_no_empty_separator_pairs() {
        // With every optional field empty, the only segment is the TM <ver> lead-in.
        let out = render_statusline(&StatusInput::default());
        assert!(!out.contains("|  | "), "no empty | | pairs");
        assert!(!out.contains("| |"), "no adjacent separators");
    }

    #[test]
    fn render_statusline_with_context_window_shows_live_fill() {
        // When session_id is empty, compaction_segment returns None; ctx% is skipped.
        // When session_id is present and no state file exists, shows live fill.
        // We test via render_compaction_segment directly to avoid real file I/O.
        use compaction::{CompactionState, render_compaction_segment};

        let state = CompactionState::default();
        let cw = ContextWindow {
            total_input_tokens: 82_000,
            context_window_size: 200_000,
            used_percentage: 41.0,
        };
        let seg = render_compaction_segment(&state, &cw);
        assert_eq!(seg.as_deref(), Some("ctx 41%"));
    }

    #[test]
    fn render_statusline_with_context_window_no_session_id_omits_segment() {
        // session_id="" → compaction_segment() → None → no compaction segment
        let mut input = full_input();
        input.context_window = Some(ContextWindow {
            total_input_tokens: 82_000,
            context_window_size: 200_000,
            used_percentage: 41.0,
        });
        let out = render_statusline(&input);
        // No compaction/ctx segment because session_id is empty
        assert!(!out.contains("ctx "), "no ctx segment without session_id");
    }

    /// Why (#6304, branches b and c): end-to-end proof that the Claude Code
    /// account reaches the rendered line from Claude Code's own persisted
    /// config, and that a config file that is not there omits the segment
    /// instead of rendering a placeholder. The path is injected, so nothing
    /// here depends on the operator's home directory or login state — and
    /// nothing writes `CLAUDE_CONFIG_DIR`, which this target bans (#5544).
    /// Test: itself.
    #[test]
    fn render_statusline_shows_claude_account_when_config_is_present() {
        let dir = tempfile::tempdir().expect("temp dir");
        let cfg = dir.path().join(".claude.json");

        // Nothing at the path yet → segment omitted.
        let absent = render_statusline_from(&full_input(), Some(&cfg));
        assert!(
            !absent.contains('\u{273b}'),
            "account segment must be omitted with no config: {absent}"
        );
        // No path at all (neither CLAUDE_CONFIG_DIR nor a home dir resolvable).
        let none = render_statusline_from(&full_input(), None);
        assert!(
            !none.contains('\u{273b}'),
            "account segment must be omitted with no config path: {none}"
        );

        std::fs::write(
            &cfg,
            r#"{"oauthAccount": {"emailAddress": "someone@example.com"}}"#,
        )
        .expect("write config");
        let present = render_statusline_from(&full_input(), Some(&cfg));
        assert!(
            present.contains("\u{273b}someone@example.com"),
            "account segment must appear once the config names one: {present}"
        );
    }

    /// Why (#2140): end-to-end check that `rate_limits` flows from
    /// `StatusInput` through `render_statusline` into a trailing usage
    /// segment, appended after cost.
    /// Test: itself.
    #[test]
    fn render_statusline_with_rate_limits_shows_usage_segment() {
        use usage::{RateLimits, RateWindow};

        let mut input = full_input();
        input.rate_limits = Some(RateLimits {
            five_hour: Some(RateWindow {
                used_percentage: Some(24.0),
            }),
            seven_day: Some(RateWindow {
                used_percentage: Some(41.0),
            }),
        });
        let out = render_statusline(&input);
        assert!(out.contains("24%"), "5h usage % must appear: {out}");
        assert!(out.contains("41%"), "7d usage % must appear: {out}");
        // #7617: the savings segment now always renders — a figure, or the
        // explicit empty state — so the usage segment is no longer last. What
        // this test is about is that usage comes after COST, which is still
        // exactly what it asserts.
        let cost_at = out.find("$1.23").expect("cost segment: {out}");
        let usage_at = out.find("24%").expect("usage segment: {out}");
        assert!(
            cost_at < usage_at,
            "usage segment must be appended after cost: {out}"
        );
    }

    /// Why (#2140): before the first API response (or on non-Pro/Max
    /// accounts) `rate_limits` is entirely absent from the hook payload; the
    /// segment must be cleanly omitted, never a false `0%`.
    /// Test: itself.
    #[test]
    fn render_statusline_without_rate_limits_omits_usage_segment() {
        let input = full_input();
        let out = render_statusline(&input);
        assert!(
            !out.contains('\u{23f3}') && !out.contains('\u{1f4c5}'),
            "usage segment must be omitted when rate_limits is absent: {out}"
        );
    }
}