croft-software 0.1.942

VSCode-style TUI written in Rust
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
//! Debug configurations (#250): `.vscode/launch.json` and `.croft/launch.json`.
//!
//! VS Code has carried program arguments, environment variables, working
//! directories, build steps, and attach targets in `launch.json` since 1.0;
//! croft's zero-config "Debug active file" covers none of that. This module
//! reads both files (JSONC tolerated, like tasks.json), resolves the
//! `${...}` substitution variables, and builds the DAP `launch`/`attach`
//! request for whichever adapter family the config's `type` names. Fields
//! croft doesn't know are passed through to the adapter verbatim — that is
//! how VS Code behaves, and it keeps adapter-specific keys (`sourceMaps`,
//! `justMyCode`, …) working without croft modelling them.
//!
//! Everything here is pure (filesystem in, values out); the App owns the
//! side effects (spawning adapters, running the preLaunchTask in a pane).

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde_json::{Map, Value, json};

use crate::dap::session::AdapterKind;

/// launch/attach — the two DAP session-starting requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequestKind {
    Launch,
    Attach,
}

/// One configuration as read from a launch.json, unresolved: substitution
/// variables still in place, every field kept in `raw`. Resolution happens at
/// F5 time (in [`resolve`]) because `${file}` depends on the active editor.
// `Eq` is intentionally not derived: `presentation.order` is a `f64`, and
// floats break total equality. (`ResolvedConfig` below DOES derive `Eq` - it
// carries no float - so it is not the precedent this looks like.) None of
// these is ever a map key, so `PartialEq` is all the call sites and tests
// need.
#[derive(Debug, Clone, PartialEq)]
pub struct DebugConfig {
    pub name: String,
    /// The `type` as written (`python`, `lldb`, `node`, …); mapped to an
    /// [`AdapterKind`] only at resolve time so an unsupported type shows a
    /// per-config error instead of being silently dropped from the picker.
    pub type_name: String,
    pub request: RequestKind,
    /// Which file declared it, for the picker's detail column.
    pub source: &'static str,
    /// The configuration's `presentation` (#318), when it declares a usable
    /// one. VS Code reads this on configurations as well as compounds and
    /// sorts BOTH kinds in one list, so a config that asks for a group must
    /// be able to sort against a compound that asks for the same one.
    pub presentation: Option<Presentation>,
    raw: Map<String, Value>,
}

/// Compounds declared beside the configurations, in the same precedence order
/// as [`discover_configs`]: `.croft/launch.json` wins over `.vscode`, and a
/// duplicate name from the lower-precedence file is dropped rather than
/// listed twice.
pub fn discover_compounds(root: &Path) -> Vec<Compound> {
    let mut out: Vec<Compound> = Vec::new();
    for rel in [".croft/launch.json", ".vscode/launch.json"] {
        let Ok(text) = std::fs::read_to_string(root.join(rel)) else {
            continue;
        };
        for c in parse_compounds(&text, rel) {
            if !out.iter().any(|existing| existing.name == c.name) {
                out.push(c);
            }
        }
    }
    out
}

/// Every configuration from every file, duplicates kept, in file-precedence
/// order. [`discover_configs`] is the picker's list and drops a lower-precedence
/// duplicate by name; a compound needs the ones it dropped, because its members
/// name configurations in ITS OWN file and both files may use the same name.
pub fn discover_configs_all(root: &Path) -> Vec<DebugConfig> {
    let mut out: Vec<DebugConfig> = Vec::new();
    for (rel, source) in [
        (".croft/launch.json", ".croft/launch.json"),
        (".vscode/launch.json", ".vscode/launch.json"),
    ] {
        let Ok(text) = std::fs::read_to_string(root.join(rel)) else {
            continue;
        };
        out.extend(parse_launch_json(&text, source));
    }
    out
}

/// Every configuration the workspace declares: `.croft/launch.json` first
/// (croft-native, same schema, no `.vscode/` directory required), then
/// `.vscode/launch.json`. Both are JSONC-tolerant. Order is preserved so the
/// picker lists them as written; duplicate names keep the first occurrence.
pub fn discover_configs(root: &Path) -> Vec<DebugConfig> {
    let mut out: Vec<DebugConfig> = Vec::new();
    for (rel, source) in [
        (".croft/launch.json", ".croft/launch.json"),
        (".vscode/launch.json", ".vscode/launch.json"),
    ] {
        let Ok(text) = std::fs::read_to_string(root.join(rel)) else {
            continue;
        };
        for cfg in parse_launch_json(&text, source) {
            if !out.iter().any(|c| c.name == cfg.name) {
                out.push(cfg);
            }
        }
    }
    out
}

/// Parse one launch.json body: either the VS Code shape
/// (`{"configurations": [...]}`) or a bare array. Entries without a `name`
/// or `type` are skipped (VS Code refuses to run those too). Pure.
pub fn parse_launch_json(text: &str, source: &'static str) -> Vec<DebugConfig> {
    let Ok(v) = serde_json::from_str::<Value>(&crate::tasks::strip_jsonc(text)) else {
        return Vec::new();
    };
    let list = match (&v, v.get("configurations")) {
        (_, Some(Value::Array(a))) => a.clone(),
        (Value::Array(a), _) => a.clone(),
        _ => return Vec::new(),
    };
    list.into_iter()
        .filter_map(|c| {
            let obj = c.as_object()?;
            let name = obj.get("name")?.as_str()?.to_string();
            let type_name = obj.get("type")?.as_str()?.to_string();
            let request = match obj.get("request").and_then(Value::as_str) {
                Some("attach") => RequestKind::Attach,
                // VS Code defaults an omitted `request` to launch.
                _ => RequestKind::Launch,
            };
            Some(DebugConfig {
                name,
                type_name,
                request,
                source,
                presentation: parse_presentation(obj),
                raw: obj.clone(),
            })
        })
        .collect()
}

/// A `presentation` block, as declared on a configuration OR a compound
/// (#318). VS Code reads the same three keys in both places and sorts the two
/// kinds together in one list, so croft parses it in both too.
// `Eq` is intentionally not derived: `presentation.order` is a `f64`, and
// floats break total equality. (`ResolvedConfig` below DOES derive `Eq` - it
// carries no float - so it is not the precedent this looks like.) None of
// these is ever a map key, so `PartialEq` is all the call sites and tests
// need.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Presentation {
    /// Do not list this entry in the picker.
    pub hidden: bool,
    /// The name entries are grouped under. Groups sort against each other by
    /// name; entries carrying one sort ahead of entries that do not.
    pub group: Option<String>,
    /// Position within the group, ascending. An entry with no numeric order
    /// sorts after the ones that have it.
    ///
    /// `f64` rather than an integer because VS Code's schema says `number`
    /// and its comparator subtracts one from the other, so `1.5` is a legal
    /// position between two neighbours - not the typo that a non-number is.
    pub order: Option<f64>,
}

/// Read a `presentation` block, if the entry declares one at all.
///
/// `None` only for ABSENT or unreadable. An empty block is still a block:
/// VS Code's comparator tests the object itself for truthiness (`if
/// (!first.presentation) … return 1`), so `{}` is truthy there and does sort
/// ahead of an entry carrying no block. Returning `None` for it would place
/// those rows differently than VS Code places them, which is the one thing a
/// transcription must not do.
///
/// The INNER checks stay truthiness-based, matching the same comparator: an
/// empty-string `group` is no group.
pub fn parse_presentation(obj: &Map<String, Value>) -> Option<Presentation> {
    let p = obj.get("presentation")?.as_object()?;
    let hidden = p.get("hidden").and_then(Value::as_bool).unwrap_or(false);
    let group = p
        .get("group")
        .and_then(Value::as_str)
        .filter(|g| !g.is_empty())
        .map(str::to_string);
    let order = p.get("order").and_then(Value::as_f64);
    Some(Presentation {
        hidden,
        group,
        order,
    })
}

/// The malformed `presentation` shapes this entry declares, named with their
/// parent so they can be found in the file (#318).
///
/// A value croft cannot read is a TYPO, and `{"order": "1"}` is the same
/// mistake as `{"hidden": "true"}`: quoted where it should be bare. Dropping
/// it silently would leave the user with a picker that ignores the ordering
/// they wrote and nothing to explain why.
///
/// Only COMPOUNDS act on this. A configuration has no refusal path to hang it
/// on - it launches directly rather than through a gate - so a config follows
/// VS Code and ignores what it cannot read.
pub fn malformed_presentation_keys(obj: &Map<String, Value>) -> Vec<&'static str> {
    let Some(value) = obj.get("presentation") else {
        return Vec::new();
    };
    // A key that REQUESTS NOTHING is honoured by doing nothing, and naming it
    // in a refusal would report a limitation croft does not have. `null`,
    // `false` and `""` are that shape; this list is the same one
    // `asks_for_something` applies to the sibling keys, kept in step with it
    // on purpose.
    if value.is_null() || value == &Value::Bool(false) || value.as_str().is_some_and(str::is_empty)
    {
        return Vec::new();
    }
    let Some(p) = value.as_object() else {
        return vec!["presentation"];
    };
    let mut out = Vec::new();
    for (key, path, well_formed) in [
        (
            "hidden",
            "presentation.hidden",
            Value::is_boolean as fn(&Value) -> bool,
        ),
        (
            "group",
            "presentation.group",
            Value::is_string as fn(&Value) -> bool,
        ),
        (
            "order",
            "presentation.order",
            Value::is_number as fn(&Value) -> bool,
        ),
    ] {
        if p.get(key).is_some_and(|v| !v.is_null() && !well_formed(v)) {
            out.push(path);
        }
    }
    out
}

