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
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
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
//! Unit tests for the coordinator TUI skeleton (Child #1).
//!
//! Why: the spec's pure/unit test tier (DOC-13 §9) requires the row-builders,
//! the selection clamp, and the slash-command parse to be verified WITHOUT a
//! terminal or a daemon. These tests exercise exactly that surface.
//! What: covers row construction, `CoordinatorState` selection/history, the
//! `parse_slash` stub (incl. leading-`/` detection), key dispatch branches, and
//! the layout text helpers.
//! Test: this IS the test module.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use super::banner::{
    GLYPH_ACTIVE, GLYPH_UNREACHABLE, HELP_HINT, ProbeOutcome, USER_PALACE, compose_banner,
    ensure_user_palace_at, probe_memory, probe_search,
};
use super::dispatch::{Dispatch, route};
use super::events::{SlashCommand, handle_key, is_quit, parse_slash};
use super::layout::output_tail;
use super::layout::{
    CATALOG_STALE_HINT, CONTROLLER_STATUS, DAEMON_REACHABLE, DAEMON_UNREACHABLE, INPUT_PROMPT,
    STATUS_BAR_HINT, catalog_indicator, daemon_indicator, input_line, status_bar_text,
};
use super::nav::{ListNav, MIN_VISIBLE_ROWS, PAGE_JUMP};
use super::poll::{coord_poll_daemon, coord_session_to_entry};
use super::render::render_result;
use super::rows::{
    COLUMN_SEPARATOR, CONTROLLER_GLYPH, SESSION_GLYPH, active_row_two_col, controller_bullet_row,
    numbered_session_row, session_row, session_short_id,
};
use super::state::{CoordinatorState, INPUT_HISTORY_LIMIT, OUTPUT_LOG_LIMIT, SessionEntry};
use crate::client::result::ManagedSessionView;
use crate::client::{CommandResult, CoordinatorSession, DaemonClient, TrustyCommand};

/// Render a ratatui `Line` to a flat string for content assertions.
fn line_text(line: &ratatui::text::Line<'_>) -> String {
    line.spans.iter().map(|s| s.content.as_ref()).collect()
}

fn key(code: KeyCode) -> KeyEvent {
    KeyEvent::new(code, KeyModifiers::NONE)
}

// ---- rows -----------------------------------------------------------------

#[test]
fn controller_bullet_row_renders_glyph_label_and_status() {
    let line = controller_bullet_row("idle · ready", false);
    let text = line_text(&line);
    assert!(
        text.starts_with(CONTROLLER_GLYPH),
        "expected leading bullet: {text}"
    );
    assert!(text.contains("controller"), "missing label: {text}");
    assert!(text.contains("idle · ready"), "missing status: {text}");
}

#[test]
fn controller_bullet_row_selected_is_still_well_formed() {
    // The selected variant changes style, not text content.
    let plain = line_text(&controller_bullet_row("ready", false));
    let selected = line_text(&controller_bullet_row("ready", true));
    assert_eq!(plain, selected);
}

#[test]
fn session_row_renders_bullet_and_prefix() {
    let text = line_text(&session_row("4f9ca1b2", "aipowerranking", "Active"));
    assert!(
        text.starts_with(SESSION_GLYPH),
        "expected hollow bullet: {text}"
    );
    assert!(text.contains("4f9ca1b2"), "missing short id: {text}");
    assert!(text.contains("aipowerranking"), "missing prefix: {text}");
    assert!(text.contains("Active"), "missing status: {text}");
}

#[test]
fn active_row_two_col_splits_on_bar() {
    let text = line_text(&active_row_two_col("4f9ca1b2", "Running tests"));
    assert!(
        text.contains(COLUMN_SEPARATOR),
        "missing column separator: {text}"
    );
    // The id is left of the bar, the summary right of it.
    let (left, right) = text
        .split_once(COLUMN_SEPARATOR)
        .expect("a bar separator must be present");
    assert!(left.contains("4f9ca1b2"), "id not in left column: {left}");
    assert!(
        right.contains("Running tests"),
        "summary not in right column: {right}"
    );
}

#[test]
fn numbered_session_row_prefixes_number() {
    // STUI-1: the list is numbered (1, 2, 3, …); the row text must lead with the
    // 1-based list number while still carrying the standard session spans.
    let text = line_text(&numbered_session_row(
        3,
        "4f9ca1b2",
        "aipowerranking",
        "Active",
    ));
    assert!(
        text.trim_start().starts_with("3."),
        "expected a leading list number `3.`: {text}"
    );
    // The bullet, id, prefix, and status are still present after the number.
    assert!(text.contains(SESSION_GLYPH), "missing bullet: {text}");
    assert!(text.contains("4f9ca1b2"), "missing short id: {text}");
    assert!(text.contains("aipowerranking"), "missing prefix: {text}");
    assert!(text.contains("Active"), "missing status: {text}");
}

#[test]
fn session_short_id_truncates() {
    assert_eq!(session_short_id("4f9ca1b2deadbeef"), "4f9ca1b2");
    // Shorter-than-8 ids are returned whole.
    assert_eq!(session_short_id("abc"), "abc");
    assert_eq!(session_short_id(""), "");
}

// ---- nav: pure ListNav navigation (STUI-1) --------------------------------

#[test]
fn min_visible_rows_is_five() {
    // The spec fixes a five-row floor for the list viewport.
    assert_eq!(MIN_VISIBLE_ROWS, 5);
    // Page scrolling jumps by a page (== the visible-row floor in the pure model).
    assert_eq!(PAGE_JUMP, MIN_VISIBLE_ROWS);
}

#[test]
fn nav_default_selects_controller_row() {
    // The list always has at least the controller row; row 0 is selected and the
    // offset starts at the top.
    let nav = ListNav::default();
    assert_eq!(nav.selected(), 0);
    assert_eq!(nav.offset(), 0);
}

#[test]
fn nav_up_down_saturate() {
    // A 4-row list (len 4): down saturates at row 3, up saturates at row 0.
    let mut nav = ListNav::default();
    nav.sync_len(4);
    nav.up(); // already at 0
    assert_eq!(nav.selected(), 0, "up saturates at the top");
    nav.down();
    nav.down();
    nav.down();
    assert_eq!(nav.selected(), 3, "stepped to the last row");
    nav.down(); // saturates
    assert_eq!(nav.selected(), 3, "down saturates at the last row");
    nav.up();
    assert_eq!(nav.selected(), 2);
}

#[test]
fn nav_select_clamps_into_bounds() {
    // `select` past the end clamps to the last valid row.
    let mut nav = ListNav::default();
    nav.sync_len(3); // rows 0..=2
    nav.select(99);
    assert_eq!(nav.selected(), 2, "select clamps to the last row");
    nav.select(1);
    assert_eq!(nav.selected(), 1, "an in-bounds select is honoured");
}

#[test]
fn page_down_jumps_by_page_size() {
    // A long list (len 20): Page-Down advances by exactly PAGE_JUMP rows.
    let mut nav = ListNav::default();
    nav.sync_len(20);
    nav.page_down();
    assert_eq!(nav.selected(), PAGE_JUMP, "page down jumps by a page");
}

#[test]
fn page_up_jumps_by_page_size() {
    let mut nav = ListNav::default();
    nav.sync_len(20);
    nav.select(2 * PAGE_JUMP);
    nav.page_up();
    assert_eq!(nav.selected(), PAGE_JUMP, "page up jumps back by a page");
}

