trusty-common 0.4.15

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
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
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
//! Service-specific terminal UI for the trusty-memory daemon.
//!
//! Why: operators of the trusty-memory daemon want a focused terminal surface
//! — a palace list, a streaming activity log of dream / drawer / recall
//! events, and a recall query bar — rather than the generic two-daemon
//! dashboard. Living in `trusty-common` behind the `monitor-tui` feature keeps
//! the pure state / rendering testable (issue #34).
//! What: a ratatui app with a 3-zone layout (title bar, PALACES + right-hand
//! split, RECALL input bar). The PALACES list always leads with an "All
//! palaces" entry that fans recalls out across every palace; the right side is
//! split vertically into an ACTIVITY feed (top) and a STATISTICS panel
//! (bottom), both scoped to the selected palace — or aggregated when "All" is
//! selected. It polls the daemon every 2 seconds, subscribes to the `/sse`
//! event stream on startup, runs cross-palace recalls from the input bar on
//! `[Enter]`, and triggers a dream cycle on `[d]`.
//! Test: `cargo test -p trusty-common --features monitor-tui` covers the pure
//! state, the "All" selector, palace row formatting, the activity / statistics
//! line builders, and dream-event logging; `trusty-memory monitor tui`
//! launches the live UI.

use std::time::{Duration, Instant};

use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use ratatui::{
    Frame, Terminal,
    layout::{Constraint, Direction, Layout},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
};
use tokio::sync::mpsc;

use crate::monitor::dashboard::{MemoryData, PalaceRow, format_count};
use crate::monitor::memory_client::{MemoryClient, MemoryEvent, RecallHit, resolve_memory_url};
use crate::monitor::tui_common::{
    self, ListFocus, ThreeWaySortKey, enter_tui, leave_tui, left_panel_width, panel_block, truncate,
};
use crate::monitor::utils::{ActivityLog, DaemonStatus};

/// Data-refresh interval: how often the daemon is polled.
const REFRESH_INTERVAL: Duration = Duration::from_millis(2000);

/// Input-poll interval: how often the keyboard is checked.
const INPUT_POLL: Duration = Duration::from_millis(50);

/// Number of results requested per recall query.
const RECALL_TOP_K: usize = 5;

/// Crate version, surfaced in the title bar.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// One-line key hint shown along the bottom of the UI.
pub const KEY_HINT: &str = "[Tab] focus  [d] dream  [↑↓] select  [Enter] recall  [/] filter  [s] sort  [g] group  [q] quit  [?] help";

/// Domain-specific labels for the memory TUI's three sort orders.
///
/// Why: the renderer surfaces the current sort key in the panel title; this
/// array maps the shared [`ThreeWaySortKey`] variants to memory-domain text
/// (the third variant reads as "Vectors" here, "Chunks" in search).
/// What: `["Activity", "Name", "Vectors"]`.
/// Test: covered indirectly by `test_palace_sort_key_cycle` via [`sort_label`].
const SORT_LABELS: &[&str; 3] = &["Activity", "Name", "Vectors"];

/// Sort key cycled by `[s]` in the palace list.
///
/// Why: kept as a re-export alias so external callers and tests that reference
/// `PalaceSortKey` continue to compile after the type was consolidated into
/// the shared [`ThreeWaySortKey`].
/// What: type alias for [`ThreeWaySortKey`].
/// Test: `test_palace_sort_key_cycle`.
pub type PalaceSortKey = ThreeWaySortKey;

/// Memory-domain label for the current sort key.
///
/// Why: the renderer needs `"Activity"` / `"Name"` / `"Vectors"`; the shared
/// enum is domain-agnostic so we map it through [`SORT_LABELS`].
/// What: delegates to [`ThreeWaySortKey::label`] with the memory labels.
/// Test: `test_palace_sort_key_cycle`.
pub fn sort_label(key: ThreeWaySortKey) -> &'static str {
    key.label(SORT_LABELS)
}

/// Label for the synthetic "All palaces" entry at the top of the list.
///
/// Why: selecting it fans recalls / stats out across every palace; a single
/// constant keeps the label consistent between the list and the panel titles.
/// What: the display text of the palace list's first row.
/// Test: `test_palace_lines` asserts this is the first row.
pub const ALL_LABEL: &str = "All palaces";

/// Which zone of the memory UI currently holds keyboard focus.
///
/// Why: re-export alias for [`ListFocus`] so existing callers and tests that
/// reference `MemoryFocus` continue to compile after the type was consolidated
/// into the shared module.
/// What: type alias for [`ListFocus`].
/// Test: `test_toggle_focus`.
pub type MemoryFocus = ListFocus;

/// All mutable state the memory UI renders and mutates.
///
/// Why: the event loop polls the daemon, streams `/sse` events, and handles
/// input — keeping every piece of state in one struct keeps the loop terse and
/// the rendering a pure function of this snapshot.
/// What: the daemon URL and status, the aggregate stats, the palace list and
/// selection cursor, the scroll offset of the palace panel, the bounded
/// activity log, the query buffer, the focused zone, and the help flag. The
/// selection cursor addresses a list whose first row is the synthetic "All
/// palaces" entry, so cursor `0` means "All" and cursor `n` (n ≥ 1) means
/// `palaces[n - 1]`.
/// Test: `test_selected_clamp`, `test_toggle_focus`, `test_palace_row_display`,
/// `test_all_selector`, `test_scroll_offset`.
#[derive(Debug, Clone)]
pub struct MemoryTuiState {
    /// The trusty-memory daemon base URL being monitored.
    pub base_url: String,
    /// The daemon's current liveness state.
    pub daemon_status: DaemonStatus,
    /// The latest aggregate stats, or `None` before the first poll.
    pub status: Option<MemoryData>,
    /// One row per palace.
    pub palaces: Vec<PalaceRow>,
    /// Cursor into the palace list, where row `0` is the "All palaces" entry
    /// and row `n` (n ≥ 1) selects `palaces[n - 1]`.
    pub selected: usize,
    /// Index of the first row drawn in the PALACES panel — the scroll offset
    /// that keeps [`Self::selected`] on screen when the list overflows.
    pub scroll_offset: usize,
    /// Bounded, timestamped log of dream / drawer / recall activity.
    pub log: ActivityLog,
    /// The in-progress recall query buffer.
    pub input: String,
    /// Which zone currently holds keyboard focus.
    pub focus: ListFocus,
    /// Whether the help overlay is visible (toggled with `?`).
    pub show_help: bool,
    /// Case-insensitive filter applied to palace name / project; empty disables.
    pub filter: String,
    /// Whether the inline filter bar is focused (captures typed chars).
    pub filter_active: bool,
    /// Current palace-list sort order.
    pub sort_key: ThreeWaySortKey,
    /// Whether the palace list is grouped by inferred project.
    pub group_by_project: bool,
}

impl MemoryTuiState {
    /// Build a fresh memory UI state targeting `base_url`.
    ///
    /// Why: the event loop seeds the state at startup before the first poll.
    /// What: stores the URL, sets the daemon `Connecting`, and starts with no
    /// stats, an empty palace list, empty log, empty query, and list focus.
    /// Test: `test_new_state_defaults`.
    pub fn new(base_url: impl Into<String>) -> Self {
        Self {
            base_url: base_url.into(),
            daemon_status: DaemonStatus::Connecting,
            status: None,
            palaces: Vec::new(),
            selected: 0,
            scroll_offset: 0,
            log: ActivityLog::new(),
            input: String::new(),
            focus: ListFocus::List,
            show_help: false,
            filter: String::new(),
            filter_active: false,
            sort_key: ThreeWaySortKey::default(),
            group_by_project: false,
        }
    }

    /// Cycle keyboard focus between the palace list and the recall bar.
    ///
    /// Why: `[Tab]` decides whether arrows navigate the list or whether typed
    /// characters edit the recall query.
    /// What: flips [`Self::focus`] via [`ListFocus::toggled`].
    /// Test: `test_toggle_focus`.
    pub fn toggle_focus(&mut self) {
        self.focus = self.focus.toggled();
    }

    /// Move the palace selection up one row, saturating at the top.
    ///
    /// Why: `↑` navigates the PALACES list when it has focus.
    /// What: decrements [`Self::selected`], never below zero.
    /// Test: `test_selected_clamp`.
    pub fn select_up(&mut self) {
        self.selected = self.selected.saturating_sub(1);
    }

    /// Move the palace selection down one row, clamped to the last palace.
    ///
    /// Why: `↓` navigates the PALACES list when it has focus.
    /// What: increments [`Self::selected`] but never past the last row. The
    /// list has `palaces.len() + 1` rows (row 0 is "All palaces").
    /// Test: `test_selected_clamp`.
    pub fn select_down(&mut self) {
        if self.selected < self.last_row() {
            self.selected += 1;
        }
    }

