trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Unit tests for the picker's #3723 (verbless color rows + duplicate-index
//! fix) and #3724 (rename input mode) changes.
//!
//! Why: kept in its own file (rather than growing `tests_behavior_c_tests.rs`
//! or `tests_behavior_d_tests.rs`, both already near the 1500-SLOC test cap)
//! and included via `session_picker.rs`'s `#[path]` `mod tests`, mirroring
//! the `rename_tests.rs`/`managed_tests.rs` convention used elsewhere in this
//! command tree.
//! What: fixture builders + `next_launch_slot_*`, `parse_picker_choice`'s new
//! `Rename` branch (`parse_picker_choice_rename_*`), and
//! `session_picker_render`'s row formatting/color (`format_session_row_*`,
//! `state_color_*`, `colorize_*`, `picker_use_color_*`).

use trusty_mpm::client::ManagedSessionSummary;

use super::{LaunchNewRequest, PickerDecision, next_launch_slot};
use crate::commands::session_picker_render::{
    StateColor, colorize, command_legend, format_session_row, picker_use_color,
    restart_confirm_hint, session_color, state_color, table_use_color,
};

/// [`super::parse_picker_choice`] with the pre-#3552 bare-Enter target.
///
/// Why: #3552 gave the parser a `default_idx` so `[s]`/`/<text>` can reorder
/// the menu without repointing what Enter does. Every test below predates the
/// pin and asserts the `default_idx = 0` behavior it always asserted, so the
/// shim states that once here rather than repeating a literal `0` at each call.
fn parse_picker_choice(
    line: &str,
    sessions: &[ManagedSessionSummary],
    first_needs_restart: bool,
) -> PickerDecision {
    super::parse_picker_choice(line, sessions, 0, first_needs_restart)
}

/// Minimal `ManagedSessionSummary` fixture with a given `slot`.
fn session(name: &str, state: &str, slot: u32) -> ManagedSessionSummary {
    ManagedSessionSummary {
        id: format!("{name}-id"),
        name: name.to_string(),
        state: state.to_string(),
        persisted_state: None,
        workspace_path: None,
        repo_url: None,
        branch: None,
        created_at: None,
        last_activity_at: None,
        pending_decision: None,
        proposed_default: None,
        source_id: None,
        task: None,
        cwd: None,
        claude_session_id: None,
        deliverable_id: None,
        pane_id: None,
        injection_status: None,
        unresumable: false,
        stale_assets: false,
        stale_assets_unchecked: false,
        attached: false,
        slot,
        deleted: false,
        auto_resume_parked: None,
        kind: None,
    }
}

// ── next_launch_slot (#3723 duplicate-index fix) ────────────────────────────

#[test]
fn next_launch_slot_matches_ascending_order() {
    let sessions = vec![session("s1", "active", 1), session("s2", "active", 2)];
    assert_eq!(next_launch_slot(&sessions), 3);
}

#[test]
fn next_launch_slot_survives_recency_reorder() {
    // Simulates the exact defect: `sort_sessions(Recent)` can put a
    // LOW-slot session last. The pre-fix `sessions.last().slot + 1`
    // computed 12 (colliding with the real session at slot 12); the fix
    // must use the true maximum across the whole slice regardless of order.
    let sessions = vec![
        session("s31", "active", 31),
        session("s12", "active", 12),
        session("s5", "active", 5), // least-recently-active, sorted last
    ];
    assert_eq!(
        next_launch_slot(&sessions),
        32,
        "must be (max slot)+1, not (last element's slot)+1"
    );
}

#[test]
fn next_launch_slot_survives_alpha_reorder() {
    // Alpha-sorted: "s12" < "s31" < "s5" lexicographically — slot 5 lands
    // last even though it is the LOWEST slot in the list.
    let sessions = vec![
        session("s12", "active", 12),
        session("s31", "active", 31),
        session("s5", "active", 5),
    ];
    assert_eq!(next_launch_slot(&sessions), 32);
}

#[test]
fn next_launch_slot_empty_sessions_is_one() {
    assert_eq!(next_launch_slot(&[]), 1);
}

#[test]
fn next_launch_slot_stale_slots_uses_positional_fallback() {
    // #3678 shape: every slot decodes to the `0` sentinel — positional
    // fallback (len + 1), unaffected by this fix (no real slots to collide
    // with).
    let sessions = vec![session("s1", "active", 0), session("s2", "active", 0)];
    assert_eq!(next_launch_slot(&sessions), 3);
}