#[test]
fn page_down_saturates_at_bottom() {
    // A short list (len 3): Page-Down cannot move past the last row.
    let mut nav = ListNav::default();
    nav.sync_len(3); // rows 0..=2
    nav.page_down();
    assert_eq!(nav.selected(), 2, "page down saturates at the last row");
}

#[test]
fn page_up_saturates_at_top() {
    let mut nav = ListNav::default();
    nav.sync_len(20);
    nav.select(2); // within one page of the top
    nav.page_up();
    assert_eq!(nav.selected(), 0, "page up saturates at the top");
}

#[test]
fn nav_sync_len_preserves_selection_and_offset() {
    // A refresh that GROWS (or keeps) the list must leave the selection AND the
    // scroll offset exactly where the operator left them.
    let mut nav = ListNav::default();
    nav.sync_len(20);
    nav.select(12);
    // Force a non-zero offset by scrolling the viewport via the render seam.
    *nav.state_mut().offset_mut() = 8;
    assert_eq!(nav.selected(), 12);
    assert_eq!(nav.offset(), 8);

    // Grow the list: cursor + offset are untouched (both still in bounds).
    nav.sync_len(25);
    assert_eq!(nav.selected(), 12, "grown list preserves the selection");
    assert_eq!(nav.offset(), 8, "grown list preserves the scroll offset");

    // Unchanged length: still preserved.
    nav.sync_len(25);
    assert_eq!(nav.selected(), 12);
    assert_eq!(nav.offset(), 8);
}

#[test]
fn nav_sync_len_clamps_on_shrink() {
    // A refresh that SHRINKS the list past the cursor/offset must clamp both
    // inward so neither indexes past the new end.
    let mut nav = ListNav::default();
    nav.sync_len(20);
    nav.select(18);
    *nav.state_mut().offset_mut() = 15;

    // Shrink to 5 rows (0..=4): selection and offset clamp to the last row.
    nav.sync_len(5);
    assert_eq!(
        nav.selected(),
        4,
        "selection clamps to the last row on shrink"
    );
    assert!(
        nav.offset() <= 4,
        "offset clamps within the shrunk list: {}",
        nav.offset()
    );

    // Shrink to the controller-only list (len 1): everything pins to row 0.
    nav.sync_len(1);
    assert_eq!(nav.selected(), 0);
    assert_eq!(nav.offset(), 0);
}

#[test]
fn nav_sync_len_floors_at_one_row() {
    // The controller row always exists, so a zero row_count still yields len 1
    // and a valid row-0 selection (never an underflow).
    let mut nav = ListNav::default();
    nav.sync_len(0);
    assert_eq!(
        nav.selected(),
        0,
        "an empty list still has the controller row"
    );
}

// ---- state: selection clamp (boundary cases) ------------------------------

#[test]
fn clamp_selection_empty_list() {
    // Empty session list: only the controller row exists (row 0).
    let mut state = CoordinatorState::default();
    assert_eq!(state.row_count(), 1);
    state.select_row(9);
    state.clamp_selection();
    assert_eq!(state.selected(), 0, "clamp to the sole controller row");
}

#[test]
fn clamp_selection_single_row() {
    // Controller + exactly one session → valid indices are 0 and 1.
    let mut state = CoordinatorState::default();
    state
        .sessions
        .push(SessionEntry::new("id", "p", "Active", "s"));
    assert_eq!(state.row_count(), 2);
    state.select_row(1);
    state.clamp_selection();
    assert_eq!(state.selected(), 1, "valid selection is preserved");
    state.select_row(5);
    state.clamp_selection();
    assert_eq!(state.selected(), 1, "past-end clamps to last session");
}

#[test]
fn clamp_selection_past_end() {
    let mut state = CoordinatorState::skeleton(); // controller + 2 sessions
    assert_eq!(state.row_count(), 3);
    state.select_row(99);
    state.clamp_selection();
    assert_eq!(state.selected(), 2, "clamps to the last valid row index");
}

#[test]
fn selection_movement_saturates() {
    let mut state = CoordinatorState::skeleton(); // rows 0..=2
    state.select_up(); // already at 0
    assert_eq!(state.selected(), 0);
    state.select_down();
    assert_eq!(state.selected(), 1);
    state.select_down();
    assert_eq!(state.selected(), 2);
    state.select_down(); // saturates at last
    assert_eq!(state.selected(), 2);
    state.select_up();
    assert_eq!(state.selected(), 1);
}

#[test]
fn select_row_clamps_into_bounds() {
    // `select_row` re-syncs the live row count then clamps into 0..row_count.
    let mut state = CoordinatorState::skeleton(); // controller + 2 sessions → rows 0..=2
    state.select_row(1);
    assert_eq!(state.selected(), 1, "an in-bounds row is honoured");
    state.select_row(99);
    assert_eq!(
        state.selected(),
        2,
        "past-end select clamps to the last row"
    );
}

#[test]
fn clamp_selection_preserves_valid_selection() {
    // STUI-1: a refresh that leaves the selection in bounds must NOT move it back
    // to the controller — the operator stays on the row they chose.
    let mut state = CoordinatorState::skeleton(); // rows 0..=2
    state.select_row(2);
    // Simulate a poll that keeps the same number of rows.
    state.clamp_selection();
    assert_eq!(
        state.selected(),
        2,
        "a still-valid selection survives the refresh"
    );

    // A poll that GROWS the list also preserves the selection.
    state
        .sessions
        .push(SessionEntry::new("new", "p", "Active", "s"));
    state.clamp_selection();
    assert_eq!(state.selected(), 2, "grown list keeps the cursor in place");
}

#[test]
fn page_scroll_moves_by_page_and_saturates() {
    // Build a controller + enough sessions that a page jump does not hit the end.
    let mut state = CoordinatorState::live();
    for i in 0..20 {
        state
            .sessions
            .push(SessionEntry::new(format!("id{i}"), "p", "Active", "s"));
    }
    // rows 0..=20 (controller + 20 sessions).
    state.page_down();
    assert_eq!(state.selected(), PAGE_JUMP, "page down jumps by a page");
    state.page_down();
    assert_eq!(
        state.selected(),
        2 * PAGE_JUMP,
        "second page down jumps again"
    );
    state.page_up();
    assert_eq!(state.selected(), PAGE_JUMP, "page up jumps back by a page");
    // Page-up from within a page of the top saturates at the controller row.
    state.select_row(2);
    state.page_up();
    assert_eq!(
        state.selected(),
        0,
        "page up saturates at the controller row"
    );
}

#[test]
fn request_repoll_sets_and_take_clears() {
    // STUI-1: a mutation requests a re-poll; the run loop consumes it exactly once.
    let mut state = CoordinatorState::live();
    assert!(!state.take_repoll(), "no re-poll requested initially");
    state.request_repoll();
    assert!(state.take_repoll(), "the requested re-poll fires once");
    assert!(
        !state.take_repoll(),
        "a consumed re-poll does not re-fire on the next tick"
    );
}

#[test]
fn controller_is_selected_at_row_zero() {
    let mut state = CoordinatorState::skeleton();
    assert!(state.controller_selected());
    state.select_row(1);
    assert!(!state.controller_selected());
}