    /// The index of the last selectable row.
    ///
    /// Why: the list always carries the synthetic "All" row, so the last valid
    /// cursor is `palaces.len()` (not `palaces.len() - 1`).
    /// What: returns `palaces.len()` — row 0 is "All", rows `1..=len` are the
    /// individual palaces.
    /// Test: `test_selected_clamp`.
    fn last_row(&self) -> usize {
        self.palaces.len()
    }

    /// Clamp the selection cursor to the current palace count.
    ///
    /// Why: a poll can shrink the palace list leaving the cursor past the end;
    /// this keeps it valid before rendering.
    /// What: caps [`Self::selected`] at `palaces.len()` (the "All" row plus one
    /// row per palace).
    /// Test: `test_selected_clamp`.
    pub fn clamp_selection(&mut self) {
        if self.selected > self.last_row() {
            self.selected = self.last_row();
        }
    }

    /// Recompute the scroll offset so the selected row fits a `visible` window.
    ///
    /// Why: the PALACES panel is a fixed-height viewport; when the list has
    /// more rows than fit, the panel must scroll so [`Self::selected`] is never
    /// drawn off-screen — otherwise `↑`/`↓` appear to do nothing past the edge.
    /// What: given the panel's visible row count, shifts [`Self::scroll_offset`]
    /// down when the cursor falls below the window and up when it rises above
    /// it, leaving it untouched while the cursor is already in view. A zero
    /// `visible` is treated as one row so the offset always tracks the cursor.
    /// Test: `test_scroll_offset`.
    pub fn sync_scroll(&mut self, visible: usize) {
        let cursor = self.selected;
        self.sync_scroll_to(cursor, visible);
    }

    /// Recompute the scroll offset for an arbitrary cursor row.
    ///
    /// Why: when filtering, sorting, or grouping reorders the rendered rows,
    /// `Self::selected` (an index into the original `palaces` array) no
    /// longer matches the row's on-screen position. The renderer must pass
    /// in the *visible* row index so the viewport scrolls to the row the
    /// user actually sees as selected.
    /// What: identical scroll math to [`Self::sync_scroll`] but anchored on
    /// the supplied `cursor_row` instead of `self.selected`.
    /// Test: `test_sync_scroll_to_follows_sorted_order`.
    pub fn sync_scroll_to(&mut self, cursor_row: usize, visible: usize) {
        let window = visible.max(1);
        if cursor_row >= self.scroll_offset + window {
            self.scroll_offset = cursor_row + 1 - window;
        } else if cursor_row < self.scroll_offset {
            self.scroll_offset = cursor_row;
        }
    }

    /// Whether the "All palaces" entry is currently selected.
    ///
    /// Why: when "All" is selected the UI fans recalls out across every palace
    /// and aggregates the activity feed and statistics.
    /// What: returns `true` exactly when the cursor is on row 0.
    /// Test: `test_all_selector`.
    pub fn is_all_selected(&self) -> bool {
        self.selected == 0
    }

    /// The id of the currently selected single palace, if any.
    ///
    /// Why: `[Enter]` recalls and the log labels the selected palace; neither
    /// applies to a single palace when "All" is selected.
    /// What: returns `Some(id)` for the palace at cursor row `n ≥ 1`, or `None`
    /// when "All" is selected or the palace list is empty.
    /// Test: `test_selected_id`.
    pub fn selected_id(&self) -> Option<&str> {
        if self.selected == 0 {
            return None;
        }
        self.palaces.get(self.selected - 1).map(|p| p.id.as_str())
    }

    /// Clamp the selection to the currently visible (filtered + sorted) list.
    ///
    /// Why: when the filter changes the selected palace may no longer appear in
    /// the visible subset, so arrow navigation would jump unpredictably; this
    /// drops the cursor back to "All" (row 0) in that case so navigation always
    /// starts from a visible row.
    /// What: if `selected` is non-zero and the corresponding palace id is not in
    /// the visible id list, resets `selected` to 0.
    /// Test: `test_clamp_to_visible`.
    pub fn clamp_to_visible(&mut self) {
        if self.selected == 0 {
            return;
        }
        let Some(current_id) = self.palaces.get(self.selected - 1).map(|p| p.id.clone()) else {
            self.selected = 0;
            return;
        };
        let ids = visible_palace_ids(self);
        if !ids.iter().any(|id| id == &current_id) {
            self.selected = 0;
        }
    }

    /// The scope filter for the activity feed and statistics panels.
    ///
    /// Why: the right-hand panels render the selected palace's events / stats,
    /// or every palace's when "All" is selected; this folds the cursor into the
    /// `Option<&str>` filter [`ActivityLog::tail_scoped`] expects.
    /// What: returns `None` when "All" is selected (un-filtered) or `Some(id)`
    /// for the selected single palace.
    /// Test: `test_all_selector`.
    pub fn scope_filter(&self) -> Option<&str> {
        self.selected_id()
    }
}

/// Run the trusty-memory monitor TUI.
///
/// Why: the single entry point the `monitor tui` subcommand of `trusty-memory`
/// calls.
/// What: resolves the daemon URL from the service lock file and delegates to
/// [`run_with_url`].
/// Test: the pure pieces are unit-tested; this thin glue is exercised by
/// launching the UI.
pub async fn run() -> anyhow::Result<()> {
    run_with_url(resolve_memory_url()).await
}

/// Run the memory TUI against an explicit daemon URL.
///
/// Why: separated from [`run`] so a future CLI flag can override the resolved
/// address, and so terminal setup/teardown lives in one place.
/// What: builds the client and state, enters raw mode + the alternate screen,
/// runs [`run_loop`], and unconditionally restores the terminal even on error.
/// Test: terminal glue is exercised by launching the UI.
pub async fn run_with_url(base_url: String) -> anyhow::Result<()> {
    let mut client = MemoryClient::new(base_url.clone());
    let mut state = MemoryTuiState::new(base_url);

    let mut terminal = enter_tui()?;
    let result = run_loop(&mut terminal, &mut state, &mut client).await;
    leave_tui(&mut terminal)?;
    result
}

/// Poll the trusty-memory daemon and fold the result into `state`.
///
/// Why: keeps the per-poll I/O out of the event loop so the loop can re-poll
/// on demand as well as on its timer.
/// What: re-resolves the URL when the daemon is offline, calls `fetch_all`, and
/// updates the status, aggregate stats, palace list, and selection clamp.
/// Test: thin I/O glue; the pure clamp is unit-tested.
async fn poll_daemon(state: &mut MemoryTuiState, client: &mut MemoryClient) {
    if !state.daemon_status.is_online() {
        let resolved = resolve_memory_url();
        if resolved != client.base_url() {
            client.set_base_url(resolved.clone());
            state.base_url = resolved;
        }
    }
    match client.fetch_all().await {
        Ok(data) => {
            state.daemon_status = DaemonStatus::Online {
                version: data.version.clone(),
                uptime_secs: 0,
            };
            state.palaces = data.palaces.clone();
            state.status = Some(data);
            state.clamp_selection();
        }
        Err(e) => {
            state.daemon_status = DaemonStatus::Offline {
                last_error: e.to_string(),
            };
        }
    }
}

/// Run a recall and append the hits to the activity log.
///
/// Why: pressing `[Enter]` in the recall bar runs a memory recall; the
/// operator sees the results inline in the ACTIVITY panel. The recall endpoint
/// is inherently cross-palace, so when a single palace is selected the hits
/// are filtered to that palace; when "All palaces" is selected every hit is
/// shown.
/// What: calls `client.recall`, then — for the "All" selection — appends a
/// daemon-wide `recall "<q>" → N results` summary plus one `palace_id`-scoped
/// `· [palace] snippet` continuation per hit. For a single palace it appends a
/// palace-scoped summary counting only that palace's hits and a continuation
/// per kept hit. An empty query is a no-op; transport errors are logged scoped
/// to the selection.
/// Test: thin I/O glue; result projection is tested in `memory_client`.
async fn run_recall(state: &mut MemoryTuiState, client: &MemoryClient) {
    let query = state.input.trim().to_string();
    if query.is_empty() {
        return;
    }
    let scope = state.selected_id().map(str::to_string);
    match client.recall(&query, RECALL_TOP_K).await {
        Ok(hits) => match &scope {
            // "All palaces": one daemon-wide summary, each hit scoped to its
            // own palace so the per-palace feed still shows it.
            None => {
                state
                    .log
                    .push(format!("recall \"{query}\" (all) → {} results", hits.len()));
                for hit in &hits {
                    let palace = if hit.palace_id.is_empty() {
                        "?"
                    } else {
                        hit.palace_id.as_str()
                    };
                    state
                        .log
                        .push_raw_scoped(palace, format!("  · [{palace}] {}", hit.snippet));
                }
            }
            // A single palace: keep only that palace's hits.
            Some(id) => {
                let kept: Vec<&RecallHit> = hits.iter().filter(|h| h.palace_id == *id).collect();
                state
                    .log
                    .push_scoped(id, format!("recall \"{query}\"{} results", kept.len()));
                for hit in kept {
                    state
                        .log
                        .push_raw_scoped(id, format!("  · {}", hit.snippet));
                }
            }
        },
        Err(e) => match &scope {
            None => state
                .log
                .push(format!("recall \"{query}\" (all) failed: {e}")),
            Some(id) => state
                .log
                .push_scoped(id, format!("recall \"{query}\" failed: {e}")),
        },
    }
    state.input.clear();
}