#[test]
fn parse_picker_choice_launch_new_uses_max_slot_after_reorder() {
    // End-to-end through the public parse seam: typing the OLD (buggy)
    // "next slot" number must now resolve to the EXISTING session at that
    // slot, never to `LaunchNew` — proving the duplicate-`[N]` defect is
    // gone from the parse side too.
    let sessions = vec![
        session("s31", "active", 31),
        session("s12", "active", 12),
        session("s5", "active", 5),
    ];
    assert_eq!(
        parse_picker_choice("31", &sessions, false),
        PickerDecision::Resume(0),
        "31 must resolve to the real session at that slot, not collide with launch-new"
    );
    assert_eq!(
        parse_picker_choice("32", &sessions, false),
        PickerDecision::LaunchNew(LaunchNewRequest::unnamed())
    );
}

// ── PickerDecision::View parsing (#3552) ────────────────────────────────────

/// The sort key reaches the picker's own parser, not just the view module's.
#[test]
fn parse_picker_choice_s_cycles_the_sort_order() {
    let sessions = vec![session("s1", "active", 1)];
    assert_eq!(
        parse_picker_choice("s", &sessions, false),
        PickerDecision::View(crate::commands::session_picker_view::ViewCommand::CycleSort)
    );
}

/// `/<text>` is a filter, not a session name — and `r`/`d`/`n`/numeric parsing
/// must not have claimed it first.
#[test]
fn parse_picker_choice_slash_sets_the_filter() {
    let sessions = vec![session("s1", "active", 1)];
    assert_eq!(
        parse_picker_choice("/auth", &sessions, false),
        PickerDecision::View(
            crate::commands::session_picker_view::ViewCommand::SetFilter("auth".to_string())
        )
    );
}

// ── PickerDecision::Rename parsing (#3724) ──────────────────────────────────

#[test]
fn parse_picker_choice_rename_no_space_between_prefix_and_number() {
    let sessions = vec![session("s1", "active", 1)];
    assert_eq!(
        parse_picker_choice("r1 new-name", &sessions, false),
        PickerDecision::Rename(0, "new-name".to_string())
    );
}

#[test]
fn parse_picker_choice_rename_space_between_prefix_and_number() {
    let sessions = vec![session("s1", "active", 1)];
    assert_eq!(
        parse_picker_choice("r 1 new-name", &sessions, false),
        PickerDecision::Rename(0, "new-name".to_string())
    );
}

#[test]
fn parse_picker_choice_rename_uppercase_prefix() {
    let sessions = vec![session("s1", "active", 1)];
    assert_eq!(
        parse_picker_choice("R1 new-name", &sessions, false),
        PickerDecision::Rename(0, "new-name".to_string())
    );
}

#[test]
fn parse_picker_choice_rename_trims_and_joins_multiword_name() {
    let sessions = vec![session("s1", "active", 1)];
    assert_eq!(
        parse_picker_choice("r1   my new name  \n", &sessions, false),
        PickerDecision::Rename(0, "my new name".to_string())
    );
}

#[test]
fn parse_picker_choice_rename_missing_name_is_unrecognised() {
    let sessions = vec![session("s1", "active", 1)];
    assert_eq!(
        parse_picker_choice("r1", &sessions, false),
        PickerDecision::Unrecognised
    );
}

#[test]
fn parse_picker_choice_rename_whitespace_only_name_is_unrecognised() {
    let sessions = vec![session("s1", "active", 1)];
    assert_eq!(
        parse_picker_choice("r1    ", &sessions, false),
        PickerDecision::Unrecognised
    );
}

#[test]
fn parse_picker_choice_rename_unknown_slot_is_unrecognised() {
    let sessions = vec![session("s1", "active", 1)];
    assert_eq!(
        parse_picker_choice("r99 new-name", &sessions, false),
        PickerDecision::Unrecognised
    );
}

#[test]
fn parse_picker_choice_rename_non_numeric_slot_is_unrecognised() {
    let sessions = vec![session("s1", "active", 1)];
    assert_eq!(
        parse_picker_choice("rabc new-name", &sessions, false),
        PickerDecision::Unrecognised
    );
}