#[test]
fn selected_session_offsets_by_controller_row() {
    let mut state = CoordinatorState::skeleton();
    assert!(
        state.selected_session().is_none(),
        "row 0 is the controller"
    );
    state.select_row(1);
    assert_eq!(state.selected_session().unwrap().prefix, "aipowerranking");
    state.select_row(2);
    assert_eq!(state.selected_session().unwrap().prefix, "genealogy");
}

#[test]
fn default_state_has_placeholder_rows() {
    let state = CoordinatorState::skeleton();
    assert_eq!(state.sessions.len(), 2);
    assert_eq!(state.selected(), 0);
}

// ---- state: input + history ring ------------------------------------------

#[test]
fn input_edits_buffer() {
    let mut state = CoordinatorState::default();
    state.push_char('h');
    state.push_char('i');
    assert_eq!(state.input, "hi");
    state.backspace();
    assert_eq!(state.input, "h");
    state.clear_input();
    assert!(state.input.is_empty());
}

#[test]
fn submit_records_history() {
    let mut state = CoordinatorState::default();
    state.input = "  status please  ".to_string();
    let submitted = state.submit_input();
    assert_eq!(
        submitted.as_deref(),
        Some("status please"),
        "trims and returns"
    );
    assert_eq!(state.history, vec!["status please".to_string()]);
    assert!(state.input.is_empty(), "buffer cleared after submit");
}

#[test]
fn submit_empty_input_is_noop() {
    let mut state = CoordinatorState::default();
    state.input = "   ".to_string();
    assert!(state.submit_input().is_none());
    assert!(state.history.is_empty());
}

#[test]
fn history_ring_is_bounded() {
    let mut state = CoordinatorState::default();
    for i in 0..(INPUT_HISTORY_LIMIT + 5) {
        state.input = format!("msg{i}");
        let _ = state.submit_input();
    }
    assert_eq!(state.history.len(), INPUT_HISTORY_LIMIT, "ring is capped");
    // Oldest entries were evicted; the newest is retained.
    assert_eq!(
        state.history.last().unwrap(),
        &format!("msg{}", INPUT_HISTORY_LIMIT + 4)
    );
    assert_eq!(state.history.first().unwrap(), "msg5", "oldest dropped");
}

#[test]
fn history_recall_walks_entries() {
    let mut state = CoordinatorState::default();
    for m in ["one", "two", "three"] {
        state.input = m.to_string();
        let _ = state.submit_input();
    }
    state.history_prev();
    assert_eq!(state.input, "three");
    state.history_prev();
    assert_eq!(state.input, "two");
    state.history_next();
    assert_eq!(state.input, "three");
    state.history_next();
    assert!(state.input.is_empty(), "stepping past newest clears buffer");
}

// ---- events: slash parsing (the stub) -------------------------------------

#[test]
fn parse_slash_recognises_known_commands() {
    assert_eq!(parse_slash("/help"), Some(SlashCommand::Help));
    assert_eq!(parse_slash("/new repo=x"), Some(SlashCommand::New));
    assert_eq!(parse_slash("/sessions"), Some(SlashCommand::Sessions));
    assert_eq!(parse_slash("/attach"), Some(SlashCommand::Attach));
    assert_eq!(parse_slash("/stop"), Some(SlashCommand::Stop));
    assert_eq!(parse_slash("/resume"), Some(SlashCommand::Resume));
    assert_eq!(parse_slash("/kill"), Some(SlashCommand::Kill));
    // `/health` and its operator aliases all classify as the health verb.
    assert_eq!(parse_slash("/health"), Some(SlashCommand::Health));
    assert_eq!(parse_slash("/healthcheck"), Some(SlashCommand::Health));
    assert_eq!(parse_slash("/ping"), Some(SlashCommand::Health));
    // Case-insensitive on the verb.
    assert_eq!(parse_slash("/HELP"), Some(SlashCommand::Help));
}

#[test]
fn parse_slash_classifies_unknown() {
    assert_eq!(
        parse_slash("/frobnicate now"),
        Some(SlashCommand::Unknown("frobnicate".to_string()))
    );
}

#[test]
fn parse_slash_ignores_plain_text() {
    assert_eq!(parse_slash("hello there"), None);
    assert_eq!(parse_slash("@aipowerranking: run tests"), None);
    assert_eq!(parse_slash(""), None);
}

#[test]
fn mutating_commands_are_classified() {
    // STUI-1: only fleet-mutating commands force an immediate re-poll.
    assert!(SlashCommand::New.is_mutating());
    assert!(SlashCommand::Kill.is_mutating());
    assert!(SlashCommand::Stop.is_mutating());
    assert!(SlashCommand::Resume.is_mutating());
    // Read-only commands must NOT trigger a refresh.
    assert!(!SlashCommand::Help.is_mutating());
    assert!(!SlashCommand::Sessions.is_mutating());
    assert!(!SlashCommand::Attach.is_mutating());
    assert!(!SlashCommand::Unknown("frob".to_string()).is_mutating());
}

#[test]
fn parse_slash_bare_slash_is_not_a_command() {
    // A lone `/` (or `/` followed only by whitespace) has no command word, so it
    // must NOT classify as `Unknown("")` — it falls through to chat as `None`.
    assert_eq!(parse_slash("/"), None);
    assert_eq!(parse_slash("/   "), None);
    assert_eq!(parse_slash("/\t"), None);
}

// ---- events: key dispatch -------------------------------------------------

#[test]
fn quit_on_q_when_empty() {
    assert!(is_quit(&key(KeyCode::Char('q')), true));
    let mut state = CoordinatorState::skeleton();
    handle_key(&mut state, key(KeyCode::Char('q')));
    assert!(state.should_exit);
}

#[test]
fn quit_on_ctrl_c() {
    let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
    assert!(is_quit(&ctrl_c, true));
    assert!(is_quit(&ctrl_c, false), "Ctrl-C quits even mid-message");
    let mut state = CoordinatorState::default();
    state.input = "typing".to_string();
    handle_key(&mut state, ctrl_c);
    assert!(state.should_exit);
}

#[test]
fn q_in_message_is_not_quit() {
    assert!(!is_quit(&key(KeyCode::Char('q')), false));
    let mut state = CoordinatorState::default();
    state.input = "fi".to_string();
    handle_key(&mut state, key(KeyCode::Char('q')));
    assert!(!state.should_exit, "q is editing text, not quitting");
    assert_eq!(state.input, "fiq");
}

#[test]
fn handle_key_moves_selection_when_input_empty() {
    let mut state = CoordinatorState::skeleton();
    handle_key(&mut state, key(KeyCode::Down));
    assert_eq!(state.selected(), 1);
    handle_key(&mut state, key(KeyCode::Char('j')));
    assert_eq!(state.selected(), 2);
    handle_key(&mut state, key(KeyCode::Char('k')));
    assert_eq!(state.selected(), 1);
    handle_key(&mut state, key(KeyCode::Up));
    assert_eq!(state.selected(), 0);
}

#[test]
fn handle_key_enter_submits_and_returns_line() {
    let mut state = CoordinatorState::default();
    state.input = "spin up a session".to_string();
    let submitted = handle_key(&mut state, key(KeyCode::Enter));
    assert_eq!(submitted.as_deref(), Some("spin up a session"));
    assert_eq!(state.history.len(), 1);
}