/// Filter out hidden entries and sort the rest the way VS Code's
/// `getVisibleAndSorted` does (#318), so a launch.json ordered for VS Code
/// reads the same here.
///
/// The comparator is transcribed from `debugUtils.ts` rather than invented,
/// because every one of its rules is a decision croft would otherwise get
/// subtly wrong:
///
/// - an entry WITH a `presentation` sorts ahead of one without, so adding
///   `{"order": 1}` to a single entry lifts it above untouched neighbours;
/// - within those, an entry with a `group` sorts ahead of one without;
/// - groups compare by NAME, so grouping is alphabetical rather than
///   first-seen;
/// - inside a group, a numeric `order` sorts ahead of a missing one.
///
/// The sort is stable, matching JS, which is what keeps a workspace that
/// declares no `presentation` at all in exactly its file order - the case
/// that must not move.
///
/// One deliberate divergence: VS Code compares group names with
/// `localeCompare`, which is locale-aware collation; croft compares them
/// bytewise. The two agree on ASCII group names and can disagree on accented
/// ones, and matching it properly would mean taking a collation dependency
/// for the ordering of a picker.
pub fn visible_and_sorted<T>(
    items: Vec<T>,
    presentation: impl Fn(&T) -> Option<&Presentation>,
) -> Vec<T> {
    let mut kept: Vec<T> = items
        .into_iter()
        .filter(|i| !presentation(i).is_some_and(|p| p.hidden))
        .collect();
    kept.sort_by(|a, b| {
        use std::cmp::Ordering;
        let (Some(first), Some(second)) = (presentation(a), presentation(b)) else {
            return match (presentation(a), presentation(b)) {
                (None, None) => Ordering::Equal,
                (None, Some(_)) => Ordering::Greater,
                (Some(_), None) => Ordering::Less,
                _ => unreachable!("both-Some is handled by the outer let-else"),
            };
        };
        match (&first.group, &second.group) {
            (None, None) => compare_orders(first.order, second.order),
            (None, Some(_)) => Ordering::Greater,
            (Some(_), None) => Ordering::Less,
            (Some(g1), Some(g2)) if g1 != g2 => g1.cmp(g2),
            _ => compare_orders(first.order, second.order),
        }
    });
    kept
}

/// `order` against `order`: a declared one wins over a missing one, and two
/// missing ones tie (leaving the stable sort to keep file order).
fn compare_orders(first: Option<f64>, second: Option<f64>) -> std::cmp::Ordering {
    match (first, second) {
        (None, None) => std::cmp::Ordering::Equal,
        (None, Some(_)) => std::cmp::Ordering::Greater,
        (Some(_), None) => std::cmp::Ordering::Less,
        // `total_cmp` rather than `partial_cmp` with a fallback: JSON cannot
        // carry a NaN, but a comparator that answered `Equal` for one would
        // break transitivity, which `sort_by` panics on. A total order has no
        // such arm to get wrong. It orders `-0.0` before `0.0` where VS Code's
        // subtraction calls them equal; `"order": -0.0` is expressible and
        // nothing else about the two differs.
        (Some(a), Some(b)) => a.total_cmp(&b),
    }
}

/// A `compounds` entry: several configurations launched together under one
/// name. Members are stored as written and resolved against the file's
/// `configurations` at launch time, so a compound naming a configuration that
/// is later renamed fails loudly rather than launching a subset.
// `Eq` is intentionally not derived: `presentation.order` is a `f64`, and
// floats break total equality. (`ResolvedConfig` below DOES derive `Eq` - it
// carries no float - so it is not the precedent this looks like.) None of
// these is ever a map key, so `PartialEq` is all the call sites and tests
// need.
#[derive(Debug, Clone, PartialEq)]
pub struct Compound {
    pub name: String,
    pub configurations: Vec<String>,
    /// The compound's own `preLaunchTask`, if it asks for one (#318). Run
    /// before the member starts, and separate from the member's own task:
    /// VS Code runs both, so croft chains them rather than choosing.
    ///
    /// `None` for a key that is absent, `null`, or `""` - each of those
    /// requests nothing, and parking a launch behind a task named `""` would
    /// invent work the file never asked for.
    pub pre_launch_task: Option<String>,
    /// The compound's `presentation` (#318), when it declares a usable one.
    ///
    /// All three keys are honoured now: `hidden` filters the row, and
    /// `group`/`order` place it via [`visible_and_sorted`], which sorts
    /// compounds and configurations in ONE list the way VS Code does. Only
    /// the malformed shapes still refuse, and they are listed in
    /// `unsupported_keys`.
    pub presentation: Option<Presentation>,
    /// Keys croft does not honour that this compound ACTUALLY ASKS FOR,
    /// named with their parent so they can be found in the file. Since #318
    /// honoured all three, only VALUES croft cannot READ remain: a
    /// `presentation` that is not an object, or a `hidden`, `group` or
    /// `order` that is not a bool, string or number respectively.
    ///
    /// A `presentation` that is `null`, `false`, `""` or empty is not
    /// recorded: the first three ask for nothing, and an empty block asks
    /// only to be DECLARED, which the sort reads (it places such a row ahead
    /// of one carrying no block, as VS Code does). Inside the block only
    /// `null` is carved out, so `{"order": false}` IS recorded. A MALFORMED
    /// value is recorded rather than ignored: `{"hidden": "true"}` is the
    /// likely typo here, and launching it unhidden with no signal is worse
    /// than the refusal it replaces.
    ///
    /// A mistyped KEY (`{"grup": "a"}`) is still ignored in silence, on
    /// purpose: enumerating unknown keys would refuse whatever VS Code adds
    /// next.
    ///
    /// `stopAll` is deliberately absent at either value: it decides whether
    /// ending one session ends the others, which is meaningless for the
    /// single-session launch this list gates.
    ///
    /// Recorded rather than silently dropped because a ONE-member compound now
    /// launches, and launching it via its member alone would run neither the
    /// compound's own pre-launch task nor respect its presentation. Note the
    /// MULTI-member path still discards these silently: it refuses for the
    /// session count first, and #310 is the blocker the user must clear.
    pub unsupported_keys: Vec<&'static str>,
    /// Which file declared it. A compound's members name configurations in
    /// ITS OWN file first: both files may declare the same name, and binding
    /// a `.vscode` compound to a `.croft` config of that name would debug a
    /// different program than the compound was written against.
    pub source: &'static str,
}

impl Compound {
    /// Whether the compound asked not to be listed (#318).
    pub fn hidden(&self) -> bool {
        self.presentation.as_ref().is_some_and(|p| p.hidden)
    }
}

impl DebugConfig {
    /// Whether the configuration asked not to be listed (#318). Same question
    /// as [`Compound::hidden`], and the picker's badge asks it of both kinds
    /// so the count and the list cannot disagree.
    pub fn hidden(&self) -> bool {
        self.presentation.as_ref().is_some_and(|p| p.hidden)
    }
}

/// Parse the `compounds` array of a launch.json body. Sibling key of
/// `configurations`, so this reads the same text [`parse_launch_json`] does.
/// Entries without a `name` or a non-empty `configurations` list are skipped —
/// VS Code refuses to run those too, and an empty compound would present as a
/// picker row that does nothing.
pub fn parse_compounds(text: &str, source: &'static str) -> Vec<Compound> {
    let Ok(v) = serde_json::from_str::<Value>(&crate::tasks::strip_jsonc(text)) else {
        return Vec::new();
    };
    let Some(Value::Array(list)) = v.get("compounds") else {
        return Vec::new();
    };
    list.iter()
        .filter_map(|c| {
            let obj = c.as_object()?;
            let name = obj.get("name")?.as_str()?.to_string();
            // Members may be bare names or `{ "folder": …, "name": … }`
            // objects in multi-root workspaces; croft resolves against one
            // root, so take the name either way rather than dropping the row.
            //
            // Collect FALLIBLY: one unusable member drops the whole compound
            // rather than shrinking it to the members that happen to parse.
            // `resolve_compound` already refuses to launch a subset when a
            // member names no configuration; a malformed member is the same
            // situation one boundary earlier, and silently running two of the
            // three a user wrote is the outcome both guards exist to prevent.
            let configurations: Vec<String> = obj
                .get("configurations")?
                .as_array()?
                .iter()
                .map(|m| match m {
                    Value::String(s) => Some(s.clone()),
                    Value::Object(o) => o.get("name")?.as_str().map(str::to_string),
                    _ => None,
                })
                .collect::<Option<Vec<String>>>()?;
            if configurations.is_empty() {
                return None;
            }
            // Only `name` and `configurations` are read above. Every other key
            // VS Code defines is dropped here, which was harmless while no
            // compound could launch and is not any more — so record which ones
            // ASK FOR SOMETHING rather than which ones are merely present.
            //
            // Presence is the wrong test. `stopAll: false` is VS Code's own
            // default written out, and `preLaunchTask: null` requests nothing;
            // croft honours both perfectly by doing nothing, so refusing to
            // launch would name a key whose behaviour it is already delivering.
            //
            // `stopAll` is excluded from the ONE-member gate entirely, at either
            // value: it governs whether ending one session ends the others, and
            // with a single session there are no others. It cannot change a
            // one-member outcome, so it cannot be a reason to refuse one.
            let asks_for_something = |k: &str| match obj.get(k) {
                None | Some(Value::Null) => false,
                Some(Value::String(s)) => !s.is_empty(),
                Some(Value::Bool(b)) => *b,
                Some(Value::Object(o)) => !o.is_empty(),
                Some(_) => true,
            };
            // `preLaunchTask` left this list in #318: it is honoured now, so
            // naming it as a reason to refuse would report a limitation croft
            // no longer has. Its VALUE is captured instead - the key alone was
            // enough to refuse and is not enough to run anything.
            // `presentation` is no longer refused wholesale (#318): `hidden`
            // is a row filter and `group`/`order` place the row, all three
            // honoured by the picker's sort. Testing the SUB-KEYS rather than
            // the parent is what lets `{"hidden": true}` alone launch instead
            // of being refused for a capability it never asked for. Testing the SUB-KEYS rather than
            // the parent means `{"hidden": true}` alone launches instead of
            // being refused for a capability it never asked for.
            let presentation = parse_presentation(obj);
            // Only values croft cannot READ still refuse (#318). All three
            // keys are honoured, so what is left is a typo to fix rather than
            // a feature croft lacks: silently launching a compound whose
            // `{"hidden": "true"}` did nothing is a worse answer than the
            // refusal. Each is named WITH its parent, because a refusal
            // telling the user to "remove that key" would otherwise read as
            // deleting the whole `presentation` block, taking a working
            // `group` with it.
            let unsupported_keys: Vec<&'static str> = malformed_presentation_keys(obj);
            let pre_launch_task = asks_for_something("preLaunchTask")
                .then(|| obj.get("preLaunchTask").and_then(|v| v.as_str()))
                .flatten()
                .map(str::to_string);
            Some(Compound {
                name,
                configurations,
                source,
                pre_launch_task,
                presentation,
                unsupported_keys,
            })
        })
        .collect()
}