/// Append a streamed `/sse` event to the activity log, scoped to its palace.
///
/// Why: the SSE task forwards [`MemoryEvent`]s through a channel; the event
/// loop drains them and this turns each into a human-readable log entry. The
/// drawer events concern one palace, so they are tagged with its id and the
/// per-palace activity feed keeps only its own events.
/// What: `DreamCompleted` records a daemon-wide header plus an indented
/// merge/prune/compact line; `DrawerAdded` / `DrawerDeleted` record a single
/// line each scoped to `palace_id`; `PalaceCreated` records a daemon-wide line
/// (the new palace has no id yet on the wire).
/// Test: `test_log_append_dream`, `test_apply_memory_event`.
pub fn apply_memory_event(state: &mut MemoryTuiState, event: MemoryEvent) {
    match event {
        MemoryEvent::DreamCompleted {
            merged,
            pruned,
            compacted,
        } => {
            state.log.push("SSE: dream_completed");
            state.log.push_raw(format!(
                "  merged: {merged}  pruned: {pruned}  compacted: {compacted}"
            ));
        }
        MemoryEvent::DrawerAdded {
            palace_id,
            drawer_count,
        } => {
            state.log.push_scoped(
                &palace_id,
                format!("SSE: drawer added → {palace_id} ({drawer_count})"),
            );
        }
        MemoryEvent::DrawerDeleted {
            palace_id,
            drawer_count,
        } => {
            state.log.push_scoped(
                &palace_id,
                format!("SSE: drawer deleted → {palace_id} ({drawer_count})"),
            );
        }
        MemoryEvent::PalaceCreated { name } => {
            state.log.push(format!("SSE: palace created → {name}"));
        }
    }
}

/// The memory TUI event loop: poll, render, handle input, drain SSE events.
///
/// Why: kept separate from [`run_with_url`] so terminal setup/teardown wraps it
/// cleanly.
/// What: polls the daemon immediately and spawns the `/sse` subscription task,
/// then renders every frame while polling the keyboard every 50 ms; re-polls on
/// the 2 s timer and drains SSE events via `try_recv`. `[d]` triggers a dream
/// cycle, `[Enter]` runs a recall; `Tab`, arrows, `?`, `q`/`Esc`, and `Ctrl-C`
/// behave per [`KEY_HINT`].
/// Test: the pure pieces (state, log, rendering helpers) are unit-tested.
async fn run_loop<B: ratatui::backend::Backend>(
    terminal: &mut Terminal<B>,
    state: &mut MemoryTuiState,
    client: &mut MemoryClient,
) -> anyhow::Result<()> {
    poll_daemon(state, client).await;
    let mut last_poll = Instant::now();

    // Subscribe to the daemon's /sse stream on a background task.
    let (sse_tx, mut sse_rx) = mpsc::channel::<MemoryEvent>(64);
    let sse_client = client.clone();
    tokio::spawn(async move {
        sse_client.sse_stream(sse_tx).await;
    });

    loop {
        terminal.draw(|f| render(f, state))?;
        // `terminal.draw` requires `state` mutably (the renderer scrolls the
        // palace list); the closure reborrows it for the rest of the loop.

        // Drain any SSE events the subscription task produced since last frame.
        while let Ok(event) = sse_rx.try_recv() {
            apply_memory_event(state, event);
        }

        let key = if event::poll(INPUT_POLL)? {
            match event::read()? {
                Event::Key(key) => Some(key),
                _ => None,
            }
        } else {
            None
        };
        if let Some(key) = key
            && key.kind != KeyEventKind::Release
        {
            // Ctrl-C always quits, regardless of focus or the help overlay.
            if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
                return Ok(());
            }
            if state.show_help {
                if matches!(key.code, KeyCode::Char('?') | KeyCode::Esc) {
                    state.show_help = false;
                } else if key.code == KeyCode::Char('q') {
                    return Ok(());
                }
                continue;
            }
            match (state.focus, key.code) {
                // Filter-active bindings come first — they capture characters,
                // backspace, Esc, and Enter before the general List handlers.
                (MemoryFocus::List, KeyCode::Esc) if state.filter_active => {
                    // Keep the filter text so the user can re-activate.
                    state.filter_active = false;
                }
                (MemoryFocus::List, KeyCode::Enter) if state.filter_active => {
                    state.filter_active = false;
                }
                (MemoryFocus::List, KeyCode::Backspace) if state.filter_active => {
                    state.filter.pop();
                    state.clamp_to_visible();
                }
                (MemoryFocus::List, KeyCode::Char(c)) if state.filter_active => {
                    state.filter.push(c);
                    state.clamp_to_visible();
                }
                // Tab is a no-op while the filter is active — otherwise it
                // would steal focus away from the list and break filter input.
                (MemoryFocus::List, KeyCode::Tab) if state.filter_active => {}
                (_, KeyCode::Char('?')) => state.show_help = true,
                (_, KeyCode::Tab) => state.toggle_focus(),
                (_, KeyCode::Esc) => return Ok(()),
                // List-focus bindings.
                (MemoryFocus::List, KeyCode::Char('q')) => return Ok(()),
                (MemoryFocus::List, KeyCode::Up) => navigate_up_visible(state),
                (MemoryFocus::List, KeyCode::Down) => navigate_down_visible(state),
                (MemoryFocus::List, KeyCode::Char('/')) => {
                    state.filter_active = true;
                    state.filter.clear();
                }
                (MemoryFocus::List, KeyCode::Char('s')) => {
                    state.sort_key = state.sort_key.next();
                }
                (MemoryFocus::List, KeyCode::Char('g')) => {
                    state.group_by_project = !state.group_by_project;
                }
                (MemoryFocus::List, KeyCode::Char('d')) => {
                    state.log.push("dream cycle triggered");
                    match client.dream_run().await {
                        Ok(stats) => state.log.push_raw(format!(
                            "  merged: {}  pruned: {}  compacted: {}",
                            stats.merged, stats.pruned, stats.compacted
                        )),
                        Err(e) => state.log.push(format!("dream failed: {e}")),
                    }
                    poll_daemon(state, client).await;
                    last_poll = Instant::now();
                }
                // Input-focus bindings.
                (MemoryFocus::Input, KeyCode::Enter) => {
                    run_recall(state, client).await;
                }
                (MemoryFocus::Input, KeyCode::Backspace) => {
                    state.input.pop();
                }
                (MemoryFocus::Input, KeyCode::Char(c)) => state.input.push(c),
                _ => {}
            }
        }

        if last_poll.elapsed() >= REFRESH_INTERVAL {
            poll_daemon(state, client).await;
            last_poll = Instant::now();
        }
    }
}

/// The body text for the help overlay, one binding per line.
///
/// Why: kept separate so a test can assert every binding is documented.
/// What: returns the multi-line help string.
/// Test: `test_help_text_lists_bindings`.
pub fn help_text() -> String {
    [
        "  Tab     switch focus between the palace list and the recall bar",
        "  ↑ / ↓   move the palace selection (when the list has focus)",
        "  All     the top list row fans recalls / stats across every palace",
        "  /       activate the inline palace filter (Esc / Enter close)",
        "  s       cycle palace sort: Activity → Name → Vectors",
        "  g       toggle grouping by inferred project",
        "  d       run a dream cycle across every palace",
        "  Enter   run a recall query — all palaces, or the selected one",
        "  ?       toggle this help overlay",
        "  q / Esc quit",
    ]
    .join("\n")
}

/// Format one palace as a fixed-width table row.
///
/// Why: the PALACES panel lists every palace with its vector count in aligned
/// columns; isolating the formatter makes the alignment unit-testable.
/// What: returns `> <name padded to 10>  <count>v`, where the leading marker
/// is `>` for the selected row and a space otherwise.
/// Test: `test_palace_row_display`.
pub fn palace_row(palace: &PalaceRow, selected: bool) -> String {
    let marker = if selected { ">" } else { " " };
    let label = if palace.name.is_empty() {
        &palace.id
    } else {
        &palace.name
    };
    format!(
        "{marker} {:<10} {:>7}v",
        truncate(label, 10),
        format_count(palace.vector_count),
    )
}