#[test]
fn parse_picker_choice_rename_deleted_slot_is_slot_deleted() {
    let mut gone = session("gone", "deleted", 3);
    gone.deleted = true;
    let sessions = vec![gone];
    assert_eq!(
        parse_picker_choice("r3 new-name", &sessions, false),
        PickerDecision::SlotDeleted(0)
    );
}

// ── d <glob> bulk delete parsing (#5539) ────────────────────────────────────

#[test]
fn parse_picker_choice_glob_delete_recognised() {
    let sessions = vec![session("tm-test-01", "stopped", 1)];
    let parsed = parse_picker_choice("d tm-test-*", &sessions, false);
    match parsed {
        PickerDecision::DeleteGlob(req) => {
            assert_eq!(req.pattern, "tm-test-*");
            assert!(!req.dry_run);
        }
        other => panic!("expected DeleteGlob, got {other:?}"),
    }
}

#[test]
fn parse_picker_choice_glob_delete_dry_run() {
    let sessions = vec![session("tm-test-01", "stopped", 1)];
    match parse_picker_choice("d tm-test-* --dry-run", &sessions, false) {
        PickerDecision::DeleteGlob(req) => assert!(req.dry_run),
        other => panic!("expected DeleteGlob, got {other:?}"),
    }
}

#[test]
fn parse_picker_choice_glob_delete_does_not_shadow_slot_delete() {
    // `d1` stays the single-slot delete — the numeric form is tried first.
    let sessions = vec![session("s1", "stopped", 1)];
    assert_eq!(
        parse_picker_choice("d1", &sessions, false),
        PickerDecision::Delete(0)
    );
}

#[test]
fn parse_picker_choice_glob_delete_typo_stays_unrecognised() {
    // The property the metacharacter gate exists for: a mistyped `delete` must
    // NOT become a bulk destructive action against a session named `elete`.
    let sessions = vec![session("elete", "stopped", 1)];
    assert_eq!(
        parse_picker_choice("delete", &sessions, false),
        PickerDecision::Unrecognised
    );
    // An unknown slot number likewise stays inert rather than globbing.
    assert_eq!(
        parse_picker_choice("d99", &sessions, false),
        PickerDecision::Unrecognised
    );
}

// ── session_picker_render: colorize / state_color ───────────────────────────

#[test]
fn colorize_wraps_when_color_enabled() {
    assert_eq!(
        colorize("active", StateColor::Green, true),
        "\x1b[32mactive\x1b[0m"
    );
}

#[test]
fn colorize_plain_when_color_disabled() {
    assert_eq!(colorize("active", StateColor::Green, false), "active");
}

#[test]
fn colorize_plain_variant_never_wraps_even_with_color_enabled() {
    assert_eq!(
        colorize("weird-state", StateColor::Plain, true),
        "weird-state"
    );
}

#[test]
fn state_color_attached_wins_over_active() {
    assert_eq!(state_color("active", true), StateColor::AttachedCyan);
    assert_eq!(state_color("stopped", true), StateColor::AttachedCyan);
}

#[test]
fn state_color_maps_known_states() {
    assert_eq!(state_color("active", false), StateColor::Green);
    // #8506: the owner's mapping replaces #3730's stopped=dim; provisioning
    // leaves yellow so it cannot read as stopped.
    assert_eq!(state_color("stopped", false), StateColor::Yellow);
    assert_eq!(state_color("errored", false), StateColor::Red);
    assert_eq!(state_color("provisioning", false), StateColor::Blue);
    // #8506 owner ruling: decommissioned is dim/gray, never uncolored or red.
    assert_eq!(state_color("decommissioned", false), StateColor::Dim);
}

/// Why (#8506): one row mapping feeds the static table, the TUI and the
/// numbered picker, so each state the owner named is pinned on it directly.
/// Test: this test.
#[test]
fn session_color_maps_every_state() {
    let cases = [
        ("active", StateColor::Green),
        ("stopped", StateColor::Yellow),
        ("errored", StateColor::Red),
        ("provisioning", StateColor::Blue),
        ("decommissioned", StateColor::Dim),
        ("deleted", StateColor::Plain),
        ("some-future-state", StateColor::Plain),
    ];
    for (state, want) in cases {
        assert_eq!(
            session_color(&session("tm-x-01", state, 3)),
            want,
            "state {state}"
        );
    }
    let mut attached = session("tm-x-01", "active", 3);
    attached.attached = true;
    assert_eq!(session_color(&attached), StateColor::AttachedCyan);
}