/// Resolve a compound's member names against the configurations declared
/// beside it, in the compound's own order. Pass [`discover_configs_all`], not
/// [`discover_configs`]: the latter drops a lower-precedence duplicate by name,
/// which is exactly the entry a `.vscode` compound naming that name needs, so
/// the source preference below would have nothing to prefer. Errors naming the first member that
/// does not exist — launching the subset that happens to resolve would debug
/// something other than what the user asked for, and silently.
pub fn resolve_compound<'a>(
    compound: &Compound,
    configs: &'a [DebugConfig],
) -> Result<Vec<&'a DebugConfig>, String> {
    compound
        .configurations
        .iter()
        .map(|want| {
            // The compound's own file first: `discover_configs` merges both
            // files with `.croft` winning a duplicate name, so a bare name
            // match would bind a `.vscode` compound to a `.croft` config that
            // may run a different program under a different adapter. Falling
            // back to any file keeps a compound working when its members live
            // in the sibling file, which VS Code also allows via `folder`.
            configs
                .iter()
                .find(|c| &c.name == want && c.source == compound.source)
                .or_else(|| configs.iter().find(|c| &c.name == want))
                .ok_or_else(|| {
                    format!(
                        "compound \"{}\" names configuration \"{}\", which no launch.json declares",
                        compound.name, want
                    )
                })
        })
        .collect()
}

/// Map a launch.json `type` onto the adapter family croft drives. Covers the
/// names the three bundled families are known under in existing repos.
pub fn adapter_for_type(type_name: &str) -> Option<AdapterKind> {
    match type_name {
        "python" | "debugpy" => Some(AdapterKind::Debugpy),
        "lldb" | "lldb-dap" | "cppdbg" | "codelldb" => Some(AdapterKind::LldbDap),
        "node" | "pwa-node" | "node-terminal" | "javascript" => Some(AdapterKind::JsDebug),
        _ => None,
    }
}

/// The editor state `${...}` variables resolve against.
#[derive(Debug, Clone)]
pub struct SubstCtx {
    pub workspace_folder: PathBuf,
    /// Active editor file; `None` makes `${file}`-family variables error.
    pub file: Option<PathBuf>,
}

/// Expand the supported `${...}` variables in `input`. An unknown or
/// unresolvable variable is a hard error naming it — VS Code launches with
/// the literal text and the program fails obscurely; croft refuses loudly
/// instead (issue #250 acceptance).
pub fn substitute(input: &str, ctx: &SubstCtx) -> Result<String, String> {
    let mut out = String::with_capacity(input.len());
    let mut rest = input;
    while let Some(start) = rest.find("${") {
        out.push_str(&rest[..start]);
        let after = &rest[start + 2..];
        let Some(end) = after.find('}') else {
            // No closing brace: not a variable, keep the text as written.
            out.push_str(&rest[start..]);
            return Ok(out);
        };
        let var = &after[..end];
        out.push_str(&expand_variable(var, ctx)?);
        rest = &after[end + 1..];
    }
    out.push_str(rest);
    Ok(out)
}

fn expand_variable(var: &str, ctx: &SubstCtx) -> Result<String, String> {
    let file = || {
        ctx.file
            .as_deref()
            .ok_or_else(|| format!("${{{var}}}: no active file"))
    };
    match var {
        "workspaceFolder" | "workspaceRoot" => {
            Ok(ctx.workspace_folder.to_string_lossy().into_owned())
        }
        "workspaceFolderBasename" => Ok(ctx
            .workspace_folder
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default()),
        "file" => Ok(file()?.to_string_lossy().into_owned()),
        "fileBasename" => Ok(file()?
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default()),
        "fileBasenameNoExtension" => Ok(file()?
            .file_stem()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default()),
        "fileDirname" => Ok(file()?
            .parent()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default()),
        "fileExtname" => Ok(file()?
            .extension()
            .map(|e| format!(".{}", e.to_string_lossy()))
            .unwrap_or_default()),
        "cwd" => Ok(ctx.workspace_folder.to_string_lossy().into_owned()),
        "pathSeparator" => Ok(String::from(std::path::MAIN_SEPARATOR_STR)),
        _ => {
            if let Some(name) = var.strip_prefix("env:") {
                return std::env::var(name)
                    .map_err(|_| format!("${{env:{name}}}: environment variable not set"));
            }
            Err(format!("${{{var}}}: unsupported substitution variable"))
        }
    }
}

/// Recursively expand `${...}` in every string of `v` (object values and
/// array elements included), so passthrough fields get substitution too.
fn substitute_value(v: &Value, ctx: &SubstCtx) -> Result<Value, String> {
    Ok(match v {
        Value::String(s) => Value::String(substitute(s, ctx)?),
        Value::Array(a) => Value::Array(
            a.iter()
                .map(|x| substitute_value(x, ctx))
                .collect::<Result<_, _>>()?,
        ),
        Value::Object(o) => Value::Object(
            o.iter()
                .map(|(k, x)| Ok((k.clone(), substitute_value(x, ctx)?)))
                .collect::<Result<_, String>>()?,
        ),
        other => other.clone(),
    })
}

/// A configuration with substitution done and the mapped fields split out,
/// ready to become a DAP request. `extra` carries every field croft didn't
/// map, already substituted, for verbatim passthrough.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedConfig {
    pub name: String,
    pub kind: AdapterKind,
    pub request: RequestKind,
    pub program: Option<String>,
    /// debugpy `module` (`"module": "pytest"` style launches).
    pub module: Option<String>,
    pub args: Vec<String>,
    /// `env` merged over `envFile` (explicit `env` wins per key).
    pub env: BTreeMap<String, String>,
    pub cwd: Option<PathBuf>,
    pub pre_launch_task: Option<String>,
    pub stop_on_entry: bool,
    pub port: Option<u16>,
    pub process_id: Option<i64>,
    pub extra: Map<String, Value>,
}

/// The fields [`resolve`] consumes; everything else lands in `extra`.
const MAPPED_KEYS: &[&str] = &[
    "name",
    "type",
    "request",
    "program",
    "module",
    "args",
    "env",
    "envFile",
    "cwd",
    "preLaunchTask",
    "stopOnEntry",
    "port",
    "processId",
    // Forced to internalConsole: croft debugs in-process and declines the
    // `runInTerminal` reverse request, so honouring an integratedTerminal
    // console would hang the session at launch.
    "console",
];