#[test]
fn handle_key_page_keys_scroll_regardless_of_buffer() {
    // STUI-1: Page-Up/Page-Down move the selection even with text in the buffer
    // (they have no text-editing meaning).
    let mut state = CoordinatorState::live();
    for i in 0..20 {
        state
            .sessions
            .push(SessionEntry::new(format!("id{i}"), "p", "Active", "s"));
    }
    state.input = "half-typed".to_string(); // a non-empty buffer
    handle_key(&mut state, key(KeyCode::PageDown));
    assert_eq!(
        state.selected(),
        PAGE_JUMP,
        "page down scrolls even mid-message"
    );
    handle_key(&mut state, key(KeyCode::PageUp));
    assert_eq!(state.selected(), 0, "page up scrolls back even mid-message");
    assert_eq!(state.input, "half-typed", "page keys never edit the buffer");
}

#[test]
fn handle_key_enter_mutating_command_requests_repoll() {
    // STUI-1: submitting a mutating slash command flags an immediate re-poll;
    // a plain chat line or a read-only command does not.
    let mut state = CoordinatorState::live();
    state.input = "/new repo=x".to_string();
    let submitted = handle_key(&mut state, key(KeyCode::Enter));
    assert_eq!(submitted.as_deref(), Some("/new repo=x"));
    assert!(
        state.take_repoll(),
        "a mutating slash command requests a re-poll"
    );

    // A read-only command does NOT request a re-poll.
    state.input = "/help".to_string();
    handle_key(&mut state, key(KeyCode::Enter));
    assert!(
        !state.take_repoll(),
        "a read-only command must not force a refresh"
    );

    // Plain chat does NOT request a re-poll.
    state.input = "just chatting".to_string();
    handle_key(&mut state, key(KeyCode::Enter));
    assert!(!state.take_repoll(), "plain chat must not force a refresh");
}

#[test]
fn handle_key_up_recalls_history_when_input_nonempty() {
    let mut state = CoordinatorState::default();
    state.input = "earlier".to_string();
    let _ = state.submit_input();
    // Type something, then ↑ should recall history rather than move selection.
    state.push_char('x');
    handle_key(&mut state, key(KeyCode::Up));
    assert_eq!(state.input, "earlier");
}

// ---- layout text ----------------------------------------------------------

#[test]
fn input_line_shows_prompt_and_cursor() {
    let mut state = CoordinatorState::default();
    state.input = "hi".to_string();
    let line = input_line(&state);
    assert!(line.starts_with(INPUT_PROMPT), "missing prompt: {line}");
    assert!(line.ends_with('_'), "missing cursor glyph: {line}");
    assert!(line.contains("hi"));
}

#[test]
fn status_bar_lists_keys() {
    let bar = status_bar_text();
    assert_eq!(bar, STATUS_BAR_HINT);
    assert!(bar.contains("/help"));
    assert!(bar.contains("quit"));
}

#[test]
fn controller_status_is_synthetic() {
    assert!(CONTROLLER_STATUS.contains("ready"));
}

// ---- Child #2: live polling — pure session mapping ------------------------

/// Build a `CoordinatorSession` wire value for the mapping tests.
fn coord_session(id: &str, prefix: &str, status: &str, recent: &[&str]) -> CoordinatorSession {
    CoordinatorSession {
        id: id.to_string(),
        name: format!("tmpm-{prefix}"),
        prefix: prefix.to_string(),
        workdir: "/tmp".to_string(),
        status: status.to_string(),
        active_delegations: 0,
        recent_output: recent.iter().map(|s| s.to_string()).collect(),
        // #1275 fields are not exercised by these DOC-13 mapping tests; default
        // them (None / false) so the wire-shape change stays additive here.
        ..Default::default()
    }
}

#[test]
fn coord_session_to_entry_summarizes_last_output() {
    // The summary is the LAST non-empty line of recent_output (a trailing blank
    // line must be skipped), per DOC-13 §6.2 option C.
    let s = coord_session(
        "4f9ca1b2deadbeef", // pragma: allowlist secret — fake session id
        "aipowerranking",
        "Active",
        &["", "Running tests"],
    );
    let entry = coord_session_to_entry(s);
    assert_eq!(entry.summary, "Running tests");
    assert_eq!(entry.short_id, "4f9ca1b2");
    assert_eq!(entry.prefix, "aipowerranking");
    assert_eq!(entry.status, "Active");
}

#[test]
fn coord_session_to_entry_falls_back_to_status() {
    // With no recent_output the summary falls back to the status word.
    let s = coord_session("7b2ec0d1cafef00d", "genealogy", "Paused", &[]);
    let entry = coord_session_to_entry(s);
    assert_eq!(entry.summary, "Paused", "empty pane → status word");
    // An all-whitespace pane tail also falls back to the status word.
    let blank = coord_session("abc", "p", "Idle", &["   ", "\t"]);
    assert_eq!(coord_session_to_entry(blank).summary, "Idle");
}

#[test]
fn coord_session_to_entry_derives_short_id() {
    // Long UUIDs truncate to 8 hex; short ids pass through whole.
    // pragma: allowlist secret — fake session id
    let long = coord_session("0123456789abcdef0123", "p", "Active", &["x"]);
    assert_eq!(coord_session_to_entry(long).short_id, "01234567");
    let short = coord_session("abc", "p", "Active", &["x"]);
    assert_eq!(coord_session_to_entry(short).short_id, "abc");
}

#[test]
fn live_state_starts_empty_and_unreachable() {
    let state = CoordinatorState::live();
    assert!(
        state.sessions.is_empty(),
        "no placeholder rows in live mode"
    );
    assert!(
        !state.daemon_reachable,
        "daemon presumed down until first poll"
    );
    assert_eq!(state.selected(), 0, "controller selected at start");
}

#[test]
fn daemon_indicator_reflects_reachability() {
    let mut state = CoordinatorState::live();
    assert_eq!(daemon_indicator(&state), DAEMON_UNREACHABLE);
    state.daemon_reachable = true;
    assert_eq!(daemon_indicator(&state), DAEMON_REACHABLE);
    // The two indicators are visually distinct.
    assert_ne!(DAEMON_REACHABLE, DAEMON_UNREACHABLE);
}

#[test]
fn catalog_indicator_reflects_staleness() {
    // The HR-3 rebuild offer shows ONLY when the daemon is reachable AND reports
    // the catalog is stale; otherwise the status bar stays clean.
    let mut state = CoordinatorState::live();
    // Down daemon, no flag → nothing.
    assert_eq!(catalog_indicator(&state), None);

    // Stale flag but daemon DOWN → still nothing (a down daemon's flag is moot).
    state.catalog_stale = true;
    assert_eq!(catalog_indicator(&state), None);

    // Reachable + stale → the rebuild-offer hint appears.
    state.daemon_reachable = true;
    assert_eq!(catalog_indicator(&state), Some(CATALOG_STALE_HINT));

    // Reachable + fresh → nothing.
    state.catalog_stale = false;
    assert_eq!(catalog_indicator(&state), None);

    // The hint names the apply command so the offer is actionable.
    assert!(CATALOG_STALE_HINT.contains("tm catalog apply"));
}

// ---- Child #2: live polling — daemon-down branch (async) ------------------

// #4306/#4415: the dead-address fixture used to be a local bind-an-ephemeral-
// port-then-drop-it helper, whose "nothing can be listening here" premise
// expired the moment the OS re-handed that port to another binder. All three
// former copies now share ONE fixture whose guarantee does not depend on
// winning a port race — see `crate::test_support::dead_loopback_url`.
use crate::test_support::dead_loopback_url;