/// One rendered row of the PALACES panel.
///
/// Why: the renderer styles four row kinds differently — the "All" row is
/// bold, group headers are bold yellow and non-selectable, the selected row is
/// highlighted, ordinary rows are plain — so the line builder must surface
/// which kind each row is rather than just a bool.
/// What: the row `text`, whether it is `selected`, whether it is the synthetic
/// `is_all` ("All palaces") row, and whether it is a group header (non-
/// selectable when grouping by project).
/// Test: `test_palace_lines`, `test_all_selector`, `test_palace_lines_grouped`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PalaceListRow {
    /// The fully-formatted row text.
    pub text: String,
    /// Whether this row is the current selection.
    pub selected: bool,
    /// Whether this row is the synthetic "All palaces" entry.
    pub is_all: bool,
    /// Whether this row is a non-selectable group header.
    pub is_header: bool,
}

/// Format an indented palace row for use under a group header.
///
/// Why: when the list is grouped, palace rows are inset one extra space and
/// the name column shrinks by one to keep the count column aligned with the
/// flat layout.
/// What: returns `"  <name padded to 9>  <count>v"`, with `>` replacing the
/// leading space when `selected`.
/// Test: `test_palace_lines_grouped`.
fn palace_row_indented(palace: &PalaceRow, selected: bool) -> String {
    let marker = if selected { ">" } else { " " };
    let label = if palace.name.is_empty() {
        &palace.id
    } else {
        &palace.name
    };
    format!(
        "{marker}  {:<9} {:>7}v",
        truncate(label, 9),
        format_count(palace.vector_count),
    )
}

/// Apply [`MemoryTuiState::filter`] and [`MemoryTuiState::sort_key`] to the
/// state's palaces, returning the visible subset in display order.
///
/// Why: delegates to the shared [`tui_common::filtered_sorted`] so memory and
/// search apply identical filter / sort rules. Kept as a memory-named wrapper
/// for the existing tests and callers.
/// What: thin wrapper over [`tui_common::filtered_sorted`].
/// Test: `test_apply_filter`, `test_apply_sort_*`.
pub fn filtered_sorted_palaces(state: &MemoryTuiState) -> Vec<PalaceRow> {
    tui_common::filtered_sorted(&state.palaces, &state.filter, state.sort_key)
}

/// Ids of the rows the user can navigate between, in visible display order.
///
/// Why: thin wrapper over the shared [`tui_common::visible_ids`].
/// What: delegates to the shared helper with the memory state's fields.
/// Test: `test_visible_palace_ids`, `test_navigate_visible`.
pub fn visible_palace_ids(state: &MemoryTuiState) -> Vec<String> {
    tui_common::visible_ids(
        &state.palaces,
        &state.filter,
        state.sort_key,
        state.group_by_project,
    )
}

/// Move the cursor up one row in the visible (filtered + sorted) list.
///
/// Why: thin wrapper over the shared [`tui_common::navigate_up`].
/// What: delegates and writes back the new cursor.
/// Test: `test_navigate_visible`.
pub fn navigate_up_visible(state: &mut MemoryTuiState) {
    state.selected = tui_common::navigate_up(
        &state.palaces,
        state.selected,
        &state.filter,
        state.sort_key,
        state.group_by_project,
    );
}

/// Move the cursor down one row in the visible (filtered + sorted) list.
///
/// Why: thin wrapper over the shared [`tui_common::navigate_down`].
/// What: delegates and writes back the new cursor.
/// Test: `test_navigate_visible`.
pub fn navigate_down_visible(state: &mut MemoryTuiState) {
    state.selected = tui_common::navigate_down(
        &state.palaces,
        state.selected,
        &state.filter,
        state.sort_key,
        state.group_by_project,
    );
}

/// Row index — within the rendered `palace_lines` output — that the cursor
/// currently sits on.
///
/// Why: ratatui's `ListState::with_selected` and the viewport scroll math
/// both index into the rendered list, but `state.selected` is an index into
/// the *original* `state.palaces` Vec. After a filter, sort, or grouping
/// reorders rows, the two indices diverge and the highlight + scroll latch
/// onto the wrong on-screen line. This helper bridges them: given the same
/// state the renderer sees, it returns the visible row at which the current
/// selection is drawn so the highlight follows the sorted order.
/// What: returns `0` when "All" is selected; otherwise walks
/// [`palace_lines`] looking for the row whose `selected` flag is set and
/// returns its index. Falls back to `0` (the "All" row) when no matching
/// row is found, which mirrors how `clamp_to_visible` collapses a hidden
/// selection back to "All".
/// Test: `test_visible_selected_row_follows_sort`,
/// `test_visible_selected_row_follows_group`.
pub fn visible_selected_row(state: &MemoryTuiState) -> usize {
    if state.selected == 0 {
        return 0;
    }
    palace_lines(state)
        .iter()
        .position(|row| row.selected)
        .unwrap_or(0)
}

/// Build the rows for the PALACES panel body.
///
/// Why: separating row construction from the ratatui widgets lets a test
/// assert the rendered content without a terminal backend.
/// What: returns the synthetic "All palaces" row first (carrying the summed
/// vector count across every palace), then either a flat list of filtered +
/// sorted palace rows, or — when [`MemoryTuiState::group_by_project`] is set —
/// non-selectable `── <project> ──` group headers interleaved with their
/// member palaces. With no palaces the "All" row is still shown followed by a
/// placeholder line.
/// Test: `test_palace_lines`, `test_all_selector`, `test_palace_lines_grouped`.
pub fn palace_lines(state: &MemoryTuiState) -> Vec<PalaceListRow> {
    let mut rows: Vec<PalaceListRow> = Vec::with_capacity(state.palaces.len() + 1);

    // The synthetic "All palaces" row always leads the list — including when
    // filtering or grouping is active. The label may be wider than the per-
    // palace name column — it is shown in full.
    let total_vectors: u64 = state.palaces.iter().map(|p| p.vector_count).sum();
    let all_selected = state.selected == 0;
    let all_marker = if all_selected { ">" } else { " " };
    rows.push(PalaceListRow {
        text: format!("{all_marker} {ALL_LABEL}  {}v", format_count(total_vectors),),
        selected: all_selected,
        is_all: true,
        is_header: false,
    });

    if state.palaces.is_empty() {
        rows.push(PalaceListRow {
            text: "  (no palaces)".to_string(),
            selected: false,
            is_all: false,
            is_header: false,
        });
        return rows;
    }

    let visible = filtered_sorted_palaces(state);
    if visible.is_empty() {
        rows.push(PalaceListRow {
            text: "  (no matches)".to_string(),
            selected: false,
            is_all: false,
            is_header: false,
        });
        return rows;
    }

    // We need to compute the cursor row each visible palace lives at. The cursor
    // addresses the *original* `state.palaces` indices (cursor n → palaces[n-1])
    // so we look up each visible palace's original index by id.
    let cursor_for = |p: &PalaceRow| -> usize {
        state
            .palaces
            .iter()
            .position(|orig| orig.id == p.id)
            .map(|i| i + 1)
            .unwrap_or(0)
    };

    if state.group_by_project {
        // Collect distinct projects in the order they first appear in `visible`.
        let mut seen: Vec<String> = Vec::new();
        for p in &visible {
            let proj = p.project().to_string();
            if !seen.iter().any(|s| s == &proj) {
                seen.push(proj);
            }
        }
        for project in &seen {
            rows.push(PalaceListRow {
                text: format!("── {project} ─────"),
                selected: false,
                is_all: false,
                is_header: true,
            });
            for palace in visible.iter().filter(|p| p.project() == project) {
                let cursor = cursor_for(palace);
                let selected = cursor == state.selected;
                rows.push(PalaceListRow {
                    text: palace_row_indented(palace, selected),
                    selected,
                    is_all: false,
                    is_header: false,
                });
            }
        }
    } else {
        for palace in &visible {
            let cursor = cursor_for(palace);
            let selected = cursor == state.selected;
            rows.push(PalaceListRow {
                text: palace_row(palace, selected),
                selected,
                is_all: false,
                is_header: false,
            });
        }
    }
    rows
}