/// Resolve `cfg` against the editor state: substitute variables, load the
/// `envFile`, and split the mapped fields. Errors are user-facing strings
/// (unknown type, unresolved variable, unreadable envFile).
pub fn resolve(cfg: &DebugConfig, ctx: &SubstCtx) -> Result<ResolvedConfig, String> {
    let kind = adapter_for_type(&cfg.type_name).ok_or_else(|| {
        format!(
            "config \"{}\": unsupported type \"{}\" (python, lldb, and node families are supported)",
            cfg.name, cfg.type_name
        )
    })?;
    let raw = Value::Object(cfg.raw.clone());
    let raw = substitute_value(&raw, ctx).map_err(|e| format!("config \"{}\": {e}", cfg.name))?;
    let obj = raw.as_object().expect("substitution preserves the object");

    let get_str = |key: &str| obj.get(key).and_then(Value::as_str).map(str::to_string);
    let mut env: BTreeMap<String, String> = BTreeMap::new();
    if let Some(env_file) = get_str("envFile") {
        let path = absolute_in(&env_file, &ctx.workspace_folder);
        let text = std::fs::read_to_string(&path)
            .map_err(|e| format!("config \"{}\": envFile {}: {e}", cfg.name, path.display()))?;
        env.extend(parse_env_file(&text));
    }
    if let Some(map) = obj.get("env").and_then(Value::as_object) {
        for (k, v) in map {
            // VS Code allows non-string scalars here; stringify them.
            let val = match v {
                Value::String(s) => s.clone(),
                other => other.to_string(),
            };
            env.insert(k.clone(), val);
        }
    }
    let args = obj
        .get("args")
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .map(|x| match x {
                    Value::String(s) => s.clone(),
                    other => other.to_string(),
                })
                .collect()
        })
        .unwrap_or_default();
    let port = obj
        .get("port")
        .and_then(Value::as_u64)
        .and_then(|p| u16::try_from(p).ok());
    let process_id = match obj.get("processId") {
        Some(Value::Number(n)) => n.as_i64(),
        Some(Value::String(s)) => s.trim().parse::<i64>().ok(),
        _ => None,
    };
    let extra: Map<String, Value> = obj
        .iter()
        .filter(|(k, _)| !MAPPED_KEYS.contains(&k.as_str()))
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    Ok(ResolvedConfig {
        name: cfg.name.clone(),
        kind,
        request: cfg.request,
        program: get_str("program"),
        module: get_str("module"),
        args,
        env,
        cwd: get_str("cwd").map(|c| absolute_in(&c, &ctx.workspace_folder)),
        pre_launch_task: get_str("preLaunchTask"),
        stop_on_entry: obj
            .get("stopOnEntry")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        port,
        process_id,
        extra,
    })
}

/// Resolve a possibly-relative path against the workspace folder (VS Code
/// resolves `envFile` and `cwd` the same way).
pub fn absolute_in(path: &str, workspace_folder: &Path) -> PathBuf {
    let p = PathBuf::from(path);
    if p.is_absolute() {
        p
    } else {
        workspace_folder.join(p)
    }
}

/// Parse a dotenv-style file: `KEY=VALUE` lines, `#` comments, blank lines,
/// an optional `export ` prefix, and single/double quotes around the value.
pub fn parse_env_file(text: &str) -> BTreeMap<String, String> {
    let mut out = BTreeMap::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let line = line.strip_prefix("export ").unwrap_or(line).trim_start();
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let key = key.trim();
        if key.is_empty() || key.contains(char::is_whitespace) {
            continue;
        }
        let value = value.trim();
        let value = value
            .strip_prefix('"')
            .and_then(|v| v.strip_suffix('"'))
            .or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
            .unwrap_or(value);
        out.insert(key.to_string(), value.to_string());
    }
    out
}

/// Start from the passthrough fields and layer the mapped ones on top, so a
/// mapped field always wins over a duplicate left in `extra`.
fn base_arguments(rc: &ResolvedConfig) -> Map<String, Value> {
    let mut args = rc.extra.clone();
    if let Some(p) = &rc.program {
        args.insert("program".into(), json!(p));
    }
    if !rc.args.is_empty() {
        args.insert("args".into(), json!(rc.args));
    }
    if let Some(c) = &rc.cwd {
        args.insert("cwd".into(), json!(c.to_string_lossy()));
    }
    args.insert("stopOnEntry".into(), json!(rc.stop_on_entry));
    args
}

fn request_value(command: &str, arguments: Map<String, Value>) -> Value {
    json!({
        "type": "request",
        "command": command,
        "arguments": Value::Object(arguments),
    })
}

/// Build the debugpy `launch`/`attach` request. `debug_venv_python` is the
/// interpreter of croft's debug venv, used as the debuggee interpreter when
/// the config doesn't name its own `python`.
pub fn debugpy_request(rc: &ResolvedConfig, debug_venv_python: &Path) -> Value {
    let mut args = base_arguments(rc);
    match rc.request {
        RequestKind::Launch => {
            args.insert("request".into(), json!("launch"));
            if let Some(m) = &rc.module {
                args.insert("module".into(), json!(m));
                // debugpy rejects a launch naming both program and module.
                args.remove("program");
            }
            if !rc.env.is_empty() {
                args.insert("env".into(), json!(rc.env));
            }
            if !args.contains_key("python") {
                args.insert(
                    "python".into(),
                    json!([debug_venv_python.to_string_lossy()]),
                );
            }
            args.insert("console".into(), json!("internalConsole"));
            if !args.contains_key("justMyCode") {
                args.insert("justMyCode".into(), json!(false));
            }
            request_value("launch", args)
        }
        RequestKind::Attach => {
            args.insert("request".into(), json!("attach"));
            if let Some(port) = rc.port
                && !args.contains_key("connect")
            {
                let host = args.remove("host").unwrap_or_else(|| json!("127.0.0.1"));
                args.insert("connect".into(), json!({ "host": host, "port": port }));
            }
            request_value("attach", args)
        }
    }
}

/// Build the lldb-dap `launch`/`attach` request. `env` uses the
/// `"VAR=VALUE"` string-array format lldb-dap has accepted since
/// lldb-vscode. Attach targets `pid`.
pub fn lldb_request(rc: &ResolvedConfig) -> Value {
    let mut args = base_arguments(rc);
    if !rc.env.is_empty() {
        let pairs: Vec<String> = rc.env.iter().map(|(k, v)| format!("{k}={v}")).collect();
        args.insert("env".into(), json!(pairs));
    }
    match rc.request {
        RequestKind::Launch => request_value("launch", args),
        RequestKind::Attach => {
            if let Some(pid) = rc.process_id {
                args.insert("pid".into(), json!(pid));
            }
            // Attaching runs an existing process; launch-only keys confuse
            // some lldb-dap builds.
            args.remove("stopOnEntry");
            request_value("attach", args)
        }
    }
}