// #9556: serial — resolution reads TRUSTY_DATA_DIR_OVERRIDE, which serial tests set.
#[tokio::test]
#[serial_test::serial]
async fn poll_marks_unreachable_clears_sessions() {
    // Why: `coord_poll_daemon` must, on an unreachable daemon, clear any rows it
    // previously showed and flip `daemon_reachable` to false (DOC-13 §6) so the
    // operator never sees stale sessions behind a `daemon ✗` indicator. The live
    // (daemon-UP) branch needs a running daemon and is exercised manually / by
    // the daemon suites, not here.
    //
    // Determinism note: `coord_poll_daemon` self-heals via `rediscover`, which
    // re-resolves the URL from the lock file on a failed probe. If a real daemon
    // is discoverable on this machine the function will (correctly) re-point to
    // it and report reachable, so we only assert the daemon-down outcome when
    // discovery itself yields no reachable daemon — which is always the case in
    // CI. We pin the client to discovery's own result so the no-op `rediscover`
    // path is taken and the probe is the sole determinant.
    let discovered = crate::core::resolve_daemon_url(None);
    let probe = DaemonClient::new(discovered.clone());
    if probe.is_healthy().await {
        // A real daemon is up locally; the down-branch is unreachable through the
        // self-healing poll, so there is nothing deterministic to assert here.
        // CI (no daemon) always exercises the assertions below.
        eprintln!(
            "skipping daemon-down assertions: a reachable daemon was discovered at {discovered}"
        );
        return;
    }

    // No daemon is discoverable. Pin the client at a guaranteed-dead port; since
    // `discovered` is itself unreachable, `rediscover` cannot rescue the probe.
    let mut state = CoordinatorState::live();
    state.daemon_reachable = true; // pretend a prior poll had succeeded
    state.sessions = vec![
        SessionEntry::new("4f9ca1b2", "aipowerranking", "Active", "Running tests"),
        SessionEntry::new("7b2ec0d1", "genealogy", "Idle", "Idle"),
    ];
    state.select_row(2); // selection sits on the last session

    let mut client = DaemonClient::new(dead_loopback_url());
    coord_poll_daemon(&mut state, &mut client).await;

    assert!(
        !state.daemon_reachable,
        "an unreachable daemon must flip daemon_reachable to false"
    );
    assert!(
        state.sessions.is_empty(),
        "a daemon-down poll must clear stale session rows"
    );
    assert_eq!(
        state.selected(),
        0,
        "clearing the list clamps the selection back to the controller row"
    );
}

/// Why (#9556): the `--single-pane` coordinator poll must report a dead
/// explicit endpoint as unreachable instead of re-pointing at the lock-file or
/// default daemon. With the URL pinned the poll dials only `dead`: a bound,
/// never-listening loopback socket, refused at once on every host, including
/// WSL2, where port 1 hangs instead (#9526).
/// Test: itself.
#[tokio::test]
async fn coord_poll_keeps_explicit_url() {
    let bound = tokio::net::TcpSocket::new_v4()
        .and_then(|s| s.bind("127.0.0.1:0".parse().expect("addr")).map(|()| s))
        .expect("bind loopback socket");
    let dead = format!("http://{}", bound.local_addr().expect("bound addr"));
    let mut client = DaemonClient::new(dead.clone()).with_pinned_base_url(true);
    let mut state = CoordinatorState::live();
    state.daemon_reachable = true;

    coord_poll_daemon(&mut state, &mut client).await;

    assert!(
        !state.daemon_reachable,
        "a dead explicit URL reports unreachable"
    );
    assert_eq!(client.base_url(), dead, "the explicit URL is kept");
}

// ---- STUI-0 banner --------------------------------------------------------

/// Why: §3.1 fixes the banner's first line to `trusty-mpm sessions v<version>`;
/// the composition must embed the crate `CARGO_PKG_VERSION` verbatim so the
/// operator sees which build is running.
/// What: composes a banner and asserts the version line is present with the
/// compile-time version.
/// Test: this IS the test.
#[test]
fn compose_banner_includes_name_and_version() {
    let banner = compose_banner(
        env!("CARGO_PKG_VERSION"),
        &ProbeOutcome::active(None),
        &ProbeOutcome::active(None),
        Some(3),
    );
    let expected = format!("trusty-mpm sessions  v{}", env!("CARGO_PKG_VERSION"));
    assert!(
        banner.lines().next() == Some(expected.as_str()),
        "banner must lead with the name + version line, got:\n{banner}"
    );
}

/// Why: §3.1 pins the active glyph `●` and the word `active` for a reachable
/// backplane; both memory and search lines must render them.
/// What: composes an all-active banner and asserts each service line carries
/// the active glyph + word.
/// Test: this IS the test.
#[test]
fn compose_banner_active_shows_glyphs() {
    let banner = compose_banner(
        "1.2.3",
        &ProbeOutcome::active(None),
        &ProbeOutcome::active(None),
        Some(2),
    );
    assert!(
        banner.contains(&format!("memory  {GLYPH_ACTIVE} active")),
        "active memory must show `● active`, got:\n{banner}"
    );
    assert!(
        banner.contains(&format!("search  {GLYPH_ACTIVE} active")),
        "active search must show `● active`, got:\n{banner}"
    );
}

/// Why: §3.1 error conditions require an unreachable service to render
/// `○ unreachable` (a glyph distinct from active) without aborting — so the
/// composer must emit it for a down probe.
/// What: composes a banner with both services unreachable and asserts the
/// unreachable glyph + word appear for each.
/// Test: this IS the test.
#[test]
fn compose_banner_unreachable_shows_glyphs() {
    let banner = compose_banner(
        "1.2.3",
        &ProbeOutcome::unreachable(None),
        &ProbeOutcome::unreachable(None),
        Some(0),
    );
    assert!(
        banner.contains(&format!("memory  {GLYPH_UNREACHABLE} unreachable")),
        "down memory must show `○ unreachable`, got:\n{banner}"
    );
    assert!(
        banner.contains(&format!("search  {GLYPH_UNREACHABLE} unreachable")),
        "down search must show `○ unreachable`, got:\n{banner}"
    );
}

/// Why: decision D4 confirms memory against the fixed `user` palace; the banner
/// must surface that palace as a parenthetical note so the operator sees WHICH
/// palace was checked.
/// What: composes a banner whose memory outcome carries the `palace: user` note
/// and asserts the rendered memory line includes it.
/// Test: this IS the test.
#[test]
fn compose_banner_active_shows_palace_note() {
    let banner = compose_banner(
        "0.1.0",
        &ProbeOutcome::active(Some(format!("palace: {USER_PALACE}"))),
        &ProbeOutcome::active(None),
        Some(1),
    );
    assert!(
        banner.contains(&format!("(palace: {USER_PALACE})")),
        "memory line must note the `user` palace per D4, got:\n{banner}"
    );
}

/// Why: §3.1 requires the startup line to point operators at `/help`.
/// What: composes a banner and asserts the final line carries the `/help` hint.
/// Test: this IS the test.
#[test]
fn compose_banner_appends_help_hint() {
    let banner = compose_banner(
        "0.1.0",
        &ProbeOutcome::active(None),
        &ProbeOutcome::active(None),
        Some(4),
    );
    let last = banner.lines().last().unwrap_or_default();
    assert!(
        last.ends_with(HELP_HINT),
        "startup line must end with the /help hint, got: {last:?}"
    );
    assert!(
        last.starts_with("4 active sessions"),
        "startup line must lead with the active-session count, got: {last:?}"
    );
}