/// Build the STATISTICS panel lines for the current selection.
///
/// Why: the bottom-right panel shows counts and sizes for whichever palace is
/// selected, or aggregate totals plus a per-palace breakdown when "All" is
/// selected; isolating the builder makes the content testable without a
/// terminal.
/// What: for a single palace, returns its name, vector count, and id. For the
/// "All" selection, returns the palace count and the daemon's aggregate
/// vector / drawer / KG-triple totals, plus one `· <name>: <vectors>`
/// breakdown line per palace.
/// Test: `test_stats_lines`.
pub fn stats_lines(state: &MemoryTuiState) -> Vec<String> {
    if state.is_all_selected() {
        let stats = state.status.clone().unwrap_or_default();
        let mut lines = vec![
            format!("Scope:        {ALL_LABEL}"),
            format!("Palaces:      {}", state.palaces.len()),
            format!("Vectors:      {}", format_count(stats.total_vectors)),
            format!("Drawers:      {}", format_count(stats.total_drawers)),
            format!("KG triples:   {}", format_count(stats.total_kg_triples)),
        ];
        if state.palaces.is_empty() {
            lines.push("(no palaces)".to_string());
        } else {
            lines.push(String::new());
            for palace in &state.palaces {
                let label = if palace.name.is_empty() {
                    &palace.id
                } else {
                    &palace.name
                };
                lines.push(format!(
                    "  · {:<12} {:>7}v",
                    truncate(label, 12),
                    format_count(palace.vector_count),
                ));
            }
        }
        return lines;
    }

    match state.palaces.get(state.selected.saturating_sub(1)) {
        Some(palace) => {
            let label = if palace.name.is_empty() {
                "(unnamed)"
            } else {
                palace.name.as_str()
            };
            vec![
                format!("Palace:       {label}"),
                format!("Vectors:      {}", format_count(palace.vector_count)),
                format!("Id:           {}", palace.id),
            ]
        }
        None => vec!["(no palace selected)".to_string()],
    }
}

/// Build the title-bar line for the memory UI.
///
/// Why: the top row shows the daemon name, version, and liveness badge at a
/// glance; isolating it keeps `render` terse and the text testable.
/// What: returns `trusty-memory vX  [●] <status>` — the daemon's reported
/// version is appended when it is online.
/// Test: `test_title_line`.
pub fn title_line(state: &MemoryTuiState) -> String {
    let (glyph, label) = state.daemon_status.badge();
    match &state.daemon_status {
        DaemonStatus::Online { version, .. } => {
            format!("trusty-memory v{version}  [{glyph}] {label}")
        }
        _ => format!(
            "trusty-memory v{VERSION}  [{glyph}] {label}  {}",
            state.base_url
        ),
    }
}