/// Why (#8506): the `[dead]` marker (`unresumable`) and a slot tombstone are
/// the owner's "dead"; they must read red whatever state or attachment the
/// record also carries.
/// Test: this test.
#[test]
fn session_color_dead_wins_over_state_and_attached() {
    for state in ["active", "stopped", "provisioning"] {
        let mut unresumable = session("tm-x-01", state, 3);
        unresumable.unresumable = true;
        unresumable.attached = true;
        assert_eq!(session_color(&unresumable), StateColor::Red, "{state}");
        let mut tombstone = session("tm-x-01", state, 3);
        tombstone.deleted = true;
        assert_eq!(session_color(&tombstone), StateColor::Red, "{state}");
    }
}

#[test]
fn state_color_unknown_state_is_plain() {
    assert_eq!(state_color("some-future-state", false), StateColor::Plain);
}

#[test]
fn picker_use_color_requires_tty() {
    assert!(!picker_use_color(false));
}

/// Why: proves the NO_COLOR branch (previously untested — code-critic
/// finding on PR #3730), not just the TTY gate. Mutating a process-global
/// env var races any other test that reads/sets `NO_COLOR` concurrently
/// (the exact bug class fixed in commit 4716e4a5) — no other test in this
/// crate touches `NO_COLOR` today, but `#[serial_test::serial(no_color_env)]`
/// plus save/restore around the mutation keeps this test race-safe even if
/// one is added later, mirroring the `ENV_MUTEX`/save-restore convention in
/// `tests_behavior_c_tests.rs`.
#[test]
#[serial_test::serial(no_color_env)]
fn picker_use_color_false_when_no_color_set_even_on_tty() {
    let prev = std::env::var_os("NO_COLOR");
    // SAFETY: serialized via #[serial(no_color_env)] against every other
    // test in this named group; no other test in the crate touches
    // NO_COLOR, so this is the sole mutator of this key process-wide.
    unsafe {
        std::env::set_var("NO_COLOR", "1");
    }
    let result = picker_use_color(true);
    unsafe {
        match prev {
            Some(v) => std::env::set_var("NO_COLOR", v),
            None => std::env::remove_var("NO_COLOR"),
        }
    }
    assert!(
        !result,
        "NO_COLOR must disable color even when stderr is a TTY"
    );
}

/// Why: the `tm ls` table writes to STDOUT via `println!`, so reusing the
/// picker's stderr gate would leak ANSI escapes into `tm ls | grep` whenever
/// stderr stayed a TTY. This pins that the table gate keys off its own stream.
#[test]
fn table_use_color_requires_stdout_tty() {
    assert!(!table_use_color(false));
    // With NO_COLOR unset (the default in this process) a TTY enables color.
    if std::env::var_os("NO_COLOR").is_none() {
        assert!(table_use_color(true));
    }
}

/// Why: the table gate must honour `NO_COLOR` identically to the picker gate —
/// any set value, including the empty string, disables color
/// (https://no-color.org). Shares the `no_color_env` serial group and the
/// save/restore convention with `picker_use_color_false_when_no_color_set_even_on_tty`.
#[test]
#[serial_test::serial(no_color_env)]
fn table_use_color_false_when_no_color_set_even_on_tty() {
    let prev = std::env::var_os("NO_COLOR");
    // SAFETY: serialized via #[serial(no_color_env)] against every other test
    // in this named group.
    unsafe {
        std::env::set_var("NO_COLOR", "");
    }
    let result = table_use_color(true);
    unsafe {
        match prev {
            Some(v) => std::env::set_var("NO_COLOR", v),
            None => std::env::remove_var("NO_COLOR"),
        }
    }
    assert!(
        !result,
        "an EMPTY NO_COLOR must still disable color on a stdout TTY"
    );
}

// ── session_picker_render: format_session_row (#3723 verb removal) ─────────

#[test]
fn format_session_row_normal_is_verbless() {
    let s = session("tm-proj-01", "active", 5);
    let row = format_session_row(5, &s, false);
    assert_eq!(row, "[5] tm-proj-01 (active)");
    assert!(!row.contains("resume"));
    assert!(!row.contains("restart"));
}

#[test]
fn format_session_row_stopped_is_verbless() {
    let s = session("tm-proj-01", "stopped", 11);
    let row = format_session_row(11, &s, false);
    assert_eq!(row, "[11] tm-proj-01 (stopped)");
    assert!(!row.contains("restart"));
}