/// Why: a single active session must read naturally (`1 active session`, not
/// `1 active sessions`); the count line pluralises on the count.
/// What: composes banners for counts 0, 1, and 5 and asserts the exact lead.
/// Test: this IS the test.
#[test]
fn compose_banner_pluralizes_count() {
    let line_for = |n: usize| {
        let banner = compose_banner(
            "0.1.0",
            &ProbeOutcome::active(None),
            &ProbeOutcome::active(None),
            Some(n),
        );
        banner.lines().last().unwrap_or_default().to_string()
    };
    assert!(line_for(0).starts_with("0 active sessions"));
    assert!(line_for(1).starts_with("1 active session  ·"));
    assert!(line_for(5).starts_with("5 active sessions"));
}

/// Why: when the daemon is unreachable at startup the count is unknown; the
/// banner must say so rather than render a misleading `0 active sessions`.
/// What: composes a banner with `active_count = None` and asserts the startup
/// line reports `daemon unreachable` while still carrying the `/help` hint.
/// Test: this IS the test.
#[test]
fn compose_banner_handles_unknown_count() {
    let banner = compose_banner(
        "0.1.0",
        &ProbeOutcome::unreachable(None),
        &ProbeOutcome::unreachable(None),
        None,
    );
    let last = banner.lines().last().unwrap_or_default();
    assert!(
        last.starts_with("daemon unreachable"),
        "unknown count must read `daemon unreachable`, got: {last:?}"
    );
    assert!(
        last.ends_with(HELP_HINT),
        "the /help hint must remain even when the count is unknown, got: {last:?}"
    );
}

/// Why: §3.1 makes probes fail-safe — a down search daemon yields `○ unreachable`
/// and never panics or hangs the TUI.
/// What: probes a socket path nothing binds (#9214) and asserts the outcome
/// is inactive.
/// Test: this IS the test.
#[tokio::test]
async fn probe_unreachable_search_is_inactive() {
    let dir = tempfile::tempdir().expect("tempdir");
    let outcome = probe_search(Some(&dir.path().join("missing.sock"))).await;
    assert!(
        !outcome.active,
        "an unreachable search daemon must probe inactive"
    );
}

/// Why: #9214 — the banner's search leg reaches the daemon over its socket.
/// What: a mock answering `search.health` probes active.
/// Test: this IS the test.
#[tokio::test]
async fn probe_search_over_the_socket_is_active() {
    let daemon = crate::uds_mock::spawn(crate::uds_mock::always(
        serde_json::json!({ "version": "9.9.9" }),
    ))
    .await;
    let outcome = probe_search(Some(daemon.socket())).await;
    assert!(outcome.active, "a live search socket must probe active");
}

/// Why: #9214 Fail-Open Check — a daemon that refuses `search.health` probes
/// unreachable, never panics.
/// What: a mock refusing every call; asserts the probe reached it and came back
/// inactive.
/// Test: this IS the test.
#[tokio::test]
async fn probe_search_on_a_refusing_daemon_is_inactive() {
    use std::sync::{Arc, Mutex};

    let seen: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let recorder = Arc::clone(&seen);
    let daemon = crate::uds_mock::spawn(move |method: &str, _params: serde_json::Value| {
        recorder.lock().expect("recorder").push(method.to_string());
        Box::pin(async { Err(crate::uds_mock::RpcError::internal("refused")) })
    })
    .await;
    let outcome = probe_search(Some(daemon.socket())).await;
    assert!(!outcome.active, "a refused health probe must be inactive");
    assert_eq!(
        *seen.lock().expect("recorder"),
        vec!["search.health".to_string()]
    );
}

/// Why: §3.1 + D4 make the memory probe fail-safe — a down memory daemon yields
/// `○ unreachable` with a reason and never panics.
/// What: probes a guaranteed-dead loopback address and asserts the outcome is
/// inactive and carries a reason note.
/// Test: this IS the test.
#[tokio::test]
async fn probe_unreachable_memory_is_inactive() {
    let outcome = probe_memory(Some(std::path::Path::new(
        "/nonexistent/trusty-memory.sock",
    )))
    .await;
    assert!(
        !outcome.active,
        "an unreachable memory daemon must probe inactive"
    );
    assert!(
        outcome.note.is_some(),
        "a degraded memory probe should carry a reason note"
    );
}

/// Why: the print site composes the banner and prints it with `eprintln!`; if the
/// composed banner itself ended with a newline AND `startup_line` also ended with
/// one, the operator would see two blank lines. The contract is a single trailing
/// newline so the print site yields exactly one blank separator.
/// What: composes a banner and asserts it ends with exactly one `\n` (not two and
/// not zero).
/// Test: this IS the test.
#[test]
fn compose_banner_has_single_trailing_newline() {
    let banner = compose_banner(
        "0.1.0",
        &ProbeOutcome::active(None),
        &ProbeOutcome::active(None),
        Some(2),
    );
    assert!(
        banner.ends_with('\n'),
        "composed banner must end with a newline, got:\n{banner:?}"
    );
    assert!(
        !banner.ends_with("\n\n"),
        "composed banner must NOT end with a double newline, got:\n{banner:?}"
    );
}

/// Spin up a mock trusty-memory daemon whose `memory.palace_get` refuses with
/// `code`, recording whether a `palace_create` is ever asked for.
///
/// Why: `ensure_user_palace_at` must only create on a genuine not-found. To
/// prove it does NOT create on any other refusal, the test needs to observe
/// whether the create is attempted at all.
/// What: mounts a mock whose `memory.palace_get` answers `Err(code)` and whose
/// `palace_create` flips a watch channel to `true` before succeeding.
/// Test: used by `ensure_user_palace_does_not_create_on_other_errors` and
/// `ensure_user_palace_creates_only_on_not_found`.
async fn spawn_palace_mock(
    code: i64,
) -> (
    crate::uds_mock::MockUdsDaemon,
    tokio::sync::watch::Receiver<bool>,
) {
    use crate::uds_mock::{self, RpcError};

    let (tx, rx) = tokio::sync::watch::channel(false);
    let daemon = uds_mock::spawn(move |method: &str, _params: serde_json::Value| {
        let tx = tx.clone();
        let method = method.to_string();
        Box::pin(async move {
            match method.as_str() {
                "memory.palace_get" => Err(RpcError::new(code, "stubbed refusal".to_string())),
                "palace_create" => {
                    let _ = tx.send(true);
                    Ok(serde_json::json!({"ok": true}))
                }
                other => Err(RpcError::method_not_found(other, &[])),
            }
        })
    })
    .await;
    (daemon, rx)
}

/// Why: the review flagged that `ensure_user_palace` over-eagerly created the
/// palace — any non-2xx GET (including a transient `500`/`503`) fell through to
/// a create. The fix gates creation on a genuine not-found; any other refusal
/// must return `false` WITHOUT attempting a write. #6286 moved the distinction
/// from the HTTP status onto the JSON-RPC error code.
/// What: stubs `memory.palace_get` to refuse with the internal-error code, runs
/// `ensure_user_palace_at`, and asserts it returns `false` AND that no create
/// was attempted.
/// Test: this IS the test.
#[tokio::test]
async fn ensure_user_palace_does_not_create_on_other_errors() {
    // -32603 is `CODE_INTERNAL_ERROR` — the "daemon state is unknown" case.
    let (daemon, create_seen) = spawn_palace_mock(-32603).await;
    let created = ensure_user_palace_at(daemon.socket()).await;
    assert!(
        !created,
        "an internal error from palace_get must NOT confirm the palace as active"
    );
    // Give any erroneous create a moment to land, then assert none was made.
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    assert!(
        !*create_seen.borrow(),
        "a non-not-found refusal must NOT trigger a create"
    );
}