/// Build the vscode-js-debug `launch`/`attach` request (`pwa-node`, the
/// canonical Node type — croft already normalises onto it for zero-config).
pub fn js_request(rc: &ResolvedConfig) -> Value {
    let mut args = base_arguments(rc);
    args.insert("type".into(), json!("pwa-node"));
    if !rc.env.is_empty() {
        args.insert("env".into(), json!(rc.env));
    }
    match rc.request {
        RequestKind::Launch => {
            args.insert("request".into(), json!("launch"));
            args.insert("console".into(), json!("internalConsole"));
            if !args.contains_key("sourceMaps") {
                args.insert("sourceMaps".into(), json!(true));
            }
            request_value("launch", args)
        }
        RequestKind::Attach => {
            args.insert("request".into(), json!("attach"));
            if let Some(port) = rc.port {
                args.insert("port".into(), json!(port));
            }
            if !args.contains_key("address") {
                args.insert("address".into(), json!("127.0.0.1"));
            }
            args.remove("stopOnEntry");
            request_value("attach", args)
        }
    }
}

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

    fn ctx() -> SubstCtx {
        SubstCtx {
            workspace_folder: PathBuf::from("/work/proj"),
            file: Some(PathBuf::from("/work/proj/src/main.py")),
        }
    }

    fn config(json_text: &str) -> DebugConfig {
        parse_launch_json(json_text, ".vscode/launch.json")
            .into_iter()
            .next()
            .expect("one config")
    }

    #[test]
    fn parses_vscode_shape_bare_arrays_and_jsonc() {
        let vscode = r#"{
  // launch.json allows comments
  "version": "0.2.0",
  "configurations": [
    { "name": "Run API", "type": "python", "request": "launch", "program": "api.py", },
  ],
}"#;
        let cfgs = parse_launch_json(vscode, ".vscode/launch.json");
        assert_eq!(cfgs.len(), 1);
        assert_eq!(cfgs[0].name, "Run API");
        assert_eq!(cfgs[0].request, RequestKind::Launch);

        let bare = r#"[ { "name": "A", "type": "lldb", "request": "attach", "pid": 1 } ]"#;
        let cfgs = parse_launch_json(bare, ".croft/launch.json");
        assert_eq!(cfgs.len(), 1);
        assert_eq!(cfgs[0].request, RequestKind::Attach);
    }

    #[test]
    fn entries_without_name_or_type_are_skipped_and_request_defaults_to_launch() {
        let text = r#"{ "configurations": [
            { "type": "python", "program": "a.py" },
            { "name": "no type" },
            { "name": "ok", "type": "node", "program": "s.js" }
        ]}"#;
        let cfgs = parse_launch_json(text, ".vscode/launch.json");
        assert_eq!(cfgs.len(), 1);
        assert_eq!(cfgs[0].name, "ok");
        assert_eq!(cfgs[0].request, RequestKind::Launch);
    }

    #[test]
    fn croft_file_wins_duplicate_names_and_both_files_are_read() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
        std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
        std::fs::write(
            tmp.path().join(".croft/launch.json"),
            r#"[ { "name": "Serve", "type": "python", "program": "croft.py" } ]"#,
        )
        .unwrap();
        std::fs::write(
            tmp.path().join(".vscode/launch.json"),
            r#"{ "configurations": [
                { "name": "Serve", "type": "python", "program": "vscode.py" },
                { "name": "Worker", "type": "node", "program": "w.js" }
            ]}"#,
        )
        .unwrap();
        let cfgs = discover_configs(tmp.path());
        assert_eq!(cfgs.len(), 2);
        assert_eq!(cfgs[0].name, "Serve");
        assert_eq!(cfgs[0].source, ".croft/launch.json");
        assert_eq!(cfgs[0].raw["program"], "croft.py");
        assert_eq!(cfgs[1].name, "Worker");
    }

    #[test]
    fn maps_the_three_adapter_families_and_rejects_unknown_types() {
        use AdapterKind::*;
        for (t, k) in [
            ("python", Debugpy),
            ("debugpy", Debugpy),
            ("lldb", LldbDap),
            ("cppdbg", LldbDap),
            ("node", JsDebug),
            ("pwa-node", JsDebug),
        ] {
            assert_eq!(adapter_for_type(t), Some(k), "{t}");
        }
        assert_eq!(adapter_for_type("go"), None);
        let cfg = config(r#"[{ "name": "Go", "type": "go", "program": "main.go" }]"#);
        let err = resolve(&cfg, &ctx()).unwrap_err();
        assert!(err.contains("unsupported type \"go\""), "{err}");
    }

    #[test]
    fn substitutes_workspace_and_file_variables() {
        let c = ctx();
        assert_eq!(
            substitute("${workspaceFolder}/bin", &c).unwrap(),
            "/work/proj/bin"
        );
        assert_eq!(
            substitute("${workspaceFolderBasename}", &c).unwrap(),
            "proj"
        );
        assert_eq!(substitute("${file}", &c).unwrap(), "/work/proj/src/main.py");
        assert_eq!(substitute("${fileBasename}", &c).unwrap(), "main.py");
        assert_eq!(
            substitute("${fileBasenameNoExtension}", &c).unwrap(),
            "main"
        );
        assert_eq!(substitute("${fileDirname}", &c).unwrap(), "/work/proj/src");
        assert_eq!(substitute("${fileExtname}", &c).unwrap(), ".py");
        assert_eq!(
            substitute("a ${fileBasename} b ${fileBasename}", &c).unwrap(),
            "a main.py b main.py"
        );
        // Text without variables (or with an unclosed brace) passes through.
        assert_eq!(substitute("plain", &c).unwrap(), "plain");
        assert_eq!(substitute("odd ${file", &c).unwrap(), "odd ${file");
    }

    #[test]
    fn env_variable_expands_and_unknowns_error_loudly() {
        let c = ctx();
        // SAFETY: test-only env mutation, name is unique to this test.
        unsafe { std::env::set_var("CROFT_TEST_SUBST_VAR", "xyz") };
        assert_eq!(
            substitute("${env:CROFT_TEST_SUBST_VAR}", &c).unwrap(),
            "xyz"
        );
        let err = substitute("${env:CROFT_TEST_UNSET_VAR}", &c).unwrap_err();
        assert!(err.contains("CROFT_TEST_UNSET_VAR"), "{err}");
        let err = substitute("${command:pickProcess}", &c).unwrap_err();
        assert!(err.contains("command:pickProcess"), "{err}");
        // ${file} family errors when no file is active.
        let no_file = SubstCtx {
            workspace_folder: PathBuf::from("/w"),
            file: None,
        };
        assert!(substitute("${fileBasename}", &no_file).is_err());
    }

    #[test]
    fn resolve_splits_mapped_fields_and_passes_the_rest_through() {
        let cfg = config(
            r#"[{
                "name": "API",
                "type": "python",
                "request": "launch",
                "program": "${workspaceFolder}/api.py",
                "args": ["--port", 8080],
                "env": { "MODE": "dev", "RETRIES": 3 },
                "cwd": "${workspaceFolder}",
                "preLaunchTask": "build",
                "stopOnEntry": true,
                "justMyCode": true,
                "subProcess": "${workspaceFolderBasename}"
            }]"#,
        );
        let rc = resolve(&cfg, &ctx()).unwrap();
        assert_eq!(rc.program.as_deref(), Some("/work/proj/api.py"));
        assert_eq!(rc.args, vec!["--port", "8080"]);
        assert_eq!(rc.env["MODE"], "dev");
        assert_eq!(rc.env["RETRIES"], "3");
        assert_eq!(rc.cwd.as_deref(), Some(Path::new("/work/proj")));
        assert_eq!(rc.pre_launch_task.as_deref(), Some("build"));
        assert!(rc.stop_on_entry);
        // Unmapped fields survive, substituted, for verbatim passthrough.
        assert_eq!(rc.extra["justMyCode"], json!(true));
        assert_eq!(rc.extra["subProcess"], json!("proj"));
        assert!(!rc.extra.contains_key("program"));
    }

    #[test]
    fn a_relative_cwd_resolves_against_the_workspace_folder() {
        let cfg =
            config(r#"[{ "name": "R", "type": "python", "program": "a.py", "cwd": "backend" }]"#);
        let rc = resolve(&cfg, &ctx()).unwrap();
        assert_eq!(rc.cwd.as_deref(), Some(Path::new("/work/proj/backend")));
        // An absolute cwd is kept as written.
        let cfg =
            config(r#"[{ "name": "R", "type": "python", "program": "a.py", "cwd": "/srv/app" }]"#);
        let rc = resolve(&cfg, &ctx()).unwrap();
        assert_eq!(rc.cwd.as_deref(), Some(Path::new("/srv/app")));
    }

    #[test]
    fn env_file_merges_under_explicit_env() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join(".env"),
            "# comment\nexport FROM_FILE=1\nSHARED=file\nQUOTED=\"a b\"\n",
        )
        .unwrap();
        let cfg = config(
            r#"[{
                "name": "E", "type": "python", "program": "a.py",
                "envFile": "${workspaceFolder}/.env",
                "env": { "SHARED": "config" }
            }]"#,
        );
        let c = SubstCtx {
            workspace_folder: tmp.path().to_path_buf(),
            file: None,
        };
        let rc = resolve(&cfg, &c).unwrap();
        assert_eq!(rc.env["FROM_FILE"], "1");
        assert_eq!(rc.env["QUOTED"], "a b");
        assert_eq!(rc.env["SHARED"], "config", "explicit env wins per key");
        // A missing envFile is a hard, named error.
        let cfg = config(
            r#"[{ "name": "E", "type": "python", "program": "a.py", "envFile": "/nope/.env" }]"#,
        );
        let err = resolve(&cfg, &c).unwrap_err();
        assert!(err.contains("/nope/.env"), "{err}");
    }

    #[test]
    fn debugpy_launch_request_carries_env_args_and_forces_internal_console() {
        let cfg = config(
            r#"[{
                "name": "API", "type": "python", "program": "/p/api.py",
                "args": ["--serve"], "env": { "MODE": "dev" },
                "console": "integratedTerminal"
            }]"#,
        );
        let rc = resolve(&cfg, &ctx()).unwrap();
        let req = debugpy_request(&rc, Path::new("/venv/bin/python"));
        assert_eq!(req["command"], "launch");
        assert_eq!(req["arguments"]["program"], "/p/api.py");
        assert_eq!(req["arguments"]["args"][0], "--serve");
        assert_eq!(req["arguments"]["env"]["MODE"], "dev");
        assert_eq!(req["arguments"]["python"][0], "/venv/bin/python");
        assert_eq!(req["arguments"]["justMyCode"], false);
        // integratedTerminal would hang on the declined runInTerminal.
        assert_eq!(req["arguments"]["console"], "internalConsole");
    }

    #[test]
    fn debugpy_module_launch_drops_program_and_attach_builds_connect() {
        let cfg = config(
            r#"[{ "name": "T", "type": "python", "module": "pytest", "args": ["-k", "x"] }]"#,
        );
        let rc = resolve(&cfg, &ctx()).unwrap();
        let req = debugpy_request(&rc, Path::new("/venv/bin/python"));
        assert_eq!(req["arguments"]["module"], "pytest");
        assert!(req["arguments"].get("program").is_none());

        let cfg =
            config(r#"[{ "name": "A", "type": "python", "request": "attach", "port": 5678 }]"#);
        let rc = resolve(&cfg, &ctx()).unwrap();
        let req = debugpy_request(&rc, Path::new("/venv/bin/python"));
        assert_eq!(req["command"], "attach");
        assert_eq!(req["arguments"]["connect"]["port"], 5678);
        assert_eq!(req["arguments"]["connect"]["host"], "127.0.0.1");
    }

    #[test]
    fn lldb_requests_use_kv_env_and_attach_by_pid() {
        let cfg = config(
            r#"[{
                "name": "Bin", "type": "lldb", "program": "/t/debug/app",
                "args": ["--flag"], "env": { "RUST_LOG": "debug" }
            }]"#,
        );
        let rc = resolve(&cfg, &ctx()).unwrap();
        let req = lldb_request(&rc);
        assert_eq!(req["command"], "launch");
        assert_eq!(req["arguments"]["program"], "/t/debug/app");
        assert_eq!(req["arguments"]["env"][0], "RUST_LOG=debug");

        let cfg = config(
            r#"[{ "name": "At", "type": "lldb", "request": "attach", "processId": "4242" }]"#,
        );
        let rc = resolve(&cfg, &ctx()).unwrap();
        assert_eq!(rc.process_id, Some(4242), "numeric string processId parses");
        let req = lldb_request(&rc);
        assert_eq!(req["command"], "attach");
        assert_eq!(req["arguments"]["pid"], 4242);
        assert!(req["arguments"].get("stopOnEntry").is_none());
    }

    #[test]
    fn js_requests_are_pwa_node_and_attach_by_port() {
        let cfg = config(
            r#"[{ "name": "S", "type": "node", "program": "/p/server.js", "sourceMaps": false }]"#,
        );
        let rc = resolve(&cfg, &ctx()).unwrap();
        let req = js_request(&rc);
        assert_eq!(req["command"], "launch");
        assert_eq!(req["arguments"]["type"], "pwa-node");
        assert_eq!(
            req["arguments"]["sourceMaps"], false,
            "user value respected"
        );
        assert_eq!(req["arguments"]["console"], "internalConsole");

        let cfg = config(r#"[{ "name": "A", "type": "node", "request": "attach", "port": 9229 }]"#);
        let rc = resolve(&cfg, &ctx()).unwrap();
        let req = js_request(&rc);
        assert_eq!(req["command"], "attach");
        assert_eq!(req["arguments"]["port"], 9229);
        assert_eq!(req["arguments"]["address"], "127.0.0.1");
    }

    #[test]
    fn parse_env_file_handles_comments_export_and_quotes() {
        let env = parse_env_file(
            "# a comment\n\nexport A=1\nB = spaced \nC='sq'\nnot a pair\nBAD KEY=x\n",
        );
        assert_eq!(env["A"], "1");
        assert_eq!(env["B"], "spaced");
        assert_eq!(env["C"], "sq");
        assert!(!env.contains_key("not a pair"));
        assert!(!env.contains_key("BAD KEY"));
    }

    /// #250 phase 2: `compounds` names several configurations to launch
    /// together. It is a sibling key of `configurations` in the same file, so
    /// it parses alongside them rather than needing its own discovery pass.
    /// Multi-root workspaces write members as `{ "folder": …, "name": … }`
    /// rather than bare strings. croft resolves against one root, so the name
    /// is taken either way — dropping the row would silently shrink a compound
    /// to the members that happen to be written in the short form.
    #[test]
    fn compound_members_may_be_folder_name_objects_as_well_as_bare_strings() {
        let text = r#"{"configurations":[
              {"name":"Server","type":"lldb","request":"launch"},
              {"name":"Client","type":"lldb","request":"launch"}],
            "compounds":[{"name":"Mixed","configurations":[
              "Server",
              {"folder":"web","name":"Client"}]}]}"#;

        let compounds = parse_compounds(text, ".vscode/launch.json");
        assert_eq!(compounds.len(), 1, "precondition: the compound parsed");
        assert_eq!(
            compounds[0].configurations,
            vec!["Server", "Client"],
            "an object member contributes its name, exactly as a bare string does"
        );
    }

    /// A compound must bind to the configurations ITS OWN FILE declares. Both
    /// files may declare the same name — `.croft` wins the picker row, but a
    /// `.vscode` compound naming "Server" means .vscode's Server, which may be
    /// a different program under a different adapter. Matching by bare name
    /// against the merged list launches something other than what the user
    /// wrote, which is the same rule the parse and resolve boundaries already
    /// enforce for missing and malformed members.
    #[test]
    fn a_compound_binds_to_its_own_files_configuration_not_a_same_named_one() {
        let croft = r#"{"configurations":[
              {"name":"Server","type":"python","request":"launch","program":"croft.py"}]}"#;
        let vscode = r#"{"configurations":[
              {"name":"Server","type":"node","request":"launch","program":"vscode.js"}],
            "compounds":[{"name":"VsCompound","configurations":["Server"]}]}"#;

        // Through the PRODUCTION path, not hand-stitched input. Building the
        // config list with two `parse_launch_json` calls asserts a property on
        // an input shape the shipped program never produces: `discover_configs`
        // keeps only the first occurrence per name, so the duplicate this
        // preference exists to disambiguate would already be gone.
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
        std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
        std::fs::write(tmp.path().join(".croft/launch.json"), croft).unwrap();
        std::fs::write(tmp.path().join(".vscode/launch.json"), vscode).unwrap();

        let configs = discover_configs_all(tmp.path());
        let compounds = discover_compounds(tmp.path());
        assert_eq!(compounds.len(), 1, "precondition: the compound parsed");
        assert_eq!(
            compounds[0].source, ".vscode/launch.json",
            "precondition: the compound remembers which file declared it"
        );
        assert_eq!(
            configs.iter().filter(|c| c.name == "Server").count(),
            2,
            "precondition: the list resolve_compound receives still holds BOTH \
             Servers — `discover_configs` would have dropped one, leaving the \
             source preference nothing to prefer"
        );
        assert_eq!(
            discover_configs(tmp.path())
                .iter()
                .filter(|c| c.name == "Server")
                .count(),
            1,
            "and the picker's list drops it, which is why the two lists differ"
        );

        let members = resolve_compound(&compounds[0], &configs).expect("resolves");
        assert_eq!(
            members[0].source, ".vscode/launch.json",
            "the .vscode compound binds .vscode's Server, not .croft's same-named one"
        );
        assert_eq!(
            members[0].type_name, "node",
            "which is a different adapter — binding .croft's python config here \
             would debug a different program than the compound declares"
        );
    }

    /// A compound with SOME unusable members must be dropped whole, not
    /// silently shrunk to the ones that parse. `resolve_compound` already
    /// refuses to launch a subset when a member names no configuration —
    /// "launching the subset that happens to resolve would debug something
    /// other than what the user asked for, and silently" — and a malformed
    /// member is the same situation one boundary earlier.
    #[test]
    fn a_compound_with_one_unusable_member_is_dropped_rather_than_silently_shrunk() {
        let text = r#"{"configurations":[
              {"name":"A","type":"lldb","request":"launch"},
              {"name":"B","type":"lldb","request":"launch"}],
            "compounds":[
              {"name":"Partial","configurations":["A", 7, "B"]},
              {"name":"Whole","configurations":["A","B"]}]}"#;

        let names: Vec<String> = parse_compounds(text, ".vscode/launch.json")
            .into_iter()
            .map(|c| c.name)
            .collect();
        assert_eq!(
            names,
            vec!["Whole"],
            "the compound with a malformed member is dropped entirely — shrinking \
             it to [\"A\", \"B\"] would launch two of the three the user wrote"
        );
    }

    /// A compound whose members all fail to parse would present as a picker row
    /// that does nothing, so it is skipped entirely rather than listed empty.
    #[test]
    fn a_compound_with_no_usable_members_is_skipped_rather_than_listed_empty() {
        let text = r#"{"configurations":[{"name":"A","type":"lldb","request":"launch"}],
            "compounds":[
              {"name":"Empty","configurations":[]},
              {"name":"Unusable","configurations":[7, true]},
              {"name":"Real","configurations":["A"]}]}"#;

        let names: Vec<String> = parse_compounds(text, ".vscode/launch.json")
            .into_iter()
            .map(|c| c.name)
            .collect();
        assert_eq!(
            names,
            vec!["Real"],
            "an empty compound and one whose members are all unusable are both dropped"
        );
    }

    #[test]
    fn discover_compounds_prefers_croft_over_vscode_for_a_duplicate_name() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join(".croft")).unwrap();
        std::fs::create_dir_all(root.join(".vscode")).unwrap();
        std::fs::write(
            root.join(".croft/launch.json"),
            r#"{"configurations":[{"name":"A","type":"lldb","request":"launch"}],
                "compounds":[{"name":"Both","configurations":["A"]}]}"#,
        )
        .unwrap();
        std::fs::write(
            root.join(".vscode/launch.json"),
            r#"{"configurations":[{"name":"B","type":"lldb","request":"launch"}],
                "compounds":[{"name":"Both","configurations":["B"]},
                             {"name":"VsOnly","configurations":["B"]}]}"#,
        )
        .unwrap();

        let found = discover_compounds(root);
        let names: Vec<&str> = found.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["Both", "VsOnly"],
            "both files contribute, .croft first"
        );
        assert_eq!(
            found[0].configurations,
            vec!["A"],
            "the .croft definition of a duplicate name wins, not .vscode's"
        );
    }

    #[test]
    fn compounds_are_parsed_alongside_the_configurations_they_name() {
        let text = r#"{
            "configurations": [
                { "name": "Server", "type": "node", "program": "s.js" },
                { "name": "Client", "type": "node", "program": "c.js" }
            ],
            "compounds": [
                { "name": "Full Stack", "configurations": ["Server", "Client"] }
            ]
        }"#;
        // Precondition: the configurations themselves parse, so a compound
        // finding nothing cannot be blamed on the file being unreadable.
        let cfgs = parse_launch_json(text, ".vscode/launch.json");
        assert_eq!(cfgs.len(), 2, "precondition: both configurations parsed");

        let compounds = parse_compounds(text, ".vscode/launch.json");
        assert_eq!(compounds.len(), 1, "the compound is found");
        assert_eq!(compounds[0].name, "Full Stack");
        assert_eq!(compounds[0].configurations, vec!["Server", "Client"]);
    }

    /// A compound naming a configuration that does not exist must fail loudly
    /// at resolve time rather than silently launching the subset it can find —
    /// the same posture as an unresolvable `${...}` variable (#250).
    #[test]
    fn a_compound_naming_a_missing_configuration_errors_rather_than_launching_a_subset() {
        let text = r#"{
            "configurations": [ { "name": "Server", "type": "node", "program": "s.js" } ],
            "compounds": [ { "name": "Both", "configurations": ["Server", "Ghost"] } ]
        }"#;
        let cfgs = parse_launch_json(text, ".vscode/launch.json");
        let compounds = parse_compounds(text, ".vscode/launch.json");
        assert_eq!(compounds.len(), 1, "precondition: the compound parsed");

        let err = resolve_compound(&compounds[0], &cfgs)
            .expect_err("a missing member is an error, not a shorter list");
        assert!(
            err.contains("Ghost"),
            "the error names the missing configuration, got: {err}"
        );
    }

    /// A key PRESENT but requesting nothing must not be recorded as
    /// unsupported. `contains_key` was the first attempt and it refused these:
    /// `stopAll: false` is VS Code's own default written out, and a null or
    /// empty `preLaunchTask` asks for nothing at all. croft honours every one
    /// of them perfectly by doing nothing, so naming them in a refusal tells
    /// the user croft cannot do what it is already doing.
    ///
    /// `stopAll` is excluded at EITHER value: it decides whether ending one
    /// session ends the others, and a one-member compound has no others.
    #[test]
    fn a_compound_key_that_requests_nothing_is_not_recorded_as_unsupported() {
        let text = r#"{
            "configurations": [ { "name": "A", "type": "node", "program": "a.js" } ],
            "compounds": [
                { "name": "DefaultStopAll", "configurations": ["A"], "stopAll": false },
                { "name": "TrueStopAll", "configurations": ["A"], "stopAll": true },
                { "name": "NulledTask", "configurations": ["A"], "preLaunchTask": null },
                { "name": "EmptyTask", "configurations": ["A"], "preLaunchTask": "" },
                { "name": "EmptyPresentation", "configurations": ["A"], "presentation": {} },
                { "name": "RealPresentation", "configurations": ["A"], "presentation": { "order": 1 } },
                { "name": "Malformed", "configurations": ["A"], "presentation": 7 }
            ]
        }"#;
        let cs = parse_compounds(text, ".vscode/launch.json");
        assert_eq!(cs.len(), 7, "precondition: every compound parsed");
        let by = |n: &str| {
            cs.iter()
                .find(|c| c.name == n)
                .unwrap_or_else(|| panic!("{n} parsed"))
        };

        assert!(
            by("DefaultStopAll").unsupported_keys.is_empty(),
            "stopAll:false is VS Code's default and cannot change a one-member \
             outcome: {:?}",
            by("DefaultStopAll").unsupported_keys
        );
        assert!(
            by("TrueStopAll").unsupported_keys.is_empty(),
            "nor can stopAll:true — with one session there are no others to \
             stop: {:?}",
            by("TrueStopAll").unsupported_keys
        );
        assert!(
            by("NulledTask").unsupported_keys.is_empty(),
            "a null preLaunchTask asks for nothing: {:?}",
            by("NulledTask").unsupported_keys
        );
        assert!(
            by("EmptyTask").unsupported_keys.is_empty(),
            "nor does an empty one: {:?}",
            by("EmptyTask").unsupported_keys
        );
        assert!(
            by("EmptyPresentation").unsupported_keys.is_empty(),
            "nor an empty presentation object: {:?}",
            by("EmptyPresentation").unsupported_keys
        );

        // The positive control: without it, six empties could equally mean
        // the detection never records anything at all. Every honourable key
        // is honoured now (#318), so the only shapes left to carry the
        // control are the MALFORMED ones - a `presentation` that is not an
        // object is the cheapest.
        assert_eq!(
            by("Malformed").unsupported_keys,
            vec!["presentation"],
            "and a shape croft cannot act on is still recorded"
        );
        assert_eq!(
            by("RealPresentation").unsupported_keys,
            Vec::<&str>::new(),
            "while a well-formed order is honoured rather than refused"
        );
    }

    /// #318: a compound's own `preLaunchTask` is now read and run, so it is no
    /// longer a reason to refuse the launch. The VALUE has to survive parsing
    /// — recording only that the key was present was enough to refuse, and is
    /// not enough to honour it.
    #[test]
    fn a_compounds_pre_launch_task_is_captured_and_no_longer_unsupported() {
        let text = r#"{
            "configurations": [ { "name": "A", "type": "node", "program": "a.js" } ],
            "compounds": [
                { "name": "Builds", "configurations": ["A"], "preLaunchTask": "build" },
                { "name": "Nulled", "configurations": ["A"], "preLaunchTask": null },
                { "name": "Empty", "configurations": ["A"], "preLaunchTask": "" },
                { "name": "Presents", "configurations": ["A"], "presentation": { "order": 1 } }
            ]
        }"#;
        let cs = parse_compounds(text, ".vscode/launch.json");
        let by = |n: &str| {
            cs.iter()
                .find(|c| c.name == n)
                .unwrap_or_else(|| panic!("{n} parsed"))
        };

        assert_eq!(
            by("Builds").pre_launch_task.as_deref(),
            Some("build"),
            "the task's NAME is what running it needs; the key alone cannot"
        );
        assert!(
            by("Builds").unsupported_keys.is_empty(),
            "preLaunchTask is honoured now, so it must stop being a refusal              reason: {:?}",
            by("Builds").unsupported_keys
        );

        // Requesting nothing stays nothing: null and "" must not park a launch
        // behind a task that does not exist.
        assert_eq!(by("Nulled").pre_launch_task, None);
        assert_eq!(by("Empty").pre_launch_task, None);

        // `presentation.order` is HONOURED now (#318), so it must stop being
        // a refusal reason - and it must be read, not merely tolerated.
        assert!(
            by("Presents").unsupported_keys.is_empty(),
            "order is honoured now and must stop refusing: {:?}",
            by("Presents").unsupported_keys
        );
        assert_eq!(
            by("Presents").presentation.as_ref().and_then(|p| p.order),
            Some(1.0),
            "the order's VALUE is what sorting needs; tolerating the key cannot"
        );
        assert_eq!(by("Presents").pre_launch_task, None);
    }

    #[test]
    fn presentation_keys_are_honoured_and_only_unreadable_values_refuse() {
        let text = r#"{
          "compounds": [
            { "name": "Hid",   "configurations": ["A"], "presentation": { "hidden": true } },
            { "name": "Shown", "configurations": ["A"], "presentation": { "hidden": false } },
            { "name": "Grouped", "configurations": ["A"], "presentation": { "group": "g" } },
            { "name": "Ordered", "configurations": ["A"], "presentation": { "order": 2 } },
            { "name": "Both",  "configurations": ["A"],
              "presentation": { "hidden": true, "order": 1 } },
            { "name": "Empty", "configurations": ["A"], "presentation": {} }
          ]
        }"#;
        let cs = parse_compounds(text, "test");
        let by = |n: &str| cs.iter().find(|c| c.name == n).expect("compound present");

        assert!(by("Hid").hidden(), "hidden: true asks not to be listed");
        assert!(
            !by("Shown").hidden(),
            "hidden: false is the default, spelled out"
        );
        assert!(
            !by("Empty").hidden(),
            "an empty presentation asks for nothing"
        );

        // A compound asking ONLY to be hidden is fully served, so it must not
        // be refused for a capability it never requested.
        assert!(
            by("Hid").unsupported_keys.is_empty(),
            "hidden alone is honoured, so nothing is unsupported: {:?}",
            by("Hid").unsupported_keys
        );
        assert!(
            by("Empty").unsupported_keys.is_empty(),
            "an empty presentation refuses nothing"
        );

        // `group` and `order` are honoured now (#318): read, not refused.
        assert!(
            by("Grouped").unsupported_keys.is_empty(),
            "group no longer refuses: {:?}",
            by("Grouped").unsupported_keys
        );
        assert_eq!(
            by("Grouped")
                .presentation
                .as_ref()
                .and_then(|p| p.group.clone()),
            Some(String::from("g")),
            "and its VALUE is what places the row"
        );
        assert!(by("Ordered").unsupported_keys.is_empty());
        assert_eq!(
            by("Ordered").presentation.as_ref().and_then(|p| p.order),
            Some(2.0)
        );
        // A malformed shape must keep refusing. On main these refused and the
        // user found out; silently launching a compound whose typo'd
        // `{"hidden": "true"}` did nothing would be a regression dressed as
        // a feature.
        let bad = parse_compounds(
            r#"{
              "compounds": [
                { "name": "QuotedBool", "configurations": ["A"],
                  "presentation": { "hidden": "true" } },
                { "name": "NotAnObject", "configurations": ["A"],
                  "presentation": "grouped" }
              ]
            }"#,
            "test",
        );
        let bad_by = |n: &str| bad.iter().find(|c| c.name == n).expect("present");
        assert!(
            !bad_by("QuotedBool").hidden(),
            "a quoted bool is not a bool"
        );
        assert_eq!(
            bad_by("QuotedBool").unsupported_keys,
            vec!["presentation.hidden"],
            "and it refuses rather than launching unhidden in silence"
        );
        assert_eq!(
            bad_by("NotAnObject").unsupported_keys,
            vec!["presentation"],
            "a non-object presentation refuses under its own name"
        );

        assert!(by("Both").hidden(), "Both asks to be hidden");
        assert!(
            by("Both").unsupported_keys.is_empty(),
            "and both halves are honoured now, so nothing refuses: {:?}",
            by("Both").unsupported_keys
        );
    }

    /// A value croft cannot READ is a typo, whichever key carries it (#318).
    /// `{"order": "1"}` is the same mistake as `{"hidden": "true"}`, and
    /// dropping it silently would leave a picker that ignores the ordering the
    /// user wrote with nothing to explain why.
    #[test]
    fn a_malformed_presentation_value_refuses_whichever_key_it_is_on() {
        let cs = parse_compounds(
            r#"{
              "compounds": [
                { "name": "QuotedOrder", "configurations": ["A"],
                  "presentation": { "order": "1" } },
                { "name": "NumberGroup", "configurations": ["A"],
                  "presentation": { "group": 7 } },
                { "name": "FractionalOrder", "configurations": ["A"],
                  "presentation": { "order": 1.5 } },
                { "name": "NulledKeys", "configurations": ["A"],
                  "presentation": { "group": null, "order": null } }
              ]
            }"#,
            ".vscode/launch.json",
        );
        assert_eq!(cs.len(), 4, "precondition: every compound parsed");
        let by = |n: &str| {
            cs.iter()
                .find(|c| c.name == n)
                .unwrap_or_else(|| panic!("{n} parsed"))
        };
        assert_eq!(
            by("QuotedOrder").unsupported_keys,
            vec!["presentation.order"]
        );
        assert_eq!(
            by("NumberGroup").unsupported_keys,
            vec!["presentation.group"]
        );
        // A FRACTION is not a typo: VS Code's schema says `number` and its
        // comparator subtracts, so 1.5 is a legal position between two
        // neighbours and must be honoured rather than refused.
        assert!(
            by("FractionalOrder").unsupported_keys.is_empty(),
            "a fractional order is a position, not a mistake: {:?}",
            by("FractionalOrder").unsupported_keys
        );
        assert_eq!(
            by("FractionalOrder")
                .presentation
                .as_ref()
                .and_then(|p| p.order),
            Some(1.5)
        );
        // Explicit nulls ask for nothing, which croft delivers by doing
        // nothing - naming them would report a limitation that is not one.
        assert!(
            by("NulledKeys").unsupported_keys.is_empty(),
            "null asks for nothing: {:?}",
            by("NulledKeys").unsupported_keys
        );
    }

    /// #318: the picker's order is VS Code's `getVisibleAndSorted`, which is a
    /// transcription and not a guess. Each arm below is a rule croft would
    /// plausibly have got wrong on its own.
    #[test]
    fn presentation_sorts_the_picker_the_way_vs_code_does() {
        fn p(group: Option<&str>, order: Option<f64>) -> Option<Presentation> {
            Some(Presentation {
                hidden: false,
                group: group.map(str::to_string),
                order,
            })
        }
        let items: Vec<(&str, Option<Presentation>)> = vec![
            ("plain-first", None),
            ("b-group", p(Some("b"), None)),
            ("no-group-ord-2", p(None, Some(2.0))),
            (
                "hidden",
                Some(Presentation {
                    hidden: true,
                    group: None,
                    order: None,
                }),
            ),
            ("a-group-ord-9", p(Some("a"), Some(9.0))),
            ("plain-second", None),
            ("a-group-ord-1", p(Some("a"), Some(1.0))),
            ("a-group-no-ord", p(Some("a"), None)),
            ("no-group-ord-1", p(None, Some(1.0))),
        ];
        let sorted: Vec<&str> = visible_and_sorted(items, |(_, p)| p.as_ref())
            .into_iter()
            .map(|(n, _)| n)
            .collect();
        assert_eq!(
            sorted,
            vec![
                // grouped first, groups by name, order ascending within one,
                // and a missing order last inside its group
                "a-group-ord-1",
                "a-group-ord-9",
                "a-group-no-ord",
                "b-group",
                // a presentation WITHOUT a group still beats no presentation
                "no-group-ord-1",
                "no-group-ord-2",
                // and entries that asked for nothing keep their file order
                "plain-first",
                "plain-second",
            ],
            "hidden is dropped, and every other rule is VS Code's"
        );
    }

    /// An empty `presentation` is still a `presentation`, and VS Code places
    /// it accordingly: its comparator tests the OBJECT for truthiness, so
    /// `{}` sorts ahead of an entry carrying no block at all. Reading it as
    /// "no preference" would put those rows somewhere VS Code does not.
    #[test]
    fn an_empty_presentation_block_still_outranks_no_block() {
        let cfgs = parse_launch_json(
            r#"{ "configurations": [
                { "name": "Bare", "type": "node", "program": "a.js" },
                { "name": "EmptyBlock", "type": "node", "program": "b.js",
                  "presentation": {} },
                { "name": "OnlyShown", "type": "node", "program": "c.js",
                  "presentation": { "hidden": false } }
            ] }"#,
            ".vscode/launch.json",
        );
        let by = |n: &str| {
            cfgs.iter()
                .find(|c| c.name == n)
                .unwrap_or_else(|| panic!("{n} parsed"))
                .clone()
        };
        assert_eq!(by("Bare").presentation, None, "no block is no block");
        assert_eq!(
            by("EmptyBlock").presentation,
            Some(Presentation::default()),
            "an empty block asks for nothing but is still declared"
        );
        assert_eq!(by("OnlyShown").presentation, Some(Presentation::default()));

        let sorted: Vec<String> = visible_and_sorted(cfgs, |c| c.presentation.as_ref())
            .into_iter()
            .map(|c| c.name)
            .collect();
        assert_eq!(
            sorted,
            vec!["EmptyBlock", "OnlyShown", "Bare"],
            "both declared blocks sort ahead of the bare entry, in file order"
        );
    }

    /// A key that REQUESTS NOTHING is honoured by doing nothing, so it must
    /// not be named in a refusal - that would report a limitation croft does
    /// not have. `false` and `""` are that shape, and both used to launch
    /// before `presentation` gained its own reader.
    #[test]
    fn a_presentation_that_requests_nothing_is_not_a_refusal() {
        let cs = parse_compounds(
            r#"{
              "compounds": [
                { "name": "FalseBlock", "configurations": ["A"], "presentation": false },
                { "name": "EmptyString", "configurations": ["A"], "presentation": "" },
                { "name": "NulledBlock", "configurations": ["A"], "presentation": null },
                { "name": "Truthy", "configurations": ["A"], "presentation": true }
              ]
            }"#,
            ".vscode/launch.json",
        );
        assert_eq!(cs.len(), 4, "precondition: every compound parsed");
        let by = |n: &str| {
            cs.iter()
                .find(|c| c.name == n)
                .unwrap_or_else(|| panic!("{n} parsed"))
        };
        for name in ["FalseBlock", "EmptyString", "NulledBlock"] {
            assert!(
                by(name).unsupported_keys.is_empty(),
                "{name} asks for nothing and must launch: {:?}",
                by(name).unsupported_keys
            );
        }
        // The control: a value that DOES claim to say something, and is still
        // unreadable, must refuse - or the three above prove only that this
        // function never records anything.
        assert_eq!(
            by("Truthy").unsupported_keys,
            vec!["presentation"],
            "a non-object that asks for something is unreadable"
        );
    }

    /// The property that must not break: a launch.json that says nothing
    /// about presentation is left exactly as written.
    #[test]
    fn a_workspace_with_no_presentation_keeps_its_file_order() {
        let items: Vec<(&str, Option<Presentation>)> = vec![("z", None), ("a", None), ("m", None)];
        let sorted: Vec<&str> = visible_and_sorted(items, |(_, p)| p.as_ref())
            .into_iter()
            .map(|(n, _)| n)
            .collect();
        assert_eq!(
            sorted,
            vec!["z", "a", "m"],
            "sorting must be stable, or introducing the feature would silently \
             reorder every existing workspace's picker"
        );
    }

    /// A configuration carries `presentation` too, and sorts against
    /// compounds in one list - VS Code puts both kinds through the same
    /// comparator, so a config and a compound naming one group belong
    /// together.
    #[test]
    fn a_configuration_reads_presentation_like_a_compound_does() {
        let cfgs = parse_launch_json(
            r#"{ "configurations": [
                { "name": "Plain", "type": "node", "program": "a.js" },
                { "name": "Grouped", "type": "node", "program": "b.js",
                  "presentation": { "group": "servers", "order": 3 } },
                { "name": "Hid", "type": "node", "program": "c.js",
                  "presentation": { "hidden": true } }
            ] }"#,
            ".vscode/launch.json",
        );
        let by = |n: &str| {
            cfgs.iter()
                .find(|c| c.name == n)
                .unwrap_or_else(|| panic!("{n} parsed"))
                .clone()
        };
        assert_eq!(by("Plain").presentation, None, "no block asks for nothing");
        assert_eq!(
            by("Grouped").presentation,
            Some(Presentation {
                hidden: false,
                group: Some(String::from("servers")),
                order: Some(3.0),
            })
        );
        assert!(by("Hid").presentation.is_some_and(|p| p.hidden));
    }

    /// A compound resolves to its members in the order written, so the picker
    /// and the launch sequence agree with the file.
    #[test]
    fn a_resolved_compound_yields_its_members_in_declaration_order() {
        let text = r#"{
            "configurations": [
                { "name": "Client", "type": "node", "program": "c.js" },
                { "name": "Server", "type": "node", "program": "s.js" }
            ],
            "compounds": [ { "name": "Both", "configurations": ["Server", "Client"] } ]
        }"#;
        let cfgs = parse_launch_json(text, ".vscode/launch.json");
        let compounds = parse_compounds(text, ".vscode/launch.json");
        let members = resolve_compound(&compounds[0], &cfgs).unwrap();
        assert_eq!(
            members.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
            vec!["Server", "Client"],
            "compound order wins over the order in `configurations`"
        );
    }
}