mind-cli 0.6.1

A manager for agent tooling (skills, agents, rules, tools) that melds arbitrary git repos and links items into your agent directories.
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
//! Tree data model for the TUI browse view.
//!
//! Builds the Installed/Available hierarchy from a data snapshot, flattens it
//! to a visible list given expansion state and filters. Search uses
//! `catalog::matches_query` consistent with CLI-85 (TUI-14).
//!
//! Pure: no I/O, no ratatui, no lock.

use std::collections::HashSet;
use std::path::PathBuf;

use crate::catalog;
use crate::error::ItemKind;
use crate::tui::app::FlatNode;
use crate::tui::data::Snapshot;

/// A node in the logical tree (before flattening to display rows).
#[derive(Debug, Clone)]
#[allow(dead_code)] // fields used by render/action; present but not all read yet
pub enum TreeNode {
    /// The "Installed" group header.
    InstalledGroup,
    /// The "Available" group header.
    AvailableGroup,
    /// A source node under Installed.
    Source(SourceInfo),
    /// A kind-bucket node under a source (e.g. "skills").
    KindBucket { source: String, kind: ItemKind },
    /// A single installed item.
    InstalledItem(InstalledInfo),
    /// A single available (not installed) item.
    AvailableItem(AvailableInfo),
    /// A not-yet-melded source suggested by the registry (TUI-31).
    /// Expanding this node triggers a preview (TUI-30).
    SuggestedSource(SuggestedSourceInfo),
    /// The synthetic "unmanaged" group header (UNM-6): lobe items mind did not
    /// install, distinct from any source.
    UnmanagedGroup,
    /// A single unmanaged lobe item under the unmanaged group (UNM-6).
    UnmanagedItem(UnmanagedInfo),
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct SourceInfo {
    pub name: String,
    pub installed: bool,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct InstalledInfo {
    pub key: String,
    pub name: String,
    pub source: String,
    pub kind: ItemKind,
    pub commit: String,
    pub description: Option<String>,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct AvailableInfo {
    pub key: String,
    pub name: String,
    pub source: String,
    pub kind: ItemKind,
    pub description: Option<String>,
    pub path: PathBuf,
}

/// Info about a single unmanaged lobe item (UNM-6). `key` is the `kind:name`
/// form so the forget action resolves it via the same ref path as a managed
/// item (UNM-4).
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct UnmanagedInfo {
    pub key: String,
    pub name: String,
    pub kind: ItemKind,
    pub paths: Vec<PathBuf>,
}

/// Info about a not-yet-melded suggested source (TUI-31).
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct SuggestedSourceInfo {
    /// The repo spec (for meld/preview).
    pub spec: String,
    /// Display name.
    pub name: String,
    /// URL.
    pub url: String,
}

/// A node in the tree with its children.
#[derive(Debug, Clone)]
pub struct Node {
    pub id: String,
    pub label: String,
    pub node: TreeNode,
    pub children: Vec<Node>,
}

/// Build the full tree from a snapshot, applying kind/source filters and the
/// installed_collapsed / available_collapsed state.
///
/// The search filter is applied at the item level: a source or kind bucket is
/// included if at least one of its items matches. This mirrors how `probe` works:
/// the group headers are always visible, but their contents are filtered.
// spec: TUI-10 TUI-11 TUI-12 TUI-13 TUI-14
pub fn build_tree(
    snap: &Snapshot,
    search: &str,
    kind_filter: Option<ItemKind>,
    source_filter: Option<&str>,
    installed_collapsed: bool,
    available_collapsed: bool,
) -> Vec<Node> {
    let mut roots = Vec::new();

    // --- Installed group ---
    // spec: TUI-10 TUI-12
    let installed_node = build_installed_group(snap, search, kind_filter, source_filter);
    let installed_count = count_items(&installed_node.children);
    let installed_label = if installed_collapsed {
        "Installed (collapsed)".to_string()
    } else {
        format!("Installed ({installed_count})")
    };
    roots.push(Node {
        id: "group:installed".to_string(),
        label: installed_label,
        children: if installed_collapsed {
            vec![]
        } else {
            installed_node.children
        },
        node: TreeNode::InstalledGroup,
    });

    // --- Available group ---
    // spec: TUI-10 TUI-13
    let available_node = build_available_group(snap, search, kind_filter, source_filter);
    let available_count = count_items(&available_node.children);
    let available_label = if available_collapsed {
        "Available (collapsed)".to_string()
    } else {
        format!("Available ({available_count})")
    };
    roots.push(Node {
        id: "group:available".to_string(),
        label: available_label,
        children: if available_collapsed {
            vec![]
        } else {
            available_node.children
        },
        node: TreeNode::AvailableGroup,
    });

    // --- Unmanaged group (UNM-6) ---
    // Built only when there are unmanaged items to show after filtering, so the
    // group is absent (not an empty header) on the common all-managed home. It
    // is auto-expanded and collapses via the `collapsed` set like a Source node.
    // spec: UNM-6
    let unmanaged_children = build_unmanaged_children(snap, search, kind_filter, source_filter);
    if !unmanaged_children.is_empty() {
        roots.push(Node {
            id: "group:unmanaged".to_string(),
            label: format!("Unmanaged ({})", unmanaged_children.len()),
            node: TreeNode::UnmanagedGroup,
            children: unmanaged_children,
        });
    }

    roots
}

fn count_items(children: &[Node]) -> usize {
    let mut n = 0;
    for c in children {
        match &c.node {
            TreeNode::InstalledItem(_)
            | TreeNode::AvailableItem(_)
            | TreeNode::UnmanagedItem(_) => n += 1,
            _ => n += count_items(&c.children),
        }
    }
    n
}

/// Build the Installed subtree.
// spec: TUI-12
fn build_installed_group(
    snap: &Snapshot,
    search: &str,
    kind_filter: Option<ItemKind>,
    source_filter: Option<&str>,
) -> Node {
    // Group installed items by source -> kind.
    let mut by_source: std::collections::BTreeMap<
        String,
        Vec<&crate::tui::data::SnapshotInstalled>,
    > = std::collections::BTreeMap::new();
    for item in &snap.installed {
        if kind_filter.is_some_and(|kf| item.kind != kf) {
            continue;
        }
        if source_filter.is_some_and(|sf| !crate::resolve::source_matches(&item.source, sf)) {
            continue;
        }
        if !item_matches_search_installed(item, search) {
            continue;
        }
        by_source.entry(item.source.clone()).or_default().push(item);
    }

    let mut source_nodes = Vec::new();
    for (src_name, items) in &by_source {
        let mut kind_map: std::collections::BTreeMap<
            ItemKind,
            Vec<&&crate::tui::data::SnapshotInstalled>,
        > = std::collections::BTreeMap::new();
        for item in items {
            kind_map.entry(item.kind).or_default().push(item);
        }

        let mut kind_nodes = Vec::new();
        for (kind, kind_items) in &kind_map {
            let item_nodes: Vec<Node> = kind_items
                .iter()
                .map(|it| Node {
                    id: format!("installed:{}:{}", src_name, it.key),
                    label: format!(
                        "{} [{}]{}",
                        it.name,
                        short_commit(&it.commit),
                        it.description
                            .as_deref()
                            .map(|d| format!(" - {}", truncate(d, 50)))
                            .unwrap_or_default()
                    ),
                    node: TreeNode::InstalledItem(InstalledInfo {
                        key: it.key.clone(),
                        name: it.name.clone(),
                        source: it.source.clone(),
                        kind: it.kind,
                        commit: it.commit.clone(),
                        description: it.description.clone(),
                    }),
                    children: vec![],
                })
                .collect();
            kind_nodes.push(Node {
                id: format!("installed-kind:{}:{}", src_name, kind.as_str()),
                label: format!("{} ({})", kind.as_str(), item_nodes.len()),
                node: TreeNode::KindBucket {
                    source: src_name.clone(),
                    kind: *kind,
                },
                children: item_nodes,
            });
        }

        source_nodes.push(Node {
            id: format!("installed-source:{}", src_name),
            label: src_name.clone(),
            node: TreeNode::Source(SourceInfo {
                name: src_name.clone(),
                installed: true,
            }),
            children: kind_nodes,
        });
    }

    Node {
        id: "group:installed".to_string(),
        label: "Installed".to_string(),
        node: TreeNode::InstalledGroup,
        children: source_nodes,
    }
}

/// Build the Available subtree, de-duplicating items that are already installed.
/// Also appends TUI-31 suggested sources as collapsed leaf nodes.
// spec: TUI-13 TUI-14 TUI-31
fn build_available_group(
    snap: &Snapshot,
    search: &str,
    kind_filter: Option<ItemKind>,
    source_filter: Option<&str>,
) -> Node {
    // Installed item keys (for de-dup).
    let installed_keys: HashSet<String> = snap.installed.iter().map(|i| i.key.clone()).collect();

    let mut by_source: std::collections::BTreeMap<
        String,
        Vec<&crate::tui::data::SnapshotAvailable>,
    > = std::collections::BTreeMap::new();

    for item in &snap.available {
        // De-duplicate: skip items already installed.
        // spec: TUI-13
        if installed_keys.contains(&item.key) {
            continue;
        }
        if kind_filter.is_some_and(|kf| item.kind != kf) {
            continue;
        }
        if source_filter.is_some_and(|sf| !crate::resolve::source_matches(&item.source, sf)) {
            continue;
        }
        if !item_matches_search_available(item, search) {
            continue;
        }
        by_source.entry(item.source.clone()).or_default().push(item);
    }

    let mut source_nodes = Vec::new();
    for (src_name, items) in &by_source {
        let mut kind_map: std::collections::BTreeMap<
            ItemKind,
            Vec<&&crate::tui::data::SnapshotAvailable>,
        > = std::collections::BTreeMap::new();
        for item in items {
            kind_map.entry(item.kind).or_default().push(item);
        }

        let mut kind_nodes = Vec::new();
        for (kind, kind_items) in &kind_map {
            let item_nodes: Vec<Node> = kind_items
                .iter()
                .map(|it| Node {
                    id: format!("available:{}:{}", src_name, it.key),
                    label: format!(
                        "{}{}",
                        it.name,
                        it.description
                            .as_deref()
                            .map(|d| format!(" - {}", truncate(d, 50)))
                            .unwrap_or_default()
                    ),
                    node: TreeNode::AvailableItem(AvailableInfo {
                        key: it.key.clone(),
                        name: it.name.clone(),
                        source: it.source.clone(),
                        kind: it.kind,
                        description: it.description.clone(),
                        path: it.path.clone(),
                    }),
                    children: vec![],
                })
                .collect();
            kind_nodes.push(Node {
                id: format!("available-kind:{}:{}", src_name, kind.as_str()),
                label: format!("{} ({})", kind.as_str(), item_nodes.len()),
                node: TreeNode::KindBucket {
                    source: src_name.clone(),
                    kind: *kind,
                },
                children: item_nodes,
            });
        }

        source_nodes.push(Node {
            id: format!("available-source:{}", src_name),
            label: src_name.clone(),
            node: TreeNode::Source(SourceInfo {
                name: src_name.clone(),
                installed: false,
            }),
            children: kind_nodes,
        });
    }

    // Append suggested not-yet-melded sources (TUI-31). Search filter applies
    // to the suggestion name. Source/kind filters are not applied since
    // suggestions have no kind yet (they need a preview to reveal items).
    // spec: TUI-31
    for sug in &snap.suggestions {
        if !search.is_empty() && !sug.name.to_lowercase().contains(&search.to_lowercase()) {
            continue;
        }
        source_nodes.push(Node {
            id: format!("suggested:{}", sug.url),
            label: format!("{} [suggested]", sug.name),
            node: TreeNode::SuggestedSource(SuggestedSourceInfo {
                spec: sug.spec.clone(),
                name: sug.name.clone(),
                url: sug.url.clone(),
            }),
            // No children yet: expanding triggers a preview (handled in event loop).
            children: vec![],
        });
    }

    Node {
        id: "group:available".to_string(),
        label: "Available".to_string(),
        node: TreeNode::AvailableGroup,
        children: source_nodes,
    }
}

/// Build the leaf nodes under the unmanaged group (UNM-6): one row per
/// unmanaged lobe item, sorted by `(kind, name)` as the snapshot already is.
/// `--kind` filters; a `--source` filter excludes every unmanaged item (they
/// have no source, per UNM-3); search matches the item name (CLI-85: unmanaged
/// items carry no description, so name is all there is to match).
// spec: UNM-6
fn build_unmanaged_children(
    snap: &Snapshot,
    search: &str,
    kind_filter: Option<ItemKind>,
    source_filter: Option<&str>,
) -> Vec<Node> {
    // A source filter excludes unmanaged items entirely (UNM-3).
    if source_filter.is_some() {
        return Vec::new();
    }
    let needle = search.to_lowercase();
    snap.unmanaged
        .iter()
        .filter(|it| kind_filter.is_none_or(|kf| it.kind == kf))
        .filter(|it| needle.is_empty() || it.name.to_lowercase().contains(&needle))
        .map(|it| Node {
            id: format!("unmanaged:{}", it.key),
            label: format!("{} [{}] (unmanaged)", it.name, it.kind.as_str()),
            node: TreeNode::UnmanagedItem(UnmanagedInfo {
                key: it.key.clone(),
                name: it.name.clone(),
                kind: it.kind,
                paths: it.paths.clone(),
            }),
            children: vec![],
        })
        .collect()
}

/// True if an installed item matches the search query.
/// Delegates to `catalog::matches_query` (CLI-85 / TUI-14) so both installed
/// and available search share one source of truth.
// spec: TUI-14 CLI-85
fn item_matches_search_installed(item: &crate::tui::data::SnapshotInstalled, search: &str) -> bool {
    if search.is_empty() {
        return true;
    }
    // Build a temporary CatalogItem to reuse catalog::matches_query exactly,
    // mirroring item_matches_search_available. The installed name is already the
    // effective (possibly prefixed) name, so prefix is None to avoid
    // double-prefixing via effective_name().
    let fake = catalog::CatalogItem {
        kind: item.kind,
        name: item.name.clone(),
        source: item.source.clone(),
        prefix: None,
        path: std::path::PathBuf::new(),
        description: item.description.clone(),
        link_rel: None,
        bin: None,
        build: None,
        install: None,
        uninstall: None,
        hooks: Vec::new(),
    };
    catalog::matches_query(&fake, search)
}

/// True if an available item matches the search query.
/// Mirrors `catalog::matches_query` (CLI-85 / TUI-14).
// spec: TUI-14
fn item_matches_search_available(item: &crate::tui::data::SnapshotAvailable, search: &str) -> bool {
    if search.is_empty() {
        return true;
    }
    // Build a temporary CatalogItem to reuse catalog::matches_query exactly.
    // This ensures TUI-14's "consistent with CLI-85" requirement by literally
    // calling the same function (avoiding duplicated logic).
    let fake = catalog::CatalogItem {
        kind: item.kind,
        name: item.name.clone(),
        source: item.source.clone(),
        prefix: None,
        path: item.path.clone(),
        description: item.description.clone(),
        link_rel: None,
        bin: None,
        build: None,
        install: None,
        uninstall: None,
        hooks: Vec::new(),
    };
    catalog::matches_query(&fake, search)
}

/// Returns true for structural nodes that are auto-expanded by default
/// (InstalledGroup, AvailableGroup, Source, KindBucket). These nodes use the
/// `collapsed` set to opt-out of expansion, rather than requiring an explicit
/// `expanded` entry to opt-in.
// spec: TUI-11
pub fn is_auto_expanded(node: &TreeNode) -> bool {
    matches!(
        node,
        TreeNode::InstalledGroup
            | TreeNode::AvailableGroup
            | TreeNode::UnmanagedGroup
            | TreeNode::Source(_)
            | TreeNode::KindBucket { .. }
    )
}

/// Flatten the tree into a displayable list, respecting expansion state.
/// A group header is always shown. A node's children are shown only if the
/// node is expanded. Auto-expanded nodes (Source, KindBucket, group headers)
/// use the `collapsed` set to track user-initiated collapses; non-auto nodes
/// (InstalledItem, AvailableItem, SuggestedSource children) require explicit
/// membership in `expanded` to show children.
// spec: TUI-10 TUI-11
pub fn flatten_tree(
    nodes: &[Node],
    expanded: &HashSet<String>,
    collapsed: &HashSet<String>,
) -> Vec<FlatNode> {
    let mut out = Vec::new();
    for node in nodes {
        flatten_node(node, 0, expanded, collapsed, &mut out);
    }
    out
}

fn flatten_node(
    node: &Node,
    depth: usize,
    expanded: &HashSet<String>,
    collapsed: &HashSet<String>,
    out: &mut Vec<FlatNode>,
) {
    // Auto-expanded nodes (group headers, source nodes, kind-buckets) are
    // visible by default and collapsed only when their ID is in `collapsed`.
    // Item-detail nodes (InstalledItem / AvailableItem) require explicit
    // membership in `expanded` to reveal children.
    let is_exp = if is_auto_expanded(&node.node) {
        !collapsed.contains(&node.id)
    } else {
        expanded.contains(&node.id)
    };
    let expandable = !node.children.is_empty();
    out.push(FlatNode {
        id: node.id.clone(),
        label: node.label.clone(),
        depth,
        expandable,
        expanded: is_exp,
        node: node.node.clone(),
    });
    if is_exp {
        for child in &node.children {
            flatten_node(child, depth + 1, expanded, collapsed, out);
        }
    }
}

fn short_commit(s: &str) -> String {
    if s.is_empty() {
        "-".to_string()
    } else {
        s.chars().take(8).collect()
    }
}

fn truncate(s: &str, max: usize) -> &str {
    if s.chars().count() <= max {
        s
    } else {
        // Find the byte offset of the max-th char
        let idx = s.char_indices().nth(max).map(|(i, _)| i).unwrap_or(s.len());
        &s[..idx]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ItemKind;
    use crate::tui::data::{Snapshot, SnapshotAvailable, SnapshotInstalled};
    use std::collections::HashSet;

    fn make_installed(key: &str, name: &str, source: &str, kind: ItemKind) -> SnapshotInstalled {
        SnapshotInstalled {
            key: key.to_string(),
            name: name.to_string(),
            source: source.to_string(),
            kind,
            commit: "abc12345".to_string(),
            description: Some(format!("{name} description")),
        }
    }

    fn make_available(key: &str, name: &str, source: &str, kind: ItemKind) -> SnapshotAvailable {
        SnapshotAvailable {
            key: key.to_string(),
            name: name.to_string(),
            source: source.to_string(),
            kind,
            description: Some(format!("{name} description")),
            path: std::path::PathBuf::from(format!("/fake/{name}")),
        }
    }

    fn snap_with(installed: Vec<SnapshotInstalled>, available: Vec<SnapshotAvailable>) -> Snapshot {
        Snapshot {
            generation: 1,
            installed,
            available,
            unmanaged: vec![],
            source_names: vec!["src/a".to_string()],
            suggestions: vec![],
            lobes: vec![],
        }
    }

    fn make_unmanaged(name: &str, kind: ItemKind) -> crate::tui::data::SnapshotUnmanaged {
        crate::tui::data::SnapshotUnmanaged {
            key: format!("{}:{}", kind.as_str(), name),
            name: name.to_string(),
            kind,
            paths: vec![std::path::PathBuf::from(format!("/lobe/{name}"))],
        }
    }

    #[test]
    fn tree_has_installed_and_available_groups() {
        // spec: TUI-10
        let snap = snap_with(
            vec![make_installed(
                "skill:review",
                "review",
                "src/a",
                ItemKind::Skill,
            )],
            vec![make_available("agent:dev", "dev", "src/a", ItemKind::Agent)],
        );
        let nodes = build_tree(&snap, "", None, None, false, false);
        assert_eq!(nodes.len(), 2);
        assert!(matches!(nodes[0].node, TreeNode::InstalledGroup));
        assert!(matches!(nodes[1].node, TreeNode::AvailableGroup));
    }

    #[test]
    fn installed_group_contains_installed_items() {
        // spec: TUI-12
        let snap = snap_with(
            vec![make_installed(
                "skill:review",
                "review",
                "src/a",
                ItemKind::Skill,
            )],
            vec![],
        );
        let nodes = build_tree(&snap, "", None, None, false, false);
        // Flatten and look for InstalledItem
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        // Group headers are always expanded, so items appear even without expansion
        let has_review = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledItem(i) if i.name == "review"));
        assert!(
            has_review,
            "installed item should appear in flat tree: {:?}",
            flat.iter().map(|n| &n.label).collect::<Vec<_>>()
        );
    }

    #[test]
    fn available_group_excludes_installed_items() {
        // spec: TUI-13 (dedup: installed items not shown in Available)
        let installed = make_installed("skill:review", "review", "src/a", ItemKind::Skill);
        // Same key in available
        let also_avail = make_available("skill:review", "review", "src/a", ItemKind::Skill);
        let snap = snap_with(vec![installed], vec![also_avail]);
        let nodes = build_tree(&snap, "", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        // Should not appear under Available
        let avail_review = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == "review"));
        assert!(
            !avail_review,
            "installed item must not appear in Available tree"
        );
    }

    #[test]
    fn search_filters_available_items() {
        // spec: TUI-14
        let snap = snap_with(
            vec![],
            vec![
                make_available("agent:dev", "dev", "src/a", ItemKind::Agent),
                make_available("agent:plan", "plan", "src/a", ItemKind::Agent),
            ],
        );
        // Search for "dev" only
        let nodes = build_tree(&snap, "dev", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let has_dev = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == "dev"));
        let has_plan = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == "plan"));
        assert!(has_dev, "dev should match search 'dev'");
        assert!(!has_plan, "plan should not match search 'dev'");
    }

    #[test]
    fn search_is_case_insensitive() {
        // spec: TUI-14
        let snap = snap_with(
            vec![],
            vec![make_available(
                "skill:Review",
                "Review",
                "src/a",
                ItemKind::Skill,
            )],
        );
        let nodes = build_tree(&snap, "review", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let found = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == "Review"));
        assert!(found, "search should be case-insensitive");
    }

    #[test]
    fn search_matches_description() {
        // spec: TUI-14
        let mut item = make_available("skill:x", "x", "src/a", ItemKind::Skill);
        item.description = Some("automated code formatter".to_string());
        let snap = snap_with(vec![], vec![item]);
        let nodes = build_tree(&snap, "formatter", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let found = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == "x"));
        assert!(found, "search should match description text");
    }

    #[test]
    fn kind_filter_narrows_available() {
        // spec: TUI-14
        let snap = snap_with(
            vec![],
            vec![
                make_available("skill:s", "s", "src/a", ItemKind::Skill),
                make_available("agent:a", "a", "src/a", ItemKind::Agent),
            ],
        );
        let nodes = build_tree(&snap, "", Some(ItemKind::Skill), None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let has_skill = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == "s"));
        let has_agent = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == "a"));
        assert!(has_skill, "skill should survive kind=Skill filter");
        assert!(!has_agent, "agent should be filtered out by kind=Skill");
    }

    #[test]
    fn flatten_shows_items_by_default() {
        // spec: TUI-11
        // Source nodes and kind-buckets are auto-expanded so items are visible
        // immediately without any explicit expansion. This gives the user a
        // usable default view.
        let snap = snap_with(
            vec![make_installed(
                "skill:review",
                "review",
                "src/a",
                ItemKind::Skill,
            )],
            vec![],
        );
        let nodes = build_tree(&snap, "", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let group_visible = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledGroup));
        assert!(group_visible, "group header should always be visible");
        // With auto-expansion, items should be visible too.
        let item_visible = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledItem(_)));
        assert!(
            item_visible,
            "items should be visible by default (auto-expand): {:?}",
            flat.iter().map(|n| &n.label).collect::<Vec<_>>()
        );
    }

    #[test]
    fn search_and_kind_filter_compose() {
        // spec: TUI-13 TUI-14 - a search query and a kind filter applied at the
        // SAME time must both constrain the result (composition, not either/or).
        let snap = snap_with(
            vec![],
            vec![
                // matches search "re" AND kind=Skill -> survives
                make_available("skill:review", "review", "src/a", ItemKind::Skill),
                // matches kind=Skill but NOT search "re" -> filtered by search
                make_available("skill:build", "build", "src/a", ItemKind::Skill),
                // matches search "re" but NOT kind=Skill -> filtered by kind
                make_available("agent:render", "render", "src/a", ItemKind::Agent),
            ],
        );
        let nodes = build_tree(&snap, "re", Some(ItemKind::Skill), None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let names: Vec<&str> = flat
            .iter()
            .filter_map(|n| match &n.node {
                TreeNode::AvailableItem(i) => Some(i.name.as_str()),
                _ => None,
            })
            .collect();
        assert!(
            names.contains(&"review"),
            "review matches both axes: {names:?}"
        );
        assert!(
            !names.contains(&"build"),
            "build fails the search axis: {names:?}"
        );
        assert!(
            !names.contains(&"render"),
            "render fails the kind axis: {names:?}"
        );
    }

    #[test]
    fn search_and_source_filter_compose() {
        // spec: TUI-13 TUI-14 - search composes with the source filter too.
        let snap = snap_with(
            vec![],
            vec![
                make_available("skill:review", "review", "a/agents", ItemKind::Skill),
                // same name, different source -> excluded by source filter
                make_available("skill:review", "review", "b/agents", ItemKind::Skill),
                // right source, wrong search -> excluded by search
                make_available("skill:build", "build", "a/agents", ItemKind::Skill),
            ],
        );
        let nodes = build_tree(&snap, "review", None, Some("a/agents"), false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        // Only the a/agents review survives both filters.
        let from_a = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::Source(s) if s.name == "a/agents"));
        let from_b = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::Source(s) if s.name == "b/agents"));
        assert!(
            from_a,
            "a/agents source should remain after composed filters"
        );
        assert!(
            !from_b,
            "b/agents source must be excluded by the source filter"
        );
        let has_build = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == "build"));
        assert!(!has_build, "build must be excluded by the search filter");
    }

    #[test]
    fn clearing_search_restores_full_tree() {
        // spec: TUI-14 - "Clearing the search restores the full tree." Build with a
        // narrowing search, then with an empty search, and confirm the empty-search
        // tree is a strict superset.
        let snap = snap_with(
            vec![],
            vec![
                make_available("skill:review", "review", "src/a", ItemKind::Skill),
                make_available("agent:dev", "dev", "src/a", ItemKind::Agent),
                make_available("rule:style", "style", "src/a", ItemKind::Rule),
            ],
        );
        let filtered = flatten_tree(
            &build_tree(&snap, "review", None, None, false, false),
            &HashSet::new(),
            &HashSet::new(),
        );
        let restored = flatten_tree(
            &build_tree(&snap, "", None, None, false, false),
            &HashSet::new(),
            &HashSet::new(),
        );

        let filtered_items = filtered
            .iter()
            .filter(|n| matches!(&n.node, TreeNode::AvailableItem(_)))
            .count();
        let restored_items = restored
            .iter()
            .filter(|n| matches!(&n.node, TreeNode::AvailableItem(_)))
            .count();
        assert_eq!(
            filtered_items, 1,
            "search 'review' should match exactly one item"
        );
        assert_eq!(
            restored_items, 3,
            "clearing the search restores all three items"
        );
        // The previously hidden items are back.
        for want in ["dev", "style", "review"] {
            assert!(
                restored
                    .iter()
                    .any(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == want)),
                "{want} should reappear after clearing search"
            );
        }
    }

    #[test]
    fn search_surfaces_description_only_match_with_filter_active() {
        // spec: TUI-13 TUI-14 - a query that matches the DESCRIPTION but not the
        // NAME still surfaces the item (consistent with CLI-85 via
        // catalog::matches_query), even while a kind filter is also active.
        let mut item = make_available("skill:fmt", "fmt", "src/a", ItemKind::Skill);
        item.description = Some("automated code formatter".to_string());
        let other = make_available("agent:fmt", "fmt", "src/a", ItemKind::Agent);
        let snap = snap_with(vec![], vec![item, other]);
        // "formatter" appears only in the skill's description; kind=Skill is active.
        let nodes = build_tree(
            &snap,
            "formatter",
            Some(ItemKind::Skill),
            None,
            false,
            false,
        );
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let has_skill = flat.iter().any(|n| {
            matches!(&n.node, TreeNode::AvailableItem(i)
            if i.name == "fmt" && i.kind == ItemKind::Skill)
        });
        let has_agent = flat.iter().any(|n| {
            matches!(&n.node, TreeNode::AvailableItem(i)
            if i.kind == ItemKind::Agent)
        });
        assert!(
            has_skill,
            "description-only match must surface the skill: {:?}",
            flat.iter().map(|n| &n.label).collect::<Vec<_>>()
        );
        assert!(
            !has_agent,
            "the agent (wrong kind, no desc match) must be filtered out"
        );
    }

    #[test]
    fn two_uninstalled_sources_same_name_both_appear() {
        // spec: TUI-13 - de-dup removes only items that are INSTALLED. Two distinct
        // (uninstalled) sources that each ship a same-bare-name item must BOTH appear
        // in Available, each under its own source node. (Contrast with
        // available_dedup_across_two_sources, where the item IS installed.)
        let from_a = make_available("skill:review", "review", "a/agents", ItemKind::Skill);
        let from_b = make_available("skill:review", "review", "b/agents", ItemKind::Skill);
        let snap = snap_with(vec![], vec![from_a, from_b]); // nothing installed
        let nodes = build_tree(&snap, "", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let review_count = flat
            .iter()
            .filter(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == "review"))
            .count();
        assert_eq!(
            review_count,
            2,
            "both uninstalled same-name items should appear (one per source): {:?}",
            flat.iter().map(|n| &n.label).collect::<Vec<_>>()
        );
        let source_a = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::Source(s) if s.name == "a/agents"));
        let source_b = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::Source(s) if s.name == "b/agents"));
        assert!(source_a && source_b, "both source nodes should be present");
    }

    #[test]
    fn suggested_source_with_melded_url_excluded_at_data_layer() {
        // spec: TUI-31 - a SuggestedSource is only built from snap.suggestions, which
        // the data layer (preview::suggested_registry) has already filtered to exclude
        // already-melded URLs. Here we verify the tree faithfully renders whatever
        // suggestions it is given (the exclusion itself is tested in preview.rs).
        // An empty suggestions list must yield no SuggestedSource nodes.
        let snap = snap_with(vec![], vec![]); // no suggestions
        let nodes = build_tree(&snap, "", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let any_suggested = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::SuggestedSource(_)));
        assert!(!any_suggested, "no suggestions -> no SuggestedSource nodes");
    }

    #[test]
    fn installed_search_matches_description_not_just_name() {
        // spec: CLI-85
        // An installed item whose NAME does not contain the query but whose
        // DESCRIPTION does must still be matched. This proves item_matches_search_installed
        // delegates to catalog::matches_query (same logic as available search),
        // rather than reimplementing an inline name-only check.
        let mut item = make_installed("skill:fmt", "fmt", "src/a", ItemKind::Skill);
        item.description = Some("automated code formatter".to_string());
        // A second installed item with neither name nor description matching.
        let other = make_installed("skill:lint", "lint", "src/a", ItemKind::Skill);

        let snap = snap_with(vec![item, other], vec![]);
        // "formatter" appears only in the first item's description.
        let nodes = build_tree(&snap, "formatter", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());

        let has_fmt = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledItem(i) if i.name == "fmt"));
        let has_lint = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledItem(i) if i.name == "lint"));

        assert!(
            has_fmt,
            "installed item should be matched by description: {:?}",
            flat.iter().map(|n| &n.label).collect::<Vec<_>>()
        );
        assert!(
            !has_lint,
            "installed item with no name/desc match must be filtered out"
        );
    }

    #[test]
    fn available_dedup_across_two_sources() {
        // spec: TUI-13
        // An item key appearing in both installed and available (from a different source)
        // should still be deduped (the installed KEY is what matters).
        let installed = make_installed("skill:review", "review", "src/a", ItemKind::Skill);
        let also_from_b = make_available("skill:review", "review", "src/b", ItemKind::Skill);
        let snap = snap_with(vec![installed], vec![also_from_b]);
        let nodes = build_tree(&snap, "", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        // Same key is deduped regardless of source name
        let avail_count = flat
            .iter()
            .filter(|n| matches!(&n.node, TreeNode::AvailableItem(i) if i.name == "review"))
            .count();
        assert_eq!(
            avail_count, 0,
            "same key in available should be deduped vs installed"
        );
    }

    // --- TUI-11: collapsed set governs Source/KindBucket visibility ---

    #[test]
    fn source_id_in_collapsed_hides_its_children() {
        // spec: TUI-11 - when a Source node's id is in the `collapsed` set, its
        // children (KindBucket and item nodes) must be absent from the flat output.
        let snap = snap_with(
            vec![make_installed(
                "skill:review",
                "review",
                "src/a",
                ItemKind::Skill,
            )],
            vec![],
        );
        let nodes = build_tree(&snap, "", None, None, false, false);

        // Find the Source node id.
        let flat_default = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let source_id = flat_default
            .iter()
            .find(|n| matches!(&n.node, TreeNode::Source(_)))
            .map(|n| n.id.clone())
            .expect("a Source node must be present");

        // Children are present when not collapsed.
        let has_item = flat_default
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledItem(_)));
        assert!(
            has_item,
            "item should be visible when source is not collapsed"
        );

        // Put the source id in collapsed: children must disappear.
        let mut collapsed = HashSet::new();
        collapsed.insert(source_id.clone());
        let flat_collapsed = flatten_tree(&nodes, &HashSet::new(), &collapsed);
        let has_item_after = flat_collapsed
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledItem(_)));
        let has_bucket_after = flat_collapsed
            .iter()
            .any(|n| matches!(&n.node, TreeNode::KindBucket { .. }));
        assert!(
            !has_item_after,
            "item must be absent when source is in the collapsed set"
        );
        assert!(
            !has_bucket_after,
            "KindBucket must also be absent when source is in the collapsed set"
        );

        // Source node itself must still be visible.
        let source_visible = flat_collapsed.iter().any(|n| n.id == source_id);
        assert!(source_visible, "the Source node itself must remain visible");
    }

    #[test]
    fn kind_bucket_id_in_collapsed_hides_its_items() {
        // spec: TUI-11 - when a KindBucket node's id is in the `collapsed` set,
        // its item children must be absent while the bucket node itself stays visible.
        let snap = snap_with(
            vec![make_installed(
                "skill:review",
                "review",
                "src/a",
                ItemKind::Skill,
            )],
            vec![],
        );
        let nodes = build_tree(&snap, "", None, None, false, false);

        let flat_default = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let bucket_id = flat_default
            .iter()
            .find(|n| matches!(&n.node, TreeNode::KindBucket { .. }))
            .map(|n| n.id.clone())
            .expect("a KindBucket node must be present");

        // Items visible without collapsed.
        let has_item = flat_default
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledItem(_)));
        assert!(
            has_item,
            "item should be visible when bucket is not collapsed"
        );

        // Collapse the bucket: items disappear, bucket stays.
        let mut collapsed = HashSet::new();
        collapsed.insert(bucket_id.clone());
        let flat_collapsed = flatten_tree(&nodes, &HashSet::new(), &collapsed);
        let has_item_after = flat_collapsed
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledItem(_)));
        assert!(
            !has_item_after,
            "item must be absent when KindBucket is in the collapsed set"
        );
        let bucket_visible = flat_collapsed.iter().any(|n| n.id == bucket_id);
        assert!(
            bucket_visible,
            "the KindBucket node itself must stay visible"
        );
    }

    #[test]
    fn removing_source_from_collapsed_restores_children() {
        // spec: TUI-11 - removing a Source id from the collapsed set (expand
        // action) must restore its children in the next flatten call.
        let snap = snap_with(
            vec![make_installed(
                "skill:review",
                "review",
                "src/a",
                ItemKind::Skill,
            )],
            vec![],
        );
        let nodes = build_tree(&snap, "", None, None, false, false);
        let flat_default = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let source_id = flat_default
            .iter()
            .find(|n| matches!(&n.node, TreeNode::Source(_)))
            .map(|n| n.id.clone())
            .expect("a Source node must be present");

        // Collapse then expand.
        let mut collapsed = HashSet::new();
        collapsed.insert(source_id.clone());
        let flat_collapsed = flatten_tree(&nodes, &HashSet::new(), &collapsed);
        let hidden = flat_collapsed
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledItem(_)));
        assert!(!hidden, "items hidden after collapse");

        collapsed.remove(&source_id);
        let flat_restored = flatten_tree(&nodes, &HashSet::new(), &collapsed);
        let restored = flat_restored
            .iter()
            .any(|n| matches!(&n.node, TreeNode::InstalledItem(_)));
        assert!(
            restored,
            "items restored after removing source from collapsed set"
        );
    }

    #[test]
    fn normal_item_node_still_requires_expanded_membership() {
        // spec: TUI-11 - non-auto-expanded nodes (InstalledItem, AvailableItem)
        // use the `expanded` set, not `collapsed`. A node with children is only
        // shown expanded when its id is in `expanded`; the `collapsed` set has
        // no effect on it.
        //
        // Build a synthetic Node tree with a parent InstalledItem that has a
        // child InstalledItem (not possible from the default snapshot but valid
        // for exercising flatten_node's branching).
        let parent = Node {
            id: "item-parent".to_string(),
            label: "parent".to_string(),
            node: TreeNode::InstalledItem(InstalledInfo {
                key: "skill:parent".to_string(),
                name: "parent".to_string(),
                source: "src/a".to_string(),
                kind: ItemKind::Skill,
                commit: "abc".to_string(),
                description: None,
            }),
            children: vec![Node {
                id: "item-child".to_string(),
                label: "child".to_string(),
                node: TreeNode::InstalledItem(InstalledInfo {
                    key: "skill:child".to_string(),
                    name: "child".to_string(),
                    source: "src/a".to_string(),
                    kind: ItemKind::Skill,
                    commit: "abc".to_string(),
                    description: None,
                }),
                children: vec![],
            }],
        };

        let nodes = vec![parent];

        // Neither collapsed nor expanded: child must NOT be visible.
        let flat_empty = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let child_visible = flat_empty.iter().any(|n| n.id == "item-child");
        assert!(
            !child_visible,
            "InstalledItem child must be hidden without expanded membership"
        );

        // Collapsed contains the parent: still hidden (collapsed has no effect on non-auto nodes).
        let mut collapsed = HashSet::new();
        collapsed.insert("item-parent".to_string());
        let flat_only_collapsed = flatten_tree(&nodes, &HashSet::new(), &collapsed);
        let child_visible2 = flat_only_collapsed.iter().any(|n| n.id == "item-child");
        assert!(
            !child_visible2,
            "collapsed set must not expand non-auto nodes (they need `expanded` membership)"
        );

        // Expanded contains the parent: child appears.
        let mut expanded = HashSet::new();
        expanded.insert("item-parent".to_string());
        let flat_expanded = flatten_tree(&nodes, &expanded, &HashSet::new());
        let child_visible3 = flat_expanded.iter().any(|n| n.id == "item-child");
        assert!(
            child_visible3,
            "InstalledItem child must appear when parent is in `expanded`"
        );
    }

    // --- UNM-6: the unmanaged group node ---

    fn snap_with_unmanaged(unmanaged: Vec<crate::tui::data::SnapshotUnmanaged>) -> Snapshot {
        let mut snap = snap_with(vec![], vec![]);
        snap.unmanaged = unmanaged;
        snap
    }

    #[test]
    fn unmanaged_group_appears_with_items() {
        // spec: UNM-6 - unmanaged items appear under a dedicated group node,
        // distinct from any source, browsable (auto-expanded) like a source.
        let snap = snap_with_unmanaged(vec![
            make_unmanaged("hand-written", ItemKind::Skill),
            make_unmanaged("foreign", ItemKind::Agent),
        ]);
        let nodes = build_tree(&snap, "", None, None, false, false);
        // A third root group beyond Installed/Available.
        let group = nodes
            .iter()
            .find(|n| matches!(n.node, TreeNode::UnmanagedGroup))
            .expect("an unmanaged group node must be present");
        assert_eq!(group.label, "Unmanaged (2)");
        // Items are visible by default (the group auto-expands).
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let names: Vec<&str> = flat
            .iter()
            .filter_map(|n| match &n.node {
                TreeNode::UnmanagedItem(i) => Some(i.name.as_str()),
                _ => None,
            })
            .collect();
        assert!(names.contains(&"hand-written") && names.contains(&"foreign"));
    }

    #[test]
    fn no_unmanaged_group_when_none() {
        // spec: UNM-6 - with no unmanaged items the group is absent entirely (not
        // an empty header), keeping the common all-managed home uncluttered.
        let snap = snap_with_unmanaged(vec![]);
        let nodes = build_tree(&snap, "", None, None, false, false);
        assert!(
            !nodes
                .iter()
                .any(|n| matches!(n.node, TreeNode::UnmanagedGroup)),
            "no unmanaged items -> no unmanaged group"
        );
    }

    #[test]
    fn unmanaged_search_filters_by_name() {
        // spec: UNM-6 - the unmanaged group is searchable like a source's items.
        let snap = snap_with_unmanaged(vec![
            make_unmanaged("review", ItemKind::Skill),
            make_unmanaged("deploy", ItemKind::Skill),
        ]);
        let nodes = build_tree(&snap, "rev", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let names: Vec<&str> = flat
            .iter()
            .filter_map(|n| match &n.node {
                TreeNode::UnmanagedItem(i) => Some(i.name.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(names, vec!["review"], "search 'rev' keeps only review");
    }

    #[test]
    fn unmanaged_kind_filter_applies() {
        // spec: UNM-6 - `--kind` filters unmanaged items as it does managed ones.
        let snap = snap_with_unmanaged(vec![
            make_unmanaged("s", ItemKind::Skill),
            make_unmanaged("a", ItemKind::Agent),
        ]);
        let nodes = build_tree(&snap, "", Some(ItemKind::Skill), None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let kinds: Vec<ItemKind> = flat
            .iter()
            .filter_map(|n| match &n.node {
                TreeNode::UnmanagedItem(i) => Some(i.kind),
                _ => None,
            })
            .collect();
        assert_eq!(kinds, vec![ItemKind::Skill], "kind=Skill drops the agent");
    }

    #[test]
    fn unmanaged_source_filter_excludes_them() {
        // spec: UNM-6 - a `--source` filter excludes unmanaged items (they have no
        // source, per UNM-3), so the group is absent under any source filter.
        let snap = snap_with_unmanaged(vec![make_unmanaged("x", ItemKind::Skill)]);
        let nodes = build_tree(&snap, "", None, Some("some/source"), false, false);
        assert!(
            !nodes
                .iter()
                .any(|n| matches!(n.node, TreeNode::UnmanagedGroup)),
            "a source filter must exclude the unmanaged group"
        );
    }

    #[test]
    fn unmanaged_group_label_count_reflects_filtered_visible_items() {
        // spec: UNM-6 - the "Unmanaged (N)" label must report the number of items
        // VISIBLE after filtering, not the raw snapshot size. With three items and
        // a kind filter that keeps one, the label must read "Unmanaged (1)" and
        // exactly one item node must be present (count and contents agree).
        let snap = snap_with_unmanaged(vec![
            make_unmanaged("a", ItemKind::Skill),
            make_unmanaged("b", ItemKind::Agent),
            make_unmanaged("c", ItemKind::Agent),
        ]);
        let nodes = build_tree(&snap, "", Some(ItemKind::Skill), None, false, false);
        let group = nodes
            .iter()
            .find(|n| matches!(n.node, TreeNode::UnmanagedGroup))
            .expect("an unmanaged group node must be present");
        assert_eq!(
            group.label, "Unmanaged (1)",
            "label count must reflect items surviving the kind filter"
        );
        let item_count = group
            .children
            .iter()
            .filter(|n| matches!(&n.node, TreeNode::UnmanagedItem(_)))
            .count();
        assert_eq!(
            item_count, 1,
            "the visible item count must equal the label count"
        );
    }

    #[test]
    fn unmanaged_search_composes_with_kind_filter() {
        // spec: UNM-6 - a search query and a kind filter applied at the same time
        // must BOTH constrain the unmanaged items (composition, not either/or),
        // mirroring how the managed axes compose.
        let snap = snap_with_unmanaged(vec![
            // matches search "re" AND kind=Skill -> survives
            make_unmanaged("review", ItemKind::Skill),
            // matches kind=Skill but NOT search "re" -> dropped by search
            make_unmanaged("build", ItemKind::Skill),
            // matches search "re" but NOT kind=Skill -> dropped by kind
            make_unmanaged("render", ItemKind::Agent),
        ]);
        let nodes = build_tree(&snap, "re", Some(ItemKind::Skill), None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());
        let names: Vec<&str> = flat
            .iter()
            .filter_map(|n| match &n.node {
                TreeNode::UnmanagedItem(i) => Some(i.name.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            names,
            vec!["review"],
            "only the item matching BOTH search and kind survives: {names:?}"
        );
    }

    #[test]
    fn unmanaged_items_preserve_snapshot_kind_name_order() {
        // spec: UNM-6 - the unmanaged children are emitted in the snapshot's order
        // (the scanner sorts by (kind, name), UNM-1), with no reordering by
        // build_unmanaged_children. Feed an already-sorted snapshot and assert the
        // emitted node order matches it exactly.
        let snap = snap_with_unmanaged(vec![
            make_unmanaged("alpha", ItemKind::Skill),
            make_unmanaged("zeta", ItemKind::Skill),
            make_unmanaged("beta", ItemKind::Agent),
        ]);
        let nodes = build_tree(&snap, "", None, None, false, false);
        let group = nodes
            .iter()
            .find(|n| matches!(n.node, TreeNode::UnmanagedGroup))
            .expect("an unmanaged group node must be present");
        let order: Vec<&str> = group
            .children
            .iter()
            .filter_map(|n| match &n.node {
                TreeNode::UnmanagedItem(i) => Some(i.name.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            order,
            vec!["alpha", "zeta", "beta"],
            "node order must follow the snapshot order verbatim"
        );
    }

    #[test]
    fn unmanaged_group_sorts_after_installed_and_available() {
        // spec: UNM-6 - the synthetic unmanaged group is appended after the
        // Installed and Available group roots, so it is the last top-level group.
        let mut snap = snap_with(
            vec![make_installed(
                "skill:review",
                "review",
                "src/a",
                ItemKind::Skill,
            )],
            vec![make_available("agent:dev", "dev", "src/a", ItemKind::Agent)],
        );
        snap.unmanaged = vec![make_unmanaged("x", ItemKind::Skill)];
        let nodes = build_tree(&snap, "", None, None, false, false);
        assert!(matches!(nodes[0].node, TreeNode::InstalledGroup));
        assert!(matches!(nodes[1].node, TreeNode::AvailableGroup));
        assert!(
            matches!(nodes[2].node, TreeNode::UnmanagedGroup),
            "unmanaged group must be the last root group"
        );
        assert_eq!(nodes.len(), 3);
    }

    #[test]
    fn unmanaged_item_distinct_node_id_from_managed_same_name() {
        // spec: UNM-6 - an unmanaged item whose kind:name collides with a managed
        // installed item must still produce a DISTINCT tree node (its own id under
        // "unmanaged:") so the two are independently selectable. The unmanaged
        // item's key remains its kind:name, matching the managed key by value but
        // carried on a separate node (UNM-4 ambiguity is resolved at forget time).
        let mut snap = snap_with(
            vec![make_installed(
                "skill:review",
                "review",
                "src/a",
                ItemKind::Skill,
            )],
            vec![],
        );
        snap.unmanaged = vec![make_unmanaged("review", ItemKind::Skill)];
        let nodes = build_tree(&snap, "", None, None, false, false);
        let flat = flatten_tree(&nodes, &HashSet::new(), &HashSet::new());

        let installed_id = flat
            .iter()
            .find(|n| matches!(&n.node, TreeNode::InstalledItem(i) if i.name == "review"))
            .map(|n| n.id.clone())
            .expect("managed review must be present");
        let unmanaged_node = flat
            .iter()
            .find(|n| matches!(&n.node, TreeNode::UnmanagedItem(i) if i.name == "review"))
            .expect("unmanaged review must be present");
        assert_ne!(
            installed_id, unmanaged_node.id,
            "the colliding-name items must have distinct node ids"
        );
        assert_eq!(
            unmanaged_node.id, "unmanaged:skill:review",
            "the unmanaged node id is namespaced under 'unmanaged:'"
        );
        // Both keys equal kind:name by value, but the nodes are independent.
        if let TreeNode::UnmanagedItem(i) = &unmanaged_node.node {
            assert_eq!(i.key, "skill:review");
        } else {
            unreachable!();
        }
    }

    #[test]
    fn unmanaged_group_collapse_hides_items() {
        // spec: UNM-6 - the group is collapsible: with its id in `collapsed`, its
        // items disappear while the group header itself stays visible.
        let snap = snap_with_unmanaged(vec![make_unmanaged("x", ItemKind::Skill)]);
        let nodes = build_tree(&snap, "", None, None, false, false);
        let mut collapsed = HashSet::new();
        collapsed.insert("group:unmanaged".to_string());
        let flat = flatten_tree(&nodes, &HashSet::new(), &collapsed);
        let item_visible = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::UnmanagedItem(_)));
        let group_visible = flat
            .iter()
            .any(|n| matches!(&n.node, TreeNode::UnmanagedGroup));
        assert!(!item_visible, "collapsed group hides its items");
        assert!(
            group_visible,
            "the group header stays visible when collapsed"
        );
    }
}