/// Draw the memory TUI frame.
///
/// Why: the single entry point the event loop calls each tick.
/// What: a 4-row vertical layout — title bar, the PALACES / right-pane split,
/// the RECALL input bar, and the key-hint footer. The right pane is itself
/// split vertically into an ACTIVITY feed (top 60 %) and a STATISTICS panel
/// (bottom 40 %), both scoped to the selected palace — or aggregated when "All"
/// is selected. A centred help overlay floats on top when `show_help` is set.
/// Test: line content is unit-tested via the `*_lines` helpers; this glue is
/// exercised by `test_render_smoke`.
pub fn render(frame: &mut Frame, state: &mut MemoryTuiState) {
    let area = frame.area();
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // title bar
            Constraint::Min(4),    // panels
            Constraint::Length(3), // recall input
            Constraint::Length(1), // key hint
        ])
        .split(area);

    // Title bar.
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            title_line(state),
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ))),
        rows[0],
    );

    // PALACES on the left, the ACTIVITY / STATISTICS stack on the right.
    let split = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Length(left_panel_width(area.width)),
            Constraint::Min(10),
        ])
        .split(rows[1]);

    let list_focused = state.focus == MemoryFocus::List;
    let palace_items: Vec<ListItem> = palace_lines(state)
        .into_iter()
        .map(|row| {
            let style = if row.selected {
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Cyan)
                    .add_modifier(Modifier::BOLD)
            } else if row.is_header {
                // Group headers — bold yellow, non-selectable.
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD)
            } else if row.is_all {
                // The unselected "All" row stays distinct — bold yellow.
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default()
            };
            ListItem::new(Line::from(Span::styled(row.text, style)))
        })
        .collect();

    // When the inline filter is active or carries text, split the left column
    // vertically so the filter input renders above the palace list.
    let show_filter_bar = state.filter_active || !state.filter.is_empty();
    let (filter_area, list_area) = if show_filter_bar {
        let inner = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(3), Constraint::Min(3)])
            .split(split[0]);
        (Some(inner[0]), inner[1])
    } else {
        (None, split[0])
    };

    if let Some(area) = filter_area {
        let border_color = if state.filter_active {
            Color::Yellow
        } else {
            Color::DarkGray
        };
        frame.render_widget(
            Paragraph::new(Line::from(vec![
                Span::styled("🔍 ", Style::default().fg(Color::Yellow)),
                Span::styled(
                    state.filter.as_str().to_string(),
                    Style::default().fg(Color::White),
                ),
                Span::styled(
                    if state.filter_active { "_" } else { "" },
                    Style::default().fg(Color::Cyan),
                ),
            ]))
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(
                        Style::default()
                            .fg(border_color)
                            .add_modifier(Modifier::BOLD),
                    )
                    .title(Span::styled(
                        " FILTER ",
                        Style::default()
                            .fg(Color::Yellow)
                            .add_modifier(Modifier::BOLD),
                    )),
            ),
            area,
        );
    }

    // Scroll the PALACES list so the selected row stays visible: the panel
    // height minus its two border rows is the visible window. Both the scroll
    // anchor and the ratatui ListState selection index must reference the
    // *displayed* row (filter + sort + grouping reorder the rendered rows
    // relative to `state.palaces`), so we look up the visible row index of
    // the currently selected palace once and use it for both.
    let palace_visible = list_area.height.saturating_sub(2) as usize;
    let visible_row = visible_selected_row(state);
    state.sync_scroll_to(visible_row, palace_visible);
    let mut palace_state = ListState::default()
        .with_offset(state.scroll_offset)
        .with_selected(Some(visible_row));
    let palace_title = format!("PALACES [{}]", sort_label(state.sort_key));
    frame.render_stateful_widget(
        List::new(palace_items).block(panel_block(&palace_title, list_focused)),
        list_area,
        &mut palace_state,
    );

    // Right pane: ACTIVITY (top) over STATISTICS (bottom).
    let right = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(tui_common::ACTIVITY_PERCENT),
            Constraint::Percentage(100 - tui_common::ACTIVITY_PERCENT),
        ])
        .split(split[1]);

    // ACTIVITY panel — the tail of the scoped feed that fits the panel height.
    let scope = state.scope_filter();
    let activity_title = match scope {
        Some(id) => format!("ACTIVITY — {id}"),
        None => format!("ACTIVITY — {ALL_LABEL}"),
    };
    let activity_height = right[0].height.saturating_sub(2) as usize;
    let activity_items: Vec<ListItem> = if state.log.has_scoped(scope) {
        state
            .log
            .tail_scoped(scope, activity_height.max(1))
            .map(|line| ListItem::new(line.as_str()))
            .collect()
    } else {
        vec![ListItem::new("(no activity yet)")]
    };
    frame.render_widget(
        List::new(activity_items).block(panel_block(&activity_title, false)),
        right[0],
    );

    // STATISTICS panel — counts and sizes for the selection.
    let stats_items: Vec<ListItem> = stats_lines(state).into_iter().map(ListItem::new).collect();
    frame.render_widget(
        List::new(stats_items).block(panel_block("STATISTICS", false)),
        right[1],
    );

    // RECALL input bar.
    let input_focused = state.focus == MemoryFocus::Input;
    let cursor = if input_focused { "_" } else { "" };
    let input_style = if input_focused {
        Style::default().fg(Color::Cyan)
    } else {
        Style::default().fg(Color::DarkGray)
    };
    frame.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled("RECALL ▶ ", Style::default().fg(Color::Yellow)),
            Span::styled(format!("{}{cursor}", state.input), input_style),
        ]))
        .block(panel_block("RECALL", input_focused)),
        rows[2],
    );

    // Key-hint footer.
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            KEY_HINT,
            Style::default().fg(Color::DarkGray),
        ))),
        rows[3],
    );

    if state.show_help {
        tui_common::render_help_overlay(frame, &help_text());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::monitor::utils::timestamped;
    use ratatui::{Terminal, backend::TestBackend};

    /// A state with two palaces and aggregate stats for rendering tests.
    fn sample_state() -> MemoryTuiState {
        let mut state = MemoryTuiState::new("http://127.0.0.1:7070");
        state.daemon_status = DaemonStatus::Online {
            version: "0.1.54".into(),
            uptime_secs: 0,
        };
        state.palaces = vec![
            PalaceRow {
                id: "default".into(),
                name: "default".into(),
                vector_count: 8_400,
                ..Default::default()
            },
            PalaceRow {
                id: "work".into(),
                name: "work".into(),
                vector_count: 0,
                ..Default::default()
            },
        ];
        state.status = Some(MemoryData {
            version: "0.1.54".into(),
            palace_count: 2,
            total_drawers: 14,
            total_vectors: 8_400,
            total_kg_triples: 1_200,
            palaces: state.palaces.clone(),
        });
        state
    }

    #[test]
    fn test_new_state_defaults() {
        let state = MemoryTuiState::new("http://127.0.0.1:7070");
        assert_eq!(state.base_url, "http://127.0.0.1:7070");
        assert!(matches!(state.daemon_status, DaemonStatus::Connecting));
        assert!(state.status.is_none());
        assert!(state.palaces.is_empty());
        assert_eq!(state.selected, 0);
        assert!(state.log.is_empty());
        assert_eq!(state.focus, MemoryFocus::List);
        assert!(!state.show_help);
    }

    #[test]
    fn test_toggle_focus() {
        let mut state = MemoryTuiState::new("http://x");
        assert_eq!(state.focus, MemoryFocus::List);
        state.toggle_focus();
        assert_eq!(state.focus, MemoryFocus::Input);
        state.toggle_focus();
        assert_eq!(state.focus, MemoryFocus::List);
    }

    #[test]
    fn test_selected_clamp() {
        let mut state = sample_state();
        // The list has 1 ("All") + 2 palaces = 3 rows; the cursor stops at 2.
        for _ in 0..10 {
            state.select_down();
        }
        assert_eq!(state.selected, 2, "clamped to palaces.len()");
        for _ in 0..10 {
            state.select_up();
        }
        assert_eq!(state.selected, 0);
        // A shrunk palace list re-clamps the cursor (1 "All" + 1 palace = 1).
        state.selected = 2;
        state.palaces.truncate(1);
        state.clamp_selection();
        assert_eq!(state.selected, 1);
        // An empty list leaves only the "All" row at cursor 0.
        state.palaces.clear();
        state.selected = 9;
        state.clamp_selection();
        assert_eq!(state.selected, 0);
    }

    #[test]
    fn test_selected_id() {
        let mut state = sample_state();
        // Cursor 0 is "All" — no single palace.
        assert!(state.is_all_selected());
        assert_eq!(state.selected_id(), None);
        // Cursor 1 is the first palace.
        state.select_down();
        assert_eq!(state.selected_id(), Some("default"));
        state.select_down();
        assert_eq!(state.selected_id(), Some("work"));
        state.palaces.clear();
        state.clamp_selection();
        assert_eq!(state.selected_id(), None);
    }

    #[test]
    fn test_all_selector() {
        let mut state = sample_state();
        // The default selection is the "All palaces" row.
        assert!(state.is_all_selected());
        assert_eq!(state.scope_filter(), None);
        // Moving down off row 0 picks a single palace and a scoped filter.
        state.select_down();
        assert!(!state.is_all_selected());
        assert_eq!(state.scope_filter(), Some("default"));
        state.select_up();
        assert!(state.is_all_selected());

        // The palace list always leads with the "All" row.
        let rows = palace_lines(&state);
        assert_eq!(rows.len(), 3, "1 'All' row + 2 palaces");
        assert!(rows[0].is_all);
        assert!(rows[0].text.contains(ALL_LABEL));
        assert!(rows[0].selected, "'All' is selected by default");
        assert!(!rows[1].is_all);
        assert!(rows[1].text.contains("default"));
    }

    #[test]
    fn test_stats_lines() {
        let mut state = sample_state();
        // "All" selected → aggregate totals + per-palace breakdown.
        let all = stats_lines(&state);
        assert!(
            all.iter()
                .any(|l| l.contains("Palaces:") && l.contains('2'))
        );
        assert!(
            all.iter()
                .any(|l| l.contains("Vectors:") && l.contains("8,400"))
        );
        assert!(
            all.iter()
                .any(|l| l.contains("KG triples:") && l.contains("1,200"))
        );
        assert!(all.iter().any(|l| l.contains("default")));

        // A single palace selected → that palace's detail.
        state.select_down(); // cursor 1 → default
        let one = stats_lines(&state);
        assert!(
            one.iter()
                .any(|l| l.contains("Palace:") && l.contains("default"))
        );
        assert!(
            one.iter()
                .any(|l| l.contains("Vectors:") && l.contains("8,400"))
        );
        assert!(one.iter().any(|l| l.contains("Id:")));
    }

    #[test]
    fn test_palace_row_display() {
        // The selected row is marked `>`; columns are aligned and the count
        // carries a trailing `v`.
        let palace = PalaceRow {
            id: "default".into(),
            name: "default".into(),
            vector_count: 8_400,
            ..Default::default()
        };
        let selected = palace_row(&palace, true);
        assert!(selected.starts_with('>'), "selected marker: {selected}");
        assert!(selected.contains("default"));
        assert!(selected.contains("8,400v"));

        let unselected = palace_row(&palace, false);
        assert!(unselected.starts_with(' '), "unselected: {unselected}");

        // A nameless palace falls back to its id; a zero count still renders.
        let nameless = PalaceRow {
            id: "p-xyz".into(),
            name: String::new(),
            vector_count: 0,
            ..Default::default()
        };
        let row = palace_row(&nameless, false);
        assert!(row.contains("p-xyz"));
        assert!(row.contains("0v"));

        // A long name is truncated with an ellipsis.
        let long = PalaceRow {
            id: "x".into(),
            name: "a-very-long-palace-name".into(),
            vector_count: 1,
            ..Default::default()
        };
        assert!(palace_row(&long, false).contains(''));
    }

    #[test]
    fn test_palace_lines() {
        let state = sample_state();
        let rows = palace_lines(&state);
        // 1 "All" row + 2 palace rows.
        assert_eq!(rows.len(), 3);
        // Row 0 is "All", selected by default.
        assert!(rows[0].is_all);
        assert!(rows[0].selected);
        assert!(rows[0].text.contains(ALL_LABEL));
        assert!(rows[0].text.starts_with('>'));
        // Rows 1..3 are the palaces, unselected.
        assert!(!rows[1].is_all && !rows[1].selected);
        assert!(rows[1].text.contains("default"));
        assert!(rows[2].text.contains("work"));

        // An empty palace list still shows the "All" row plus a placeholder.
        let empty = MemoryTuiState::new("http://x");
        let rows = palace_lines(&empty);
        assert_eq!(rows.len(), 2);
        assert!(rows[0].is_all);
        assert!(rows[1].text.contains("no palaces"));
    }

    #[test]
    fn test_log_append_dream() {
        // A dream_completed SSE event appends a header line plus an indented
        // merge/prune/compact stats line.
        let mut state = MemoryTuiState::new("http://x");
        apply_memory_event(
            &mut state,
            MemoryEvent::DreamCompleted {
                merged: 3,
                pruned: 1,
                compacted: 0,
            },
        );
        let lines: Vec<&String> = state.log.iter().collect();
        assert_eq!(lines.len(), 2);
        assert!(lines[0].contains("SSE: dream_completed"));
        assert!(lines[0].starts_with('['), "header is timestamped");
        assert!(lines[1].contains("merged: 3"));
        assert!(lines[1].contains("pruned: 1"));
        assert!(lines[1].contains("compacted: 0"));
        // The continuation line is not timestamped — it reads as a sub-line.
        assert!(lines[1].starts_with("  "));
    }

    #[test]
    fn test_apply_memory_event() {
        let mut state = MemoryTuiState::new("http://x");
        apply_memory_event(
            &mut state,
            MemoryEvent::DrawerAdded {
                palace_id: "default".into(),
                drawer_count: 14,
            },
        );
        apply_memory_event(
            &mut state,
            MemoryEvent::DrawerDeleted {
                palace_id: "work".into(),
                drawer_count: 2,
            },
        );
        apply_memory_event(
            &mut state,
            MemoryEvent::PalaceCreated {
                name: "notes".into(),
            },
        );
        let lines: Vec<&String> = state.log.iter().collect();
        assert_eq!(lines.len(), 3);
        assert!(lines[0].contains("drawer added → default (14)"));
        assert!(lines[1].contains("drawer deleted → work (2)"));
        assert!(lines[2].contains("palace created → notes"));

        // Drawer events are scoped to their palace; the per-palace feed keeps
        // only its own drawer event plus the daemon-wide palace-created line.
        let default_feed: Vec<&String> = state.log.tail_scoped(Some("default"), 100).collect();
        assert_eq!(default_feed.len(), 2);
        assert!(
            default_feed
                .iter()
                .any(|l| l.contains("drawer added → default"))
        );
        assert!(
            default_feed
                .iter()
                .any(|l| l.contains("palace created → notes"))
        );
        assert!(
            !default_feed
                .iter()
                .any(|l| l.contains("drawer deleted → work"))
        );
    }

    #[test]
    fn test_log_capacity() {
        let mut state = MemoryTuiState::new("http://x");
        for i in 0..(ActivityLog::MAX_ENTRIES + 30) {
            state.log.push(format!("event {i}"));
        }
        assert_eq!(state.log.len(), ActivityLog::MAX_ENTRIES);
    }

    #[test]
    fn test_timestamped_format() {
        let line = timestamped("recall complete");
        assert!(line.starts_with('['));
        assert!(line.ends_with(" recall complete"));
        assert_eq!(line.as_bytes()[9], b']');
    }

    #[test]
    fn test_left_panel_width() {
        assert_eq!(left_panel_width(200), tui_common::LEFT_PANEL_MAX);
        assert_eq!(left_panel_width(60), 20);
    }

    #[test]
    fn test_truncate() {
        assert_eq!(truncate("work", 10), "work");
        assert_eq!(truncate("a-very-long-palace", 8), "a-very-…");
    }

    #[test]
    fn test_title_line() {
        let state = sample_state();
        let title = title_line(&state);
        assert!(title.contains("trusty-memory v0.1.54"));
        assert!(title.contains("online"));

        let mut offline = MemoryTuiState::new("http://127.0.0.1:7070");
        offline.daemon_status = DaemonStatus::Offline {
            last_error: "refused".into(),
        };
        let title = title_line(&offline);
        assert!(title.contains("offline"));
        assert!(title.contains("http://127.0.0.1:7070"));
    }

    #[test]
    fn test_palace_sort_key_cycle() {
        assert_eq!(PalaceSortKey::default(), PalaceSortKey::Activity);
        assert_eq!(PalaceSortKey::Activity.next(), PalaceSortKey::Name);
        assert_eq!(PalaceSortKey::Name.next(), PalaceSortKey::Count);
        assert_eq!(PalaceSortKey::Count.next(), PalaceSortKey::Activity);
        assert_eq!(sort_label(PalaceSortKey::Activity), "Activity");
        assert_eq!(sort_label(PalaceSortKey::Name), "Name");
        assert_eq!(sort_label(PalaceSortKey::Count), "Vectors");
    }

    /// State with four palaces spanning two projects, varied vector counts,
    /// and varied last_write_at timestamps. Used by the sort / filter / group
    /// tests.
    fn diverse_state() -> MemoryTuiState {
        use chrono::{TimeZone, Utc};
        let mut state = MemoryTuiState::new("http://127.0.0.1:7070");
        state.palaces = vec![
            PalaceRow {
                id: "trusty-search".into(),
                name: "trusty-search".into(),
                vector_count: 12,
                last_write_at: Some(Utc.with_ymd_and_hms(2026, 5, 1, 0, 0, 0).unwrap()),
                description: Some(
                    "Auto-registered from /Users/masa/Projects/trusty-tools/trusty-search".into(),
                ),
                ..Default::default()
            },
            PalaceRow {
                id: "trusty-memory".into(),
                name: "trusty-memory".into(),
                vector_count: 3_775,
                last_write_at: Some(Utc.with_ymd_and_hms(2026, 5, 18, 22, 29, 50).unwrap()),
                description: Some(
                    "Auto-registered from /Users/masa/Projects/trusty-tools/trusty-memory".into(),
                ),
                ..Default::default()
            },
            PalaceRow {
                id: "claude-mpm".into(),
                name: "claude-mpm".into(),
                vector_count: 6_163,
                last_write_at: Some(Utc.with_ymd_and_hms(2026, 5, 10, 0, 0, 0).unwrap()),
                description: Some("Auto-registered from /Users/masa/Projects/claude-mpm".into()),
                ..Default::default()
            },
            PalaceRow {
                id: "notes".into(),
                name: "notes".into(),
                vector_count: 100,
                last_write_at: None,
                description: None,
                ..Default::default()
            },
        ];
        state
    }

    #[test]
    fn test_apply_sort_activity() {
        // Activity: last_write_at desc, None last; vector_count desc tiebreak.
        let mut state = diverse_state();
        state.sort_key = PalaceSortKey::Activity;
        let rows = filtered_sorted_palaces(&state);
        assert_eq!(rows[0].id, "trusty-memory");
        assert_eq!(rows[1].id, "claude-mpm");
        assert_eq!(rows[2].id, "trusty-search");
        // None sorts last.
        assert_eq!(rows[3].id, "notes");
    }

    #[test]
    fn test_apply_sort_name() {
        let mut state = diverse_state();
        state.sort_key = PalaceSortKey::Name;
        let rows = filtered_sorted_palaces(&state);
        let names: Vec<&str> = rows.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["claude-mpm", "notes", "trusty-memory", "trusty-search"]
        );
    }

    #[test]
    fn test_apply_sort_vectors() {
        let mut state = diverse_state();
        state.sort_key = PalaceSortKey::Count;
        let rows = filtered_sorted_palaces(&state);
        assert_eq!(rows[0].id, "claude-mpm");
        assert_eq!(rows[1].id, "trusty-memory");
        assert_eq!(rows[2].id, "notes");
        assert_eq!(rows[3].id, "trusty-search");
    }

    #[test]
    fn test_apply_filter() {
        let mut state = diverse_state();
        // Case-insensitive substring match against name OR project.
        state.filter = "TRUSTY".into();
        let rows = filtered_sorted_palaces(&state);
        assert_eq!(rows.len(), 2);
        assert!(rows.iter().all(|p| p.name.contains("trusty")));

        // Match by project (description path basename).
        state.filter = "claude-mpm".into();
        let rows = filtered_sorted_palaces(&state);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].id, "claude-mpm");

        // No match → empty.
        state.filter = "nothing-here".into();
        assert!(filtered_sorted_palaces(&state).is_empty());

        // Empty filter → everything.
        state.filter.clear();
        assert_eq!(filtered_sorted_palaces(&state).len(), 4);
    }

    #[test]
    fn test_palace_lines_grouped() {
        let mut state = diverse_state();
        state.group_by_project = true;
        state.sort_key = PalaceSortKey::Name;
        let rows = palace_lines(&state);

        // "All" leads the list.
        assert!(rows[0].is_all);

        // Group headers appear and are non-selectable.
        let headers: Vec<&PalaceListRow> = rows.iter().filter(|r| r.is_header).collect();
        assert!(
            !headers.is_empty(),
            "grouping must emit at least one header"
        );
        for h in &headers {
            assert!(h.text.contains("──"));
            assert!(!h.selected);
        }
        // Project names appear in the header text.
        let header_text: String = headers
            .iter()
            .map(|h| h.text.clone())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(header_text.contains("trusty-memory") || header_text.contains("trusty-search"));
        assert!(header_text.contains("claude-mpm"));

        // Filter narrows grouping to matching projects only.
        state.filter = "claude".into();
        let rows = palace_lines(&state);
        let headers: Vec<&PalaceListRow> = rows.iter().filter(|r| r.is_header).collect();
        assert_eq!(headers.len(), 1);
        assert!(headers[0].text.contains("claude-mpm"));
    }

    #[test]
    fn test_help_text_lists_bindings() {
        let text = help_text();
        for token in ["Tab", "d ", "Enter", "?", "q ", "/", "s ", "g "] {
            assert!(text.contains(token), "help text missing {token}");
        }
    }

    #[test]
    fn test_scroll_offset() {
        // A list taller than its viewport must scroll so the cursor stays in
        // view; a list that fits leaves the offset pinned at zero.
        let mut state = sample_state();
        // 2 palaces + the "All" row = 3 rows; a 6-row window holds them all.
        for row in 0..=state.last_row() {
            state.selected = row;
            state.sync_scroll(6);
            assert_eq!(state.scroll_offset, 0, "no scroll while the list fits");
        }

        // Grow the list well past a 5-row window and walk the cursor down.
        state.palaces = (0..40)
            .map(|n| PalaceRow {
                id: format!("p-{n}"),
                name: format!("palace-{n}"),
                vector_count: 1,
                ..Default::default()
            })
            .collect();
        let window = 5;
        for row in 0..=state.last_row() {
            state.selected = row;
            state.sync_scroll(window);
            assert!(
                row >= state.scroll_offset && row < state.scroll_offset + window,
                "row {row} must be inside [{}, {})",
                state.scroll_offset,
                state.scroll_offset + window,
            );
        }
        // The cursor at the bottom pins the window against the list end.
        assert_eq!(state.scroll_offset, state.last_row() + 1 - window);

        // Walking back up drags the window up with the cursor.
        for row in (0..=state.last_row()).rev() {
            state.selected = row;
            state.sync_scroll(window);
            assert!(
                row >= state.scroll_offset && row < state.scroll_offset + window,
                "row {row} must stay visible while scrolling up",
            );
        }
        assert_eq!(state.scroll_offset, 0, "back at the top");
    }

    #[test]
    fn test_visible_palace_ids() {
        // Visible ids lead with the "All" sentinel, then follow the filtered +
        // sorted display order — not the original `state.palaces` order.
        let mut state = diverse_state();
        state.sort_key = PalaceSortKey::Name;
        let ids = visible_palace_ids(&state);
        assert_eq!(ids[0], tui_common::ALL_SENTINEL);
        // Alphabetical: claude-mpm, notes, trusty-memory, trusty-search.
        assert_eq!(
            &ids[1..],
            &[
                "claude-mpm".to_string(),
                "notes".to_string(),
                "trusty-memory".to_string(),
                "trusty-search".to_string(),
            ]
        );

        // A filter shrinks the visible list.
        state.filter = "trusty".into();
        let ids = visible_palace_ids(&state);
        assert_eq!(ids[0], tui_common::ALL_SENTINEL);
        assert_eq!(ids.len(), 3, "All + 2 trusty-* palaces");
    }

    #[test]
    fn test_navigate_visible() {
        // Navigation walks the visible (sorted) order, mapping back to
        // `state.selected` which indexes the original `state.palaces` array.
        let mut state = diverse_state();
        state.sort_key = PalaceSortKey::Name;
        // Visible order: All, claude-mpm, notes, trusty-memory, trusty-search.
        // Start at All.
        assert_eq!(state.selected, 0);
        navigate_down_visible(&mut state);
        assert_eq!(state.selected_id(), Some("claude-mpm"));
        navigate_down_visible(&mut state);
        assert_eq!(state.selected_id(), Some("notes"));
        navigate_down_visible(&mut state);
        assert_eq!(state.selected_id(), Some("trusty-memory"));
        navigate_down_visible(&mut state);
        assert_eq!(state.selected_id(), Some("trusty-search"));
        // At the bottom: another Down is a no-op.
        navigate_down_visible(&mut state);
        assert_eq!(state.selected_id(), Some("trusty-search"));
        // Walk back up to All.
        navigate_up_visible(&mut state);
        assert_eq!(state.selected_id(), Some("trusty-memory"));
        navigate_up_visible(&mut state);
        navigate_up_visible(&mut state);
        navigate_up_visible(&mut state);
        assert!(state.is_all_selected());
        // At the top: Up is a no-op.
        navigate_up_visible(&mut state);
        assert!(state.is_all_selected());

        // With a filter, navigation skips hidden rows.
        state.filter = "trusty".into();
        state.selected = 0;
        navigate_down_visible(&mut state);
        // First visible after All is trusty-memory (alphabetical among trusty-*).
        assert_eq!(state.selected_id(), Some("trusty-memory"));
        navigate_down_visible(&mut state);
        assert_eq!(state.selected_id(), Some("trusty-search"));
        navigate_down_visible(&mut state);
        // No more visible rows.
        assert_eq!(state.selected_id(), Some("trusty-search"));
    }

    #[test]
    fn test_visible_selected_row_follows_sort() {
        // The visible row index for the highlight must follow the rendered
        // (filter + sort) order, not the original `state.palaces` order.
        // Diverse palaces (in original order): trusty-search, trusty-memory,
        // claude-mpm, notes. Selecting "claude-mpm" places it at cursor 3
        // (index 2 + 1). With Name sort the displayed order is:
        //   0 All, 1 claude-mpm, 2 notes, 3 trusty-memory, 4 trusty-search
        // so the highlight must land on row 1, not row 3.
        let mut state = diverse_state();
        state.sort_key = PalaceSortKey::Name;
        let pos = state
            .palaces
            .iter()
            .position(|p| p.id == "claude-mpm")
            .expect("palace");
        state.selected = pos + 1;
        assert_eq!(state.selected, 3, "original index puts claude-mpm at 3");
        assert_eq!(
            visible_selected_row(&state),
            1,
            "claude-mpm is the first non-All row after Name sort",
        );

        // "All" always sits at row 0 regardless of sort.
        state.selected = 0;
        assert_eq!(visible_selected_row(&state), 0);

        // With Vectors sort the displayed order is:
        //   0 All, 1 claude-mpm (6163), 2 trusty-memory (3775),
        //   3 notes (100), 4 trusty-search (12)
        // so notes must land on row 3.
        state.sort_key = PalaceSortKey::Count;
        let pos = state
            .palaces
            .iter()
            .position(|p| p.id == "notes")
            .expect("palace");
        state.selected = pos + 1;
        assert_eq!(visible_selected_row(&state), 3);
    }

    #[test]
    fn test_visible_selected_row_follows_group() {
        // Grouping interleaves project headers (non-selectable) with palaces;
        // the highlight row must skip over them and follow the grouped layout.
        let mut state = diverse_state();
        state.sort_key = PalaceSortKey::Name;
        state.group_by_project = true;
        // Select "trusty-memory". The row layout starts with All, then the
        // first project header, then its palace rows; the exact row index
        // must match the position palace_lines marks as `selected`.
        let pos = state
            .palaces
            .iter()
            .position(|p| p.id == "trusty-memory")
            .expect("palace");
        state.selected = pos + 1;
        let expected = palace_lines(&state)
            .iter()
            .position(|row| row.selected)
            .expect("trusty-memory must appear in the grouped layout");
        assert_eq!(visible_selected_row(&state), expected);
        assert!(expected > 0, "highlight is not on the All row");
    }

    #[test]
    fn test_sync_scroll_to_follows_sorted_order() {
        // sync_scroll_to anchors the viewport on the *visible* row, so a
        // selection deep in the sorted list scrolls the window down even
        // when state.selected refers to a low index in the original Vec.
        let mut state = diverse_state();
        state.sort_key = PalaceSortKey::Name;
        // Visible order: All(0), claude-mpm(1), notes(2),
        //                trusty-memory(3), trusty-search(4).
        // Select trusty-search (original index 0 → state.selected = 1).
        state.selected = 1;
        let visible_row = visible_selected_row(&state);
        assert_eq!(visible_row, 4, "trusty-search is the last visible row");
        // A 3-row window must scroll so row 4 fits: offset = 4 + 1 - 3 = 2.
        state.sync_scroll_to(visible_row, 3);
        assert_eq!(state.scroll_offset, 2);
    }

    #[test]
    fn test_clamp_to_visible() {
        // When the filter hides the selected palace, clamp_to_visible drops
        // back to the "All" row so arrows resume from a visible position.
        let mut state = diverse_state();
        state.sort_key = PalaceSortKey::Name;
        // Select "claude-mpm" (cursor 3 in original order).
        let pos = state
            .palaces
            .iter()
            .position(|p| p.id == "claude-mpm")
            .expect("palace");
        state.selected = pos + 1;
        // Apply a filter that excludes it.
        state.filter = "trusty".into();
        state.clamp_to_visible();
        assert_eq!(state.selected, 0, "selection dropped to All");

        // When the selection is still visible, clamp_to_visible leaves it.
        state.filter = "trusty".into();
        let pos = state
            .palaces
            .iter()
            .position(|p| p.id == "trusty-memory")
            .expect("palace");
        state.selected = pos + 1;
        state.clamp_to_visible();
        assert_eq!(state.selected_id(), Some("trusty-memory"));
    }

    #[test]
    fn test_render_smoke() {
        // A full render in several states must not panic — exercise both the
        // "All" selection (aggregated panels) and a single-palace selection.
        let mut state = sample_state();
        state.log.push("SSE: dream_completed");
        state
            .log
            .push_scoped("default", "recall \"auth flow\" → 3 results");
        state.input = "auth flow".into();
        state.focus = MemoryFocus::Input;
        for (w, h) in [(120u16, 30u16), (80, 24)] {
            let backend = TestBackend::new(w, h);
            let mut terminal = Terminal::new(backend).expect("test terminal");
            terminal
                .draw(|f| render(f, &mut state))
                .expect("render (All) must not panic");
        }
        // Single-palace selection — the right panels scope to that palace.
        state.selected = 1;
        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).expect("test terminal");
        terminal
            .draw(|f| render(f, &mut state))
            .expect("render (single palace) must not panic");

        // A list far longer than the panel must render (and scroll) cleanly.
        state.palaces = (0..60)
            .map(|n| PalaceRow {
                id: format!("p-{n}"),
                name: format!("palace-{n}"),
                vector_count: 100,
                ..Default::default()
            })
            .collect();
        state.selected = state.last_row();
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).expect("test terminal");
        terminal
            .draw(|f| render(f, &mut state))
            .expect("overflowing list render must not panic");
        assert!(state.scroll_offset > 0, "long list scrolled to the cursor");

        state.show_help = true;
        state.daemon_status = DaemonStatus::Connecting;
        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).expect("test terminal");
        terminal
            .draw(|f| render(f, &mut state))
            .expect("help render must not panic");
    }
}