/// Why: the complement — a genuine not-found means the palace is absent, so the
/// banner SHOULD create it idempotently (D4). This pins the one code that is
/// allowed to trigger a write.
/// What: stubs `memory.palace_get` to refuse with `-32004`, runs
/// `ensure_user_palace_at`, and asserts it returns `true` and that the create
/// was observed.
/// Test: this IS the test.
#[tokio::test]
async fn ensure_user_palace_creates_only_on_not_found() {
    let (daemon, create_seen) = spawn_palace_mock(trusty_common::memory_rpc::CODE_NOT_FOUND).await;
    let created = ensure_user_palace_at(daemon.socket()).await;
    assert!(
        created,
        "a not-found followed by a successful create must confirm the palace"
    );
    assert!(
        *create_seen.borrow(),
        "a not-found must trigger exactly the create"
    );
}

// ---- Phase 1C: slash → TrustyCommand mapping + aliases --------------------

#[test]
fn parse_slash_recognises_aliases() {
    // The documented CommandSpec aliases resolve to the same SlashCommand as
    // their canonical verb.
    assert_eq!(parse_slash("/spawn"), Some(SlashCommand::New));
    assert_eq!(parse_slash("/list"), Some(SlashCommand::Sessions));
    assert_eq!(parse_slash("/managed-list"), Some(SlashCommand::Sessions));
    assert_eq!(parse_slash("/managed-stop x"), Some(SlashCommand::Stop));
    assert_eq!(parse_slash("/decommission x"), Some(SlashCommand::Kill));
    assert_eq!(
        parse_slash("/managed-decommission x"),
        Some(SlashCommand::Kill)
    );
    assert_eq!(parse_slash("/approve x"), Some(SlashCommand::Answer));
    assert_eq!(parse_slash("/status x"), Some(SlashCommand::Get));
    assert_eq!(parse_slash("/managed-send x hi"), Some(SlashCommand::Send));
    assert_eq!(
        parse_slash("/managed-activity x"),
        Some(SlashCommand::Activity)
    );
}

#[test]
fn route_slash_maps_to_command() {
    // A read-only verb with an explicit target maps to its TrustyCommand.
    assert_eq!(
        route("/sessions", None),
        Dispatch::Command(TrustyCommand::ManagedList)
    );
    assert_eq!(route("/help", None), Dispatch::Command(TrustyCommand::Help));
    // `/health` is a no-target ops verb routing straight to TrustyCommand::Health.
    assert_eq!(
        route("/health", None),
        Dispatch::Command(TrustyCommand::Health)
    );
    assert_eq!(
        route("/stop red-owl", None),
        Dispatch::Command(TrustyCommand::ManagedRuntimeStop {
            target: "red-owl".to_string()
        })
    );
    assert_eq!(
        route("/kill red-owl", None),
        Dispatch::Command(TrustyCommand::ManagedDecommission {
            target: "red-owl".to_string()
        })
    );
    assert_eq!(
        route("/resume red-owl", None),
        Dispatch::Command(TrustyCommand::ManagedResume {
            target: "red-owl".to_string()
        })
    );
    assert_eq!(
        route("/attach red-owl", None),
        Dispatch::Command(TrustyCommand::ManagedAttachCmd {
            target: "red-owl".to_string()
        })
    );
    assert_eq!(
        route("/get red-owl", None),
        Dispatch::Command(TrustyCommand::ManagedGet {
            target: "red-owl".to_string()
        })
    );
    assert_eq!(
        route("/activity red-owl", None),
        Dispatch::Command(TrustyCommand::ManagedActivity {
            target: "red-owl".to_string()
        })
    );
}

#[test]
fn route_targetless_verb_borrows_focus() {
    // With no explicit target, a target-only verb borrows the focused session.
    assert_eq!(
        route("/stop", Some("focus-id")),
        Dispatch::Command(TrustyCommand::ManagedRuntimeStop {
            target: "focus-id".to_string()
        })
    );
}

#[test]
fn route_slash_explicit_target_overrides_focus() {
    // An explicit argument wins over the focused session.
    assert_eq!(
        route("/kill other", Some("focus-id")),
        Dispatch::Command(TrustyCommand::ManagedDecommission {
            target: "other".to_string()
        })
    );
}

#[test]
fn route_missing_target_hints() {
    // No explicit target and no focus → a hint, not a command.
    match route("/stop", None) {
        Dispatch::Hint(msg) => assert!(msg.contains("no session selected"), "{msg}"),
        other => panic!("expected hint, got {other:?}"),
    }
}

#[test]
fn route_unknown_command_hints() {
    match route("/frobnicate now", None) {
        Dispatch::Hint(msg) => assert!(msg.contains("unknown command"), "{msg}"),
        other => panic!("expected hint, got {other:?}"),
    }
}

#[test]
fn route_new_requires_repo_ref_task() {
    match route("/new just-a-repo", None) {
        Dispatch::Hint(msg) => assert!(msg.contains("usage"), "{msg}"),
        other => panic!("expected usage hint, got {other:?}"),
    }
}

#[test]
fn route_new_builds_managed_new() {
    assert_eq!(
        route("/new https://x/r.git main do the thing", None),
        Dispatch::Command(TrustyCommand::ManagedNew {
            repo_url: "https://x/r.git".to_string(),
            git_ref: "main".to_string(),
            task: "do the thing".to_string(),
            name_hint: None,
            runtime: None,
            inject_task: None,
            deliverable_id: None,
            force_new: false,
        })
    );
}

#[test]
fn route_send_uses_focus_for_target() {
    // /send with a focus: the WHOLE arg string is the text, target is the focus.
    assert_eq!(
        route("/send run the tests", Some("focus-id")),
        Dispatch::Command(TrustyCommand::ManagedSend {
            target: "focus-id".to_string(),
            text: "run the tests".to_string()
        })
    );
}

#[test]
fn route_send_explicit_target() {
    // /send without a focus: first token is the target, the rest is the text.
    assert_eq!(
        route("/send red-owl run the tests", None),
        Dispatch::Command(TrustyCommand::ManagedSend {
            target: "red-owl".to_string(),
            text: "run the tests".to_string()
        })
    );
}

#[test]
fn route_send_missing_text_hints() {
    match route("/send", Some("focus-id")) {
        Dispatch::Hint(msg) => assert!(msg.contains("text is required"), "{msg}"),
        other => panic!("expected hint, got {other:?}"),
    }
}

#[test]
fn route_answer_routes_to_managed_answer() {
    assert_eq!(
        route("/answer yes proceed", Some("focus-id")),
        Dispatch::Command(TrustyCommand::ManagedAnswer {
            target: "focus-id".to_string(),
            answer: "yes proceed".to_string()
        })
    );
}

// ---- Phase 1C: free-text routing decision ---------------------------------

#[test]
fn route_free_text_sends_to_focus() {
    // A non-slash line with a focused session routes as a send to that session.
    assert_eq!(
        route("run the integration suite", Some("focus-id")),
        Dispatch::Command(TrustyCommand::ManagedSend {
            target: "focus-id".to_string(),
            text: "run the integration suite".to_string()
        })
    );
}