#[test]
fn format_session_row_attached_uses_attached_word() {
    let mut s = session("tm-proj-01", "active", 2);
    s.attached = true;
    let row = format_session_row(2, &s, false);
    assert_eq!(row, "[2] tm-proj-01 (attached)");
}

#[test]
fn format_session_row_deleted_notice() {
    let mut s = session("gone", "deleted", 7);
    s.deleted = true;
    let row = format_session_row(7, &s, false);
    assert_eq!(row, "[7] -- deleted --");
}

#[test]
fn format_session_row_unresumable_notice() {
    let mut s = session("tm-dead-01", "stopped", 9);
    s.unresumable = true;
    let row = format_session_row(9, &s, false);
    assert_eq!(
        row,
        "[9] tm-dead-01 (stopped) — DEAD: workspace removed; use [d9] to remove the record"
    );
}

#[test]
fn format_session_row_color_enabled_wraps_state_word_only() {
    let s = session("tm-proj-01", "active", 5);
    let row = format_session_row(5, &s, true);
    assert_eq!(row, "[5] tm-proj-01 (\x1b[32mactive\x1b[0m)");
}

#[test]
fn format_session_row_color_disabled_is_plain_text() {
    let s = session("tm-proj-01", "active", 5);
    let row = format_session_row(5, &s, false);
    assert!(
        !row.contains('\x1b'),
        "no ANSI escapes when use_color is false"
    );
}

// ── command_legend (#4965) ────────────────────────────────────────────────────

/// The no-sessions menu offers bare Enter and `n <name>`, and nothing to
/// delete or rename — there is no session to target.
#[test]
fn command_legend_empty_menu_shape() {
    let lines = command_legend(None);
    let keys: Vec<&str> = lines
        .iter()
        .map(|l| l.split("  ").next().unwrap())
        .collect();
    // #3552: `[s]`/`[/<text>]` are in BOTH shapes — the empty menu is reachable
    // by filtering every row away, so that is where `[/]` matters most.
    assert_eq!(
        keys,
        ["[Enter]", "[n <name>]", "[s]", "[/<text>]", "[ls]", "[q]"]
    );
}

/// The populated menu leads with the launch slot and adds the delete/rename
/// rows.
#[test]
fn command_legend_populated_menu_shape() {
    let lines = command_legend(Some(4));
    let keys: Vec<&str> = lines
        .iter()
        .map(|l| l.split("  ").next().unwrap())
        .collect();
    assert_eq!(
        keys,
        [
            "[4]",
            "[n <name>]",
            "[d<N>]",
            "[d <glob>]",
            "[r<N> <new-name>]",
            // #3552: the in-picker sort/filter keys.
            "[s]",
            "[/<text>]",
            "[ls]",
            "[q]"
        ]
    );
}

/// #5539: the bulk-delete row must name the pattern form AND the preview flag —
/// an operator who cannot see `--dry-run` on the menu will not discover it, and
/// a bulk destructive command whose preview is undiscoverable is the wrong
/// default.
#[test]
fn command_legend_glob_row_advertises_dry_run() {
    let lines = command_legend(Some(4));
    let row = lines
        .iter()
        .find(|l| l.starts_with("[d <glob>]"))
        .expect("the glob-delete row must be present");
    assert!(
        row.contains("--dry-run"),
        "row must offer the preview: {row}"
    );
    assert!(
        row.contains("stopped"),
        "row must say it only deletes stopped sessions: {row}"
    );
}

/// #4965: `n <name>` must be self-documenting. `r1 <name>` right below it
/// takes a VERBATIM full session name while `n <name>` takes a leaf the daemon
/// wraps as `tm-<name>-NN` — adjacent rows with an unexplained `<name>` each
/// read as interchangeable.
#[test]
fn command_legend_n_row_names_the_resulting_session_shape() {
    let lines = command_legend(Some(4));
    let n_row = lines
        .iter()
        .find(|l| l.starts_with("[n <name>]"))
        .expect("the n row must be present");
    assert!(
        n_row.contains("tm-<name>-NN"),
        "the n row must spell out the name it produces: {n_row}"
    );
}

/// #5773: the `n` row must advertise `--worktree`. An operator who cannot see
/// the flag on the menu will not discover it, and the picker is the surface
/// where the choice between sharing the checkout and isolating is made.
#[test]
fn command_legend_n_row_offers_the_worktree_flag() {
    for lines in [command_legend(None), command_legend(Some(4))] {
        let n_row = lines
            .iter()
            .find(|l| l.starts_with("[n <name>]"))
            .expect("the n row must be present");
        assert!(
            n_row.contains("--worktree"),
            "the n row must offer the isolation flag: {n_row}"
        );
    }
}

/// #4965 (LOW): BOTH menus are padded to the same column. The empty variant
/// was aligned and the populated one — the common case — was left ragged.
#[test]
fn command_legend_columns_are_aligned() {
    for lines in [command_legend(None), command_legend(Some(12))] {
        let offsets: Vec<usize> = lines
            .iter()
            .map(|l| {
                l.find("launch")
                    .or_else(|| l.find("delete"))
                    .or_else(|| l.find("rename"))
                    .or_else(|| l.find("re-print"))
                    // #3552: the sort/filter rows' description verbs.
                    .or_else(|| l.find("cycle"))
                    .or_else(|| l.find("filter"))
                    .or_else(|| l.find("quit"))
                    .expect("every row has a description")
            })
            .collect();
        assert!(
            offsets.windows(2).all(|w| w[0] == w[1]),
            "descriptions must all start in the same column: {lines:#?}"
        );
    }
}

/// #4965: both #2148 restart prompts must name the key that actually declines.
///
/// Why: they used to read as a yes/no question while naming no refusal key at
/// all, so the operator had to invent one. `q` is the only key that leaves the
/// prompt without acting.
#[test]
fn restart_confirm_hint_names_the_refusal_key() {
    let hint = restart_confirm_hint(3);
    assert!(hint.contains("[3] confirms"), "confirm key missing: {hint}");
    assert!(hint.contains("[q] quits"), "refusal key missing: {hint}");
}

/// #4965: the hint must say what `n` does, because `n` spawns a session.
///
/// Why: this is the whole point of the wording fix. `n` is the universal "no"
/// AND the launch-new alias, so a prompt that reads as yes/no and stays silent
/// about `n` invites an operator to spawn a session while declining one. The
/// grammar is deliberately unchanged (`guided_picker_n_launches_new_unnamed`
/// still pins `n` -> `LaunchNew(None)`); only the prompt disowns the reading.
#[test]
fn restart_confirm_hint_disowns_n_as_no() {
    let hint = restart_confirm_hint(1);
    assert!(hint.contains("[n]"), "`n` unmentioned: {hint}");
    assert!(hint.contains("not \"no\""), "`n` not disowned: {hint}");
    assert!(
        hint.contains("NEW session"),
        "`n`'s real effect unstated: {hint}"
    );
}

// ── #5007: the degraded-store banner every listing surface prints ───────────