#[test]
fn route_free_text_no_focus_echoes() {
    // No focused session → keep the historical echo/no-op behaviour.
    assert_eq!(route("just chatting", None), Dispatch::Echo);
    // An empty line is always an echo no-op.
    assert_eq!(route("   ", Some("focus-id")), Dispatch::Echo);
}

// ---- Phase 1C: focused session target -------------------------------------

#[test]
fn focused_target_is_none_on_controller() {
    let mut state = CoordinatorState::live();
    state.sessions.push(SessionEntry::with_id(
        "full-id-1",
        "fullid",
        "p",
        "Active",
        "s",
    ));
    // Row 0 (controller) selected by default → no focused session.
    assert_eq!(state.selected(), 0);
    assert_eq!(state.focused_target(), None);
}

#[test]
fn focused_target_returns_selected_session_id() {
    let mut state = CoordinatorState::live();
    state.sessions.push(SessionEntry::with_id(
        "full-id-1",
        "fullid",
        "p",
        "Active",
        "s",
    ));
    state.select_row(1); // focus the first session
    // The full id, not the short display id, is used for routing.
    assert_eq!(state.focused_target(), Some("full-id-1"));
}

#[test]
fn focused_session_target_prefers_full_id() {
    // with_id carries the full id distinct from the short display id.
    let entry = SessionEntry::with_id("0123456789ab", "01234567", "p", "Active", "s");
    assert_eq!(entry.id, "0123456789ab");
    assert_eq!(entry.short_id, "01234567");
}

// ---- Phase 1C: output log -------------------------------------------------

#[test]
fn output_log_records_and_is_bounded() {
    let mut state = CoordinatorState::live();
    state.push_output(ratatui::text::Line::from("first"));
    state.push_output_lines(vec![
        ratatui::text::Line::from("a"),
        ratatui::text::Line::from("b"),
    ]);
    assert_eq!(state.output.len(), 3);
    // Overflow drops the oldest lines, keeping the cap.
    for i in 0..OUTPUT_LOG_LIMIT + 10 {
        state.push_output(ratatui::text::Line::from(format!("line {i}")));
    }
    assert_eq!(state.output.len(), OUTPUT_LOG_LIMIT);
}

#[test]
fn output_tail_keeps_most_recent() {
    let mut state = CoordinatorState::live();
    for i in 0..10 {
        state.push_output(ratatui::text::Line::from(format!("line {i}")));
    }
    let tail = output_tail(&state, 3);
    assert_eq!(tail.len(), 3);
    assert_eq!(line_text(&tail[2]), "line 9", "last line is the newest");
    assert_eq!(line_text(&tail[0]), "line 7");
    // Requesting more rows than exist returns the whole log (no panic).
    assert_eq!(output_tail(&state, 100).len(), 10);
}

// ---- Phase 1C: CommandResult renderer -------------------------------------

fn managed_view(id: &str, name: &str, state: &str) -> ManagedSessionView {
    ManagedSessionView {
        id: id.to_string(),
        name: name.to_string(),
        state: state.to_string(),
        workspace_path: None,
        repo_url: None,
        branch: None,
        pending_decision: None,
        proposed_default: None,
        slot: 0,
        deleted: false,
    }
}

#[test]
fn render_error_is_red() {
    let lines = render_result(&CommandResult::Error("daemon unreachable".to_string()));
    assert_eq!(lines.len(), 1);
    let text = line_text(&lines[0]);
    assert!(text.contains("daemon unreachable"), "{text}");
    assert!(text.starts_with('✗'), "{text}");
}

#[test]
fn render_result_lists_managed_sessions() {
    let views = vec![
        managed_view("aaaa00001111", "tmpm-red", "Running"),
        managed_view("bbbb22223333", "tmpm-owl", "Stopped"),
    ];
    let lines = render_result(&CommandResult::ManagedSessions(views));
    let head = line_text(&lines[0]);
    assert!(head.contains("managed sessions (2)"), "{head}");
    let row = line_text(&lines[1]);
    assert!(row.contains("aaaa0000"), "short id: {row}");
    assert!(row.contains("tmpm-red"), "name: {row}");
    assert!(row.contains("Running"), "state: {row}");
}

#[test]
fn render_result_empty_sessions_shows_none() {
    let lines = render_result(&CommandResult::ManagedSessions(vec![]));
    assert!(line_text(&lines[0]).contains("(0)"));
    assert!(line_text(&lines[1]).contains("none"));
}

#[test]
fn render_result_renders_lifecycle() {
    let lines = render_result(&CommandResult::ManagedLifecycle {
        id: "0123456789ab".to_string(),
        name: "tmpm-red".to_string(),
        state: "Stopped".to_string(),
        action: "stopped".to_string(),
        workspace_removed: None,
    });
    let text = line_text(&lines[0]);
    assert!(text.starts_with('✓'), "{text}");
    assert!(text.contains("stopped"), "{text}");
    assert!(text.contains("tmpm-red"), "{text}");
    assert!(text.contains("01234567"), "short id only: {text}");
}

#[test]
fn render_result_renders_sent() {
    let lines = render_result(&CommandResult::ManagedSent {
        id: "0123456789ab".to_string(),
        tmux_name: "tmpm-red".to_string(),
    });
    let text = line_text(&lines[0]);
    assert!(text.contains("tmpm-red"), "{text}");
    assert!(text.contains("01234567"), "{text}");
}

#[test]
fn render_result_renders_activity() {
    let lines = render_result(&CommandResult::ManagedActivity {
        id: "0123456789ab".to_string(),
        state: "working".to_string(),
        summary: "running tests".to_string(),
        raw_pane: "...".to_string(),
        runtime_active: true,
        pending_decision: Some("allow rm?".to_string()),
    });
    assert!(line_text(&lines[0]).contains("working"));
    assert!(line_text(&lines[0]).contains("alive"));
    assert!(lines.iter().any(|l| line_text(l).contains("running tests")));
    assert!(lines.iter().any(|l| line_text(l).contains("allow rm?")));
}

#[test]
fn render_result_renders_help() {
    let lines = render_result(&CommandResult::Help("line one\nline two".to_string()));
    assert_eq!(lines.len(), 2);
    assert_eq!(line_text(&lines[0]), "line one");
    assert_eq!(line_text(&lines[1]), "line two");
}

#[test]
fn render_result_renders_health() {
    use crate::client::HealthReport;
    // A reachable daemon renders a heading + catalog + fleet detail lines.
    let up = render_result(&CommandResult::Health(HealthReport {
        reachable: true,
        url: "http://127.0.0.1:7880".into(),
        status: "ok".into(),
        catalog_stale: false,
        catalog_unknown: false,
        managed_total: 2,
        managed_pending_decisions: 0,
    }));
    let up_joined = up.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(up_joined.contains("daemon ok"));
    assert!(up_joined.contains("up to date"));
    assert!(up_joined.contains("2 session(s)"));

    // A dead daemon renders a single unreachable line.
    let down = render_result(&CommandResult::Health(HealthReport {
        reachable: false,
        url: "http://127.0.0.1:0".into(),
        status: "unreachable".into(),
        ..HealthReport::default()
    }));
    assert_eq!(down.len(), 1);
    assert!(line_text(&down[0]).contains("unreachable"));
}