/// Why (#5007): on 2026-08-06 `tm ls` printed a normal-looking fleet while the
/// store was corrupt and every write was failing. The banner is what makes that
/// impossible — but a banner that fired on healthy listings would be noise on
/// every invocation, so the healthy case has to be silent.
/// What: a response with no `store_health` field produces no banner.
/// Test: this test.
#[test]
fn store_banner_is_absent_for_a_healthy_listing() {
    assert_eq!(
        super::store_degradation_banner(r#"{"sessions":[]}"#),
        None,
        "a healthy listing must print nothing"
    );
}

/// Why: a body this client cannot parse is not evidence that the STORE is
/// broken, and claiming so would send an operator to repair the wrong thing.
/// What: unparseable input produces no banner.
/// Test: this test.
#[test]
fn store_banner_is_absent_for_an_unparseable_body() {
    assert_eq!(super::store_degradation_banner("not json"), None);
}

/// Why: the corrupt case is the incident. The banner has to say the list is a
/// stale in-memory copy AND carry the daemon's message, which is what names the
/// file, the byte offset, and the repair command.
/// What: asserts both halves appear.
/// Test: this test.
#[test]
fn store_banner_names_corruption_and_the_repair_command() {
    let raw = r#"{"sessions":[],"store_health":{"message":"/x/sessions.json is corrupt: trailing characters (line 3755, column 2); a complete JSON document ends at byte 145090 of 146201, followed by 1111 trailing byte(s). Repair with `tm repair session-store`","corrupt":true,"observed_at":"2026-08-06T09:01:17Z"}}"#;
    let banner = super::store_degradation_banner(raw).expect("a corrupt store must warn");
    assert!(banner.contains("CORRUPT"), "{banner}");
    assert!(
        banner.contains("every write to the store is failing"),
        "{banner}"
    );
    assert!(banner.contains("byte 145090"), "{banner}");
    assert!(banner.contains("tm repair session-store"), "{banner}");
}

/// Why (#5027 review): the banner's STREAM is the whole contract. `tm ls
/// --json` writes the daemon's response body to stdout, so a banner on stdout
/// makes that JSON unparseable for every consumer. Nothing asserted it —
/// changing `eprintln!` to `println!` left the suite at `10 passed; 0 failed`
/// with the banner on stdout.
/// What: re-runs THIS test as a child process (the only way to observe the two
/// real streams — under `cargo test` libtest intercepts them) and asserts the
/// banner reaches stderr and never stdout.
/// Test: this test.
#[test]
fn store_banner_goes_to_stderr_so_json_stays_machine_readable() {
    const CHILD: &str = "TM_5027_BANNER_CHILD";
    const MARKER: &str = "CORRUPT";
    let raw = r#"{"sessions":[],"store_health":{"message":"/x/sessions.json is corrupt","corrupt":true,"observed_at":"2026-08-06T09:01:17Z"}}"#;

    if std::env::var_os(CHILD).is_some() {
        super::warn_if_store_degraded(raw);
        return;
    }

    // libtest names tests relative to the crate root, without the crate name.
    let module = module_path!();
    let module = module.split_once("::").map_or(module, |(_, rest)| rest);
    let name = format!("{module}::store_banner_goes_to_stderr_so_json_stays_machine_readable");
    let out = std::process::Command::new(std::env::current_exe().expect("test binary path"))
        .args([&name, "--exact", "--nocapture", "--test-threads", "1"])
        .env(CHILD, "1")
        .output()
        .expect("re-run this test as a child process");

    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stdout.contains("1 passed"),
        "the child must have actually run the case; stdout: {stdout}\nstderr: {stderr}"
    );
    assert!(
        stderr.contains(MARKER),
        "the banner must go to stderr; stderr: {stderr}"
    );
    assert!(
        !stdout.contains(MARKER),
        "the banner must NEVER reach stdout — `tm ls --json` writes the response body \
         there; stdout: {stdout}"
    );
}

/// Why: a transient read failure is genuinely different — the fallback may
/// already have cleared by the next listing — so the banner must say "stale",
/// not "corrupt", or it would send an operator to repair a healthy file.
/// What: asserts the non-corrupt wording.
/// Test: this test.
#[test]
fn store_banner_marks_a_transient_read_failure_as_stale_not_corrupt() {
    let raw = r#"{"sessions":[],"store_health":{"message":"session store I/O error: nfs hiccup","corrupt":false,"observed_at":"2026-08-06T09:01:17Z"}}"#;
    let banner = super::store_degradation_banner(raw).expect("a degraded store must warn");
    assert!(banner.contains("may be stale"), "{banner}");
    assert!(
        !banner.contains("CORRUPT"),
        "a transient failure must not be called corruption: {banner}"
    );
}

// ── #6753: the picker's FIRST menu is ordered like every later one ──────────

/// A session fixture with the state, slot and attachment the ordering turns on.
///
/// Why: the defect is only visible when `attached` and `slot` disagree about
/// position — the daemon hands the list in ascending slot order and the attached
/// session is usually the HIGHEST slot, so it printed last.
fn ordered_session(
    name: &str,
    state: &str,
    slot: u32,
    attached: bool,
    last_activity_at: &str,
) -> ManagedSessionSummary {
    let mut s = session(name, state, slot);
    s.attached = attached;
    s.last_activity_at = Some(last_activity_at.to_string());
    s
}

/// The daemon's own answer shape: ascending slot, attached session last.
///
/// Why: `daemon/managed_routes/summary.rs` returns managed sessions in
/// ascending-slot order, so this is exactly what `guided::try_show_picker` used
/// to hand straight to the first render. The timestamps run OPPOSITE to the slot
/// order so the recency half of the sort is exercised too: the daemon's order is
/// least-recent-first, which is the order the operator was shown.
fn daemon_ascending_slot_order() -> Vec<ManagedSessionSummary> {
    vec![
        ordered_session("oldest", "stopped", 1, false, "2026-09-01T00:00:00Z"),
        ordered_session("middle", "stopped", 2, false, "2026-09-02T00:00:00Z"),
        ordered_session("attached-now", "active", 3, true, "2026-09-03T00:00:00Z"),
    ]
}

#[test]
fn prepare_menu_orders_the_first_render_like_every_later_one() {
    // #6753: `prepare_menu` is what `run_tty_picker` renders from, so asserting
    // on it asserts on the FIRST menu. Pre-fix the first render used this vec
    // unchanged and the attached session printed LAST at slot 3.
    let scope = super::PickerScope::project("owner/repo", "/repo");
    let menu =
        crate::commands::session_picker_order::prepare_menu(daemon_ascending_slot_order(), &scope);
    let names: Vec<&str> = menu.sessions.iter().map(|s| s.name.as_str()).collect();
    assert_eq!(
        names,
        vec!["attached-now", "middle", "oldest"],
        "attached leads, then the rest by recency — the same order every later menu uses"
    );
    assert_eq!(
        menu.sessions[0].slot, 3,
        "and each row keeps its stable daemon slot"
    );
}

#[test]
fn prepare_menu_bare_enter_targets_the_attached_session() {
    // #6753's reported effect. `first_needs_restart` drives both the default hint
    // and `parse_picker_choice`'s bare-Enter branch, and it reads position 0: on
    // the un-normalized vec that was `oldest`, a STOPPED session, so bare Enter
    // fired `ConfirmRestart` while the hint read "resume most recent".
    let scope = super::PickerScope::project("owner/repo", "/repo");
    let raw = daemon_ascending_slot_order();
    assert!(
        crate::commands::guided_resume::needs_restart(&raw[0].state),
        "fixture check: position 0 of the daemon's order is a stopped session"
    );

    let menu = crate::commands::session_picker_order::prepare_menu(raw, &scope);
    assert!(
        !menu.first_needs_restart,
        "position 0 must be resumable, so bare Enter resumes rather than restarting"
    );
    assert_eq!(
        super::decide_for_index(&menu.sessions, 0, menu.first_needs_restart),
        PickerDecision::Resume(0),
        "bare Enter must resume the attached session, not confirm a restart of the oldest"
    );
}

#[test]
fn prepare_menu_is_idempotent() {
    // #6753's closure condition: the first menu is ordered identically to every
    // subsequent one. The loop prepares on every iteration, including after a
    // `continue` that skipped the re-fetch, so preparing twice must not move a
    // row — otherwise the list would reorder under the operator exactly as it did
    // when only the loop bottom normalized.
    let scope = super::PickerScope::project("owner/repo", "/repo");
    let once =
        crate::commands::session_picker_order::prepare_menu(daemon_ascending_slot_order(), &scope);
    let names_once: Vec<String> = once.sessions.iter().map(|s| s.name.clone()).collect();
    let twice = crate::commands::session_picker_order::prepare_menu(once.sessions, &scope);
    let names_twice: Vec<String> = twice.sessions.iter().map(|s| s.name.clone()).collect();
    assert_eq!(names_once, names_twice);
    assert_eq!(once.new_idx, twice.new_idx);
    assert_eq!(once.first_needs_restart, twice.first_needs_restart);
}

#[test]
fn prepare_menu_launch_slot_is_the_maximum_not_the_last() {
    // #3723's guarantee, re-pinned through the seam that now owns it: the reorder
    // `prepare_menu` applies is exactly the one that could make `.last().slot + 1`
    // collide with a real session's slot.
    let scope = super::PickerScope::project("owner/repo", "/repo");
    let menu =
        crate::commands::session_picker_order::prepare_menu(daemon_ascending_slot_order(), &scope);
    assert_eq!(menu.new_idx, 4, "max slot 3, plus one");
    assert!(!menu.stale_slots, "these fixtures carry real slots");
}

#[test]
fn prepare_menu_applies_the_scopes_term_filter() {
    // The filter half of the pair: it ran at the loop bottom too, so the first
    // menu of a filtered `tm ls <term>` showed rows the later menus dropped.
    let scope = super::PickerScope {
        source_id: None,
        repo_url: None,
        sort: super::SessionSortArg::Recent,
        term: Some(super::SessionFilter::visible("attached")),
        selected_id: None,
    };
    let menu =
        crate::commands::session_picker_order::prepare_menu(daemon_ascending_slot_order(), &scope);
    assert_eq!(menu.sessions.len(), 1, "only the matching row survives");
    assert_eq!(menu.sessions[0].name, "attached-now");
}