cursor-setup-system 0.0.84

Install, update, back up, restore and remove complete Cursor CLI configurations. Built by NDDev.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
//! The local setup catalog: complete harness states, on disk, beside the binary.
//!
//! A setup here is the whole thing — the system-prompt components and the
//! configuration together, as a verbatim tree. That is what makes selecting one
//! and restoring one mean the same kind of thing: both put a known complete
//! state into the target, rather than adjusting part of it and leaving the rest
//! wherever the last change left it.
//!
//! ```text
//! setups/
//!   <setup-id>/
//!     setup.json    posture id, description, and optional corpus identity
//!     home/         copied verbatim into the target
//! ```
//!
//! This is one of the three sources the design admits. The other two — a setup
//! compiled by ai-stp, and a set of ai-stp components — arrive as a
//! `HarnessBundle` over the wire. All three converge on the same immutable
//! definition before any plan is made, so nothing downstream needs to know which
//! one produced it.

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

use serde::{Deserialize, Serialize};
use crate::setup_core::digest;

use crate::harness_runtime::facts::Harness;
use crate::provider_v3::{Error, Result, WireReason};

/// The catalog directory name beside the executable or repository root.
pub const CATALOG_DIRECTORY: &str = "setups";

/// The per-setup manifest file.
pub const SETUP_MANIFEST: &str = "setup.json";

/// The subdirectory copied verbatim into a target.
pub const SETUP_PAYLOAD: &str = "home";

/// The schema this build writes and is willing to read.
pub const SETUP_SCHEMA: u32 = 1;

/// What one setup says about itself.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SetupManifest {
    /// Schema of this manifest.
    pub schema_version: u32,
    /// The setup identity, matching its directory name.
    pub id: String,
    /// One line on what this setup is for.
    pub description: String,
    /// The vendor pages that decided the format of what this setup writes.
    ///
    /// A setup's payload is *content in the product's own language*: a TOML
    /// table the product reads, a JSON key it looks for. Getting the surface
    /// right and then writing the wrong key into it produces a target that
    /// looks configured and is not — the same failure as owning a path nothing
    /// reads, one level down.
    ///
    /// Measured 2026-08-27, two of the seven were exactly that. opencode's
    /// `permission` took a bare string where the product documents an object,
    /// and antigravity's file set `toolPermissions` where the product reads
    /// `toolPermission` with a closed set of four values that does not include
    /// the one we wrote. Both were valid JSON, both installed cleanly, and
    /// neither changed anything about the product.
    ///
    /// Empty for a setup that writes only documents — a `CLAUDE.md` has no
    /// schema to get wrong. [`unsourced`] holds the rest.
    #[serde(default)]
    pub sources: Vec<String>,
    /// Corpus setup id, when this catalog vendors first-party identity (`ADR-0156`).
    ///
    /// Distinct from [`Self::id`], which is the posture directory name
    /// (`full-auto`). Absent on a catalog that is only id and description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub setup_stable_id: Option<String>,
    /// Corpus setup version, when vendored. Inventing one here is forbidden.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub setup_version: Option<String>,
    /// Digest of the corpus setup passport, when vendored.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub setup_passport_digest: Option<String>,
    /// Corpus component identities, when vendored. Empty is a catalog without them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub component_refs: Vec<CatalogComponentRef>,
}

/// One component identity a catalog may vendor without minting ids.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogComponentRef {
    /// The component's sealed stable id.
    pub stable_id: String,
    /// The component's sealed version.
    pub version: String,
    /// Digest of the component passport.
    pub passport_digest: String,
    /// The adaptation this catalog ships for the harness.
    pub adaptation_id: String,
}

/// The setups every harness offers, whatever else it also offers.
///
/// Three postures, and a caller who learns them on one product knows them on
/// all seven. That symmetry is the point of the set being named rather than
/// per-harness: `minimal` means the same thing to someone moving from codex to
/// pi as it did before they moved.
///
/// A harness may carry more -- each of the seven also ships an `nddev-builder`
/// toolkit -- but never fewer.
pub const UNIVERSAL_SETUPS: &[&str] = &["baseline", "full-auto", "minimal"];

/// Every universal setup this catalog does not offer, and every one that is
/// indistinguishable from another.
///
/// The second half matters as much as the first. `full-auto` that installs
/// what `baseline` installs is a posture in name only, and it would read as
/// offered.
#[must_use]
pub fn asymmetric(setups: &[Setup]) -> Vec<String> {
    let mut found = Vec::new();
    for required in UNIVERSAL_SETUPS {
        if !setups.iter().any(|setup| setup.manifest.id == *required) {
            found.push(format!("this harness offers no {required} setup"));
        }
    }
    for (index, setup) in setups.iter().enumerate() {
        for other in &setups[index + 1..] {
            if setup.definition_digest == other.definition_digest {
                found.push(format!(
                    "{} and {} are the same bytes, so one of them is a posture in name only",
                    setup.manifest.id, other.manifest.id
                ));
            }
        }
    }
    found
}

/// The programs that came before this one, by the names their files carry.
///
/// A **closed historical set**: the frozen estate is frozen, so this list can
/// only shrink. That is what makes a denylist honest here — elsewhere in this
/// repository an allowlist is used precisely because the other set can grow.
const FROZEN_ESTATE: &[&str] = &[
    "nddev_claude_cli",
    "nddev_codex_cli",
    "nddev_cursor_cli",
    "nddev_grok_cli",
    "nddev_opencode_cli",
    "nddev_pi_cli",
    "nddev-antigravity-cli-app",
    "nddev-claude-app",
    "nddev-codex-app",
    "nddev-cursor-cli-app",
    "nddev-grok-build-app",
    "nddev-opencode-app",
    "nddev-pi-app",
    "nddev-harnesses",
    "rldyour-ai-cli-tools",
];

/// Every shipped instruction that names something this program is not.
///
/// Setups carry documents an agent reads and acts on — a skill, a rule, a
/// command file. Those documents are content like any other, and nothing was
/// checking them, so one of them told an agent to run
/// `software-status --target <dir> --json` and `list --json` for six releases.
/// Both are refused by the binary; the second says so in those words.
///
/// Two things are refused here:
///
/// * **A frozen-estate name.** The program that came before this one had
///   different commands and a different model, and a document naming it is
///   describing something a reader cannot run.
/// * **An invocation this binary would not parse.** Any line naming the
///   provider followed by a verb is checked against [`crate::harness_runtime::human::VERBS`],
///   which is the list `into_command` itself accepts.
///
/// What it deliberately does not do is judge English. `install` in a sentence
/// is a word; `cursor-setup-system install` is an instruction, and only the
/// second is checked.
#[must_use]
pub fn misdirecting(provider_id: &str, setups: &[Setup]) -> Vec<String> {
    let mut found = Vec::new();
    for setup in setups {
        for (relative, path) in files_by_path(&setup.payload) {
            let Ok(text) = std::fs::read_to_string(&path) else {
                continue;
            };
            let where_it_is = format!("{}/{relative}", setup.manifest.id);
            for name in FROZEN_ESTATE {
                if text.contains(name) {
                    found.push(format!(
                        "{where_it_is} names {name}, which is the program that came before \
                         this one and answers none of its commands"
                    ));
                }
            }
            for line in text.lines() {
                // Only an *invocation*, never prose. The provider must open the
                // line or follow a backtick or a shell prompt; "checking
                // cursor-setup-system behaviour" is a sentence, and an earlier
                // version of this check called it an instruction.
                let Some(at) = line.find(provider_id) else {
                    continue;
                };
                let before = line[..at].trim_end_matches(' ');
                let invoked = before.is_empty()
                    || before.ends_with('`')
                    || before.ends_with('$')
                    || before.ends_with('>');
                if !invoked {
                    continue;
                }
                let rest = &line[at + provider_id.len()..];
                let Some(verb) = rest.split_whitespace().next() else {
                    continue;
                };
                let verb = verb.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-');
                if verb.is_empty() || verb.starts_with('-') {
                    continue;
                }
                // Both surfaces, because the binary answers both. The first
                // version knew only `human::VERBS` and so called
                // `provider-info` refused -- a wire command this build answers
                // on demand, and one a toolkit has every reason to document.
                // A guard that names a working command as refused is the same
                // false statement it exists to catch, one level up.
                let human = crate::harness_runtime::human::VERBS.contains(&verb);
                let wire = crate::provider_v3::vocabulary::Command::parse(verb).is_some();
                if !human && !wire && !provider_id.contains(verb) {
                    found.push(format!(
                        "{where_it_is} tells a reader to run `{provider_id} {verb}`, \
                         which this binary answers on neither its human nor its wire surface"
                    ));
                }
            }
        }
    }
    found.sort();
    found.dedup();
    found
}

/// Every regular file under a payload, with its relative path and full path.
fn files_by_path(root: &std::path::Path) -> Vec<(String, std::path::PathBuf)> {
    let mut found = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(directory) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&directory) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if let Ok(relative) = path.strip_prefix(root) {
                found.push((
                    relative
                        .components()
                        .map(|part| part.as_os_str().to_string_lossy().into_owned())
                        .collect::<Vec<_>>()
                        .join("/"),
                    path,
                ));
            }
        }
    }
    found
}

/// Every regular file under a payload, as slash-separated relative paths.
fn files_under(root: &std::path::Path) -> Vec<String> {
    let mut found = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(directory) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&directory) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if let Ok(relative) = path.strip_prefix(root) {
                found.push(
                    relative
                        .components()
                        .map(|part| part.as_os_str().to_string_lossy().into_owned())
                        .collect::<Vec<_>>()
                        .join("/"),
                );
            }
        }
    }
    found
}

/// What [`undescribed`] found, and how many things it looked at.
///
/// The count is here because `assert!(problems.is_empty())` cannot tell a clean
/// tree from an empty walk, and one of the seven harnesses genuinely has
/// nothing for this guard to examine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Examined {
    /// One line per entry point that cannot describe itself.
    pub problems: Vec<String>,
    /// How many entry points the walk actually reached.
    pub entry_points: usize,
}

/// A component entry point that carries no frontmatter, or none the product
/// reads.
///
/// [`unsourced`] exempts documents on the ground that *prose has no keys to
/// spell wrong*. An entry point is not prose: its `description` is what the
/// model reads to decide whether to invoke the thing at all. A `SKILL.md` that
/// lost its frontmatter installs, verifies and restores cleanly, and the
/// product names it after its directory and gives the model nothing to choose
/// on -- the same shape as a correct key under a wrong name, one level up.
///
/// **Which files are entry points is measured, not assumed**, and the negative
/// half is the part that took the measuring:
///
/// * `SKILL.md`, and a file directly under `agents/`, are entry points. Cursor's
///   own generator writes `{name, description}` for exactly these. A codex
///   `agents/<name>.toml` is the same obligation in TOML: the product refuses
///   the file by name when `name` or `description` is absent, so the check
///   reads the keys instead of frontmatter.
/// * A file under `references/` is **not** -- it is a document a skill links to,
///   and requiring frontmatter there would be inventing a rule.
/// * A file under `commands/` is **not**. Cursor's loader builds
///   `{id, name: filename.replace(".md",""), path, scope}`: the name comes from
///   the filename and no frontmatter is read. Requiring it would be a rule the
///   product does not have.
///
/// **It reports how many entry points it looked at, and that is not decoration.**
/// `assert!(problems.is_empty())` is green when the walk found nothing, and
/// codex's own test docstring says outright that it finds nothing there. So six
/// harnesses were asserting a guard whose subject count nobody stated, and a
/// layout change that removed every entry point would have left all seven green.
///
/// A filter that selects nothing produces output identical to a filter that
/// selects correctly. The only thing that tells them apart is asking how many
/// it matched -- and that is a number nobody prints. Returning it forces each
/// caller to state the number its own tree carries, including the harness whose
/// number is zero.
#[must_use]
pub fn undescribed(setups: &[Setup]) -> Examined {
    let mut found = Vec::new();
    let mut entry_points = 0_usize;
    for setup in setups {
        for name in files_under(&setup.payload) {
            if !is_entry_point(&name) {
                continue;
            }
            entry_points += 1;
            let Ok(text) = std::fs::read_to_string(setup.payload.join(&name)) else {
                found.push(format!("{} cannot read {name:?}", setup.manifest.id));
                continue;
            };
            let named = if std::path::Path::new(&name)
                .extension()
                .is_some_and(|extension| extension.eq_ignore_ascii_case("toml"))
            {
                toml_names
            } else {
                frontmatter_names
            };
            for key in ["name", "description"] {
                if !named(&text, key) {
                    found.push(format!(
                        "{} ships {name:?} with no `{key}` the product reads, and a component \
                         the product cannot describe is one the model cannot choose",
                        setup.manifest.id
                    ));
                }
            }
        }
        // A plugin manifest is the same obligation in a different file format,
        // and it escaped this check entirely until `skills` began routing two
        // kinds: before that every entry under a skills directory was a skill,
        // so every entry had a `SKILL.md` and every one was read. A plugin has
        // no frontmatter and was therefore no entry point, and a component with
        // nothing to describe it is what this function exists to refuse.
        for name in files_under(&setup.payload) {
            if !is_a_plugin_manifest(&name) {
                continue;
            }
            let Ok(text) = std::fs::read_to_string(setup.payload.join(&name)) else {
                found.push(format!("{} cannot read {name:?}", setup.manifest.id));
                continue;
            };
            let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&text) else {
                found.push(format!(
                    "{} ships {name:?} and it is not JSON",
                    setup.manifest.id
                ));
                continue;
            };
            for key in ["name", "description"] {
                let named = manifest
                    .get(key)
                    .and_then(serde_json::Value::as_str)
                    .is_some_and(|value| !value.trim().is_empty());
                if !named {
                    found.push(format!(
                        "{} ships {name:?} with no `{key}`, and a component the product \
                         cannot describe is one the model cannot choose",
                        setup.manifest.id
                    ));
                }
            }
        }
    }
    Examined {
        problems: found,
        entry_points,
    }
}

/// Whether a path is a plugin manifest, in the two shapes that have one.
///
/// The same two arms as [`is_a_plugin_root`], reading a file rather than
/// deciding about its directory: `<name>/plugin.json` for Antigravity and Grok,
/// and `<name>/.<vendor>-plugin/plugin.json` for Claude Code, Cursor and Codex.
/// Matched on the suffix so a fifth vendor works rather than being a silent
/// miss.
///
/// **Two of the six that declare `plugin` have no manifest at all, and saying
/// "the rest" was wrong.** An OpenCode plugin is a JavaScript or TypeScript
/// module — `plugins/<name>.js`, one file exporting functions — and a Pi
/// extension is a package. Neither carries `name` or `description` for a
/// product to read, so there is nothing here to check and no arm to add: a
/// module's identity is its filename and its behaviour is its exports.
///
/// That is a real difference rather than a gap, and it is written down because
/// the first version of this comment claimed the manifest shapes covered every
/// product. They cover four of seven. No setup in this repository ships a
/// plugin for OpenCode, Grok or Pi today — only documentation about authoring
/// one — so nothing has ever tested the claim, which is why it survived being
/// written.
fn is_a_plugin_manifest(relative: &str) -> bool {
    let parts: Vec<&str> = relative.split('/').collect();
    let vendor_prefixed = matches!(
        parts.as_slice(),
        [.., directory, "plugin.json"]
            if directory.starts_with('.') && directory.ends_with("-plugin")
    );
    vendor_prefixed || parts.last().is_some_and(|leaf| *leaf == "plugin.json")
}

/// A shipped instruction naming a sibling file the setup does not carry.
///
/// A skill's routing table sends a reader to `references/surfaces.md`; an agent
/// names the document beside it. If the setup does not ship that file, the
/// instruction sends the reader nowhere -- and the reader is a model, which
/// will not say so.
///
/// **Written because this repository's generator did it.** The agent template
/// pointed every harness at `references/surfaces.md`, and codex ships no skill
/// at all -- its `skill` kind routes only under `target_scope: user_root`, so a
/// setup aimed at its own home carries no `references/` directory. The
/// instruction was correct for six harnesses and false for the seventh, which
/// is the shape this estate keeps finding: a statement true of the thing
/// measured and false of the thing declared.
///
/// Only **relative** paths with a document extension are checked, and only
/// inside a backtick. A URL is somebody else's to serve, an absolute path is
/// not this setup's to carry, and prose that happens to contain a slash is not
/// an instruction -- the same distinction [`misdirecting`] draws for commands,
/// and for the same reason.
#[must_use]
pub fn dangling_references(setups: &[Setup]) -> Vec<String> {
    let mut found = Vec::new();
    for setup in setups {
        let files = files_under(&setup.payload);
        for (relative, path) in files_by_path(&setup.payload) {
            let Ok(text) = std::fs::read_to_string(&path) else {
                continue;
            };
            let here = relative.rsplit_once('/').map_or("", |(dir, _)| dir);
            for quoted in text.split('`').skip(1).step_by(2) {
                let named = quoted.trim();
                // **Only documents, and that scope was measured rather than
                // assumed.**
                //
                // Cursor's hand-written toolkit named two files that exist
                // nowhere in this estate -- `config/nddev-contract.json` and
                // `build/manifest.json`, inherited from the program this one
                // replaced -- and this guard did not see them because they are
                // not `.md`. The obvious repair is to check every extension.
                //
                // Measured before writing it: across all 28 setups that rule
                // flags **119** backticked paths, of which **117 are correct**.
                // Prose here legitimately names repository paths a reader is
                // told to open (`references/<harness>-baseline.json`) and
                // product paths a setup deliberately does not ship
                // (`config/hooks.json`, `plugins/installed_plugins.json`,
                // `antigravity-cli/keybindings.json`). A guard with that ratio
                // is one people learn to ignore.
                //
                // The trap inside the trap: two of the 119 are the *corrective*
                // page, which quotes both dead paths in order to say they are
                // dead. The extended guard would refuse the sentence that
                // documents the removal.
                //
                // A document is different because a document named in prose is
                // a file a reader is told to *open*, and the setup either ships
                // it or the instruction goes nowhere. `.json` has no such
                // property. The two dead paths were found by reading, and this
                // note exists so the next author reaches for measurement rather
                // than for the tidier rule.
                let is_document = std::path::Path::new(named)
                    .extension()
                    .and_then(std::ffi::OsStr::to_str)
                    .is_some_and(|e| e.eq_ignore_ascii_case("md"));
                if !is_document || !named.contains('/') || named.starts_with('/') {
                    continue;
                }
                if named.contains("://") || named.contains(' ') {
                    continue;
                }
                // Describing where a product reads is not naming a file to
                // open, and the difference is visible in the path itself. A
                // glob or a placeholder names a *class* of file; a `~`-rooted
                // path is outside this setup; a leading dot-directory is the
                // product's own home, not a document shipped here.
                //
                // Cursor's references are full of all three -- `~/.cursor/
                // skills/<skill>/SKILL.md`, `<plugin>/agents/*.md`,
                // `.cursor/rules/*.mdc` -- and the first version of this guard
                // called every one of them a dangling reference. That is the
                // same distinction `misdirecting` draws between an invocation
                // and prose, applied to paths instead of verbs.
                if named.contains('*')
                    || named.contains('<')
                    || named.contains('>')
                    // Braces are a placeholder too, and this list was one
                    // vendor's convention short. Antigravity writes its path
                    // templates as `{workspace}/.agents/skills/{skill_name}/
                    // SKILL.md`, quoted verbatim from the product's own bytes
                    // into a generated reference -- a *class* of file exactly as
                    // `<name>` is, and refused here because the spelling
                    // differed. Rewording the citation would have been the
                    // wrong repair: it is the product's string, and a quotation
                    // that has been tidied is no longer evidence.
                    || named.contains('{')
                    || named.contains('}')
                    || named.starts_with('~')
                    || named.starts_with('.')
                {
                    continue;
                }
                // An environment variable as the first segment is a root this
                // setup does not contain: `CURSOR_CONFIG_DIR/AGENTS.md` says
                // where a product looks, not what is shipped here.
                let root = named.split('/').next().unwrap_or_default();
                if !root.is_empty()
                    && root
                        .chars()
                        .all(|c| c.is_ascii_uppercase() || c == '_' || c.is_ascii_digit())
                {
                    continue;
                }
                // Matched as a **suffix**, anywhere in the setup, and the
                // weakness is deliberate.
                //
                // A relative reference does not resolve the same way in every
                // product: antigravity's plugin rule names
                // `skills/antigravity-surfaces/SKILL.md` relative to the
                // *plugin root*, while a skill's own routing table names
                // `references/surfaces.md` relative to itself. A guard that
                // picked one convention would call the other broken -- it did,
                // on the first run, and the file it named was shipped.
                //
                // So this asks the question it can answer without guessing a
                // convention: **is this document in the setup at all?** That
                // catches the defect the guard exists for -- an instruction
                // naming a file nothing ships -- and stays silent about where
                // a product resolves from, which is not this build's to assert.
                let _ = here;
                if !files
                    .iter()
                    .any(|f| f == named || f.ends_with(&format!("/{named}")))
                {
                    found.push(format!(
                        "{} ships {relative:?}, which sends a reader to {named:?}, and this \
                         setup carries no such file",
                        setup.manifest.id
                    ));
                }
            }
        }
    }
    found.sort();
    found.dedup();
    found
}

/// Whether a directory is a plugin root rather than a skill.
///
/// **The products that use a manifest discriminate by it, not by location.**
/// Claude Code: *"Any folder under a skills directory that contains a
/// `.claude-plugin/plugin.json` manifest is loaded as a plugin named
/// `<name>@skills-dir`"* — the same directory holds both kinds and the manifest
/// says which. Cursor and Codex carry the same shape under their own vendor
/// prefix; Antigravity and Grok put `plugin.json` at the plugin root.
///
/// OpenCode and Pi are not directories with manifests — a module file and a
/// package — so this answers `false` for them and correctly: neither can hold a
/// `references/` directory that a walk would then demand a `SKILL.md` beside.
/// See [`is_a_plugin_manifest`] for the same distinction on the file.
///
/// Written because [`unreachable_references`] was one directory, one kind. It
/// reported a plugin folder as a skill that had lost its `SKILL.md`, which is
/// the mirror of a misclassification the consumer session found in its own
/// discovery walk on the same afternoon — both from the same cause, a walk
/// written when the surface routed a single kind.
fn is_a_plugin_root(files: &[String], owner: &str) -> bool {
    files.iter().any(|name| {
        let Some(rest) = name.strip_prefix(&format!("{owner}/")) else {
            return false;
        };
        match rest.split('/').collect::<Vec<_>>().as_slice() {
            // Antigravity's shape: the manifest at the plugin root.
            ["plugin.json"] => true,
            // The vendor-prefixed shape: `.claude-plugin/`, `.cursor-plugin/`,
            // `.codex-plugin/`. Matched on the suffix rather than a list, so a
            // vendor this estate has not met yet is not a silent miss.
            [directory, "plugin.json"] => {
                directory.starts_with('.') && directory.ends_with("-plugin")
            }
            _ => false,
        }
    })
}

/// Anything inside a skill that neither its entry point nor a page it routes to
/// names.
///
/// **Written after the same sweep produced two findings in one hour**, both
/// invisible to every guard here:
///
/// * a 192-line executable validator shipped into people's homes, named by no
///   skill, no command and no guard, and wrong in three ways because nothing
///   had asked it anything since the layout moved under it;
/// * eleven authoring pages -- the configuration file and the instruction file,
///   the two a setup spends most of its bytes on -- written into four harnesses
///   and routed to from none of them.
///
/// The estate had one direction of the reference question. `dangling_references`
/// asks whether a *named* file exists; `unreachable_references` asks whether a
/// `references/` **directory** has an entry point above it. Neither asks whether
/// an *existing* file is named, per file, and neither looks outside
/// `references/` -- which is why a `scripts/` directory could hold an orphan for
/// as long as it liked.
///
/// One hop, deliberately. A skill routes to its references and a reference may
/// route on; a chain longer than that is a document nobody was going to follow
/// anyway, and demanding transitive reachability would turn a real rule into a
/// graph problem with arbitrary depth.
///
/// It reports its subject count for the reason [`undescribed`] does: one of the
/// seven ships no skill at all, so an emptiness assertion there is green over
/// nothing.
#[must_use]
pub fn stranded(setups: &[Setup]) -> Examined {
    let mut found = Vec::new();
    let mut entry_points = 0_usize;
    for setup in setups {
        for (relative, path) in files_by_path(&setup.payload) {
            if !relative.ends_with("SKILL.md") {
                continue;
            }
            let Some(directory) = path.parent() else {
                continue;
            };
            let Ok(entry) = std::fs::read_to_string(&path) else {
                continue;
            };
            let carried: Vec<(String, std::path::PathBuf)> = files_by_path(directory)
                .into_iter()
                .filter(|(name, _)| name != "SKILL.md")
                .collect();
            let named_by = |text: &str, name: &str| {
                text.contains(name)
                    || std::path::Path::new(name)
                        .file_name()
                        .and_then(std::ffi::OsStr::to_str)
                        .is_some_and(|leaf| text.contains(leaf))
            };
            let mut hop = String::new();
            for (name, at) in &carried {
                if named_by(&entry, name)
                    && let Ok(text) = std::fs::read_to_string(at)
                {
                    hop.push_str(&text);
                }
            }
            for (name, _) in &carried {
                entry_points += 1;
                if named_by(&entry, name) || named_by(&hop, name) {
                    continue;
                }
                found.push(format!(
                    "{} ships {name:?} inside a skill, and neither its SKILL.md nor \
                     anything that routes from it names the file",
                    setup.manifest.id
                ));
            }
        }
    }
    found.sort();
    found.dedup();
    Examined {
        problems: found,
        entry_points,
    }
}

/// A `references/` directory no entry point reaches.
///
/// [`undescribed`] requires an entry point to describe itself; this requires
/// the supporting documents to have one. A `skills/x/references/*.md` with no
/// `skills/x/SKILL.md` beside it is prose nothing routes to -- installed,
/// backed up, restored, and read by nobody.
///
/// **Written because a generator in this repository produced exactly that.**
/// It wrote three references into a `skills/nddev-builder/` directory of a
/// harness whose skill is called something else, and every other guard passed: the files are documents, so
/// `unsourced` exempts them; there is no `SKILL.md`, so `undescribed` has
/// nothing to check. The absence was invisible precisely because the thing that
/// would have been checked was the thing missing.
#[must_use]
pub fn unreachable_references(setups: &[Setup]) -> Vec<String> {
    let mut found = Vec::new();
    for setup in setups {
        let files = files_under(&setup.payload);
        for name in &files {
            let parts: Vec<&str> = name.split('/').collect();
            let Some(at) = parts.iter().position(|part| *part == "references") else {
                continue;
            };
            if at == 0 {
                continue;
            }
            let owner = parts[..at].join("/");
            if is_a_plugin_root(&files, &owner) {
                continue;
            }
            let entry = format!("{owner}/SKILL.md");
            if !files.iter().any(|other| other.eq_ignore_ascii_case(&entry)) {
                found.push(format!(
                    "{} ships {name:?} under {owner:?}, which has no SKILL.md, so the \
                     document is reachable from no entry point",
                    setup.manifest.id
                ));
            }
        }
    }
    found.sort();
    found.dedup();
    found
}

/// Whether a relative path inside a setup is a component's entry point.
fn is_entry_point(relative: &str) -> bool {
    let parts: Vec<&str> = relative.split('/').collect();
    let Some(leaf) = parts.last() else {
        return false;
    };
    // Anything under `references/` is a document, whatever it is called.
    if parts.contains(&"references") {
        return false;
    }
    if leaf.eq_ignore_ascii_case("SKILL.md") {
        return true;
    }
    // `agents/<name>.md` and `agents/<name>.toml`, and only directly under it.
    // The `.toml` form is how codex declares a role file; it is measured there
    // to carry the same two keys in TOML spelling.
    parts.len() >= 2
        && parts[parts.len() - 2] == "agents"
        && std::path::Path::new(leaf)
            .extension()
            .and_then(std::ffi::OsStr::to_str)
            .is_some_and(|extension| {
                extension.eq_ignore_ascii_case("md") || extension.eq_ignore_ascii_case("toml")
            })
}

/// Whether a TOML entry point assigns `key` at the top level.
///
/// Read by structure rather than by searching the whole file: only lines
/// before the first `[section]` header count, because a `description` three
/// tables down belongs to that table and not to the agent the file names.
fn toml_names(text: &str, key: &str) -> bool {
    text.lines()
        .take_while(|line| !line.trim_start().starts_with('['))
        .any(|line| {
            let line = line.trim_start();
            line.starts_with(key)
                && line[key.len()..]
                    .trim_start_matches([' ', '\t'])
                    .starts_with('=')
        })
}

/// Whether a file opens with YAML frontmatter naming `key`.
///
/// Read by structure rather than by searching the whole file: a `description:`
/// three hundred lines into the prose is not frontmatter, and a guard that
/// matched it would be measuring the document instead of its header.
fn frontmatter_names(text: &str, key: &str) -> bool {
    let Some(rest) = text.strip_prefix("---\n") else {
        return false;
    };
    let Some(end) = rest.find("\n---") else {
        return false;
    };
    rest[..end]
        .lines()
        .any(|line| line.trim_start().starts_with(&format!("{key}:")))
}

/// Two files in one setup that a case-insensitive filesystem would merge.
///
/// macOS and Windows fold case by default, so `SKILL.md` and `skill.md` in one
/// setup are **one** file there and two on Linux. The setup would then install
/// different content depending on the machine, and its
/// `setup_catalogue_digest` would differ per platform — which the three-OS
/// matrix does catch, but only after the mistake has been written and pushed.
///
/// `crate::provider_v3::bundle` already refuses this for a bundle *arriving* from a
/// consumer, on the same reasoning: *"the second would silently overwrite the
/// first"*. This applies the rule to the files this repository authors, which
/// is the direction it was missing.
#[must_use]
pub fn colliding(setups: &[Setup]) -> Vec<String> {
    let mut found = Vec::new();
    for setup in setups {
        let mut folded: std::collections::BTreeMap<String, String> =
            std::collections::BTreeMap::new();
        for name in files_under(&setup.payload) {
            if let Some(other) = folded.insert(name.to_lowercase(), name.clone())
                && other != name
            {
                found.push(format!(
                    "{} ships {name:?} and {other:?}, which differ only in case and are one \
                     file on macOS and Windows",
                    setup.manifest.id
                ));
            }
        }
    }
    found
}

/// Every setup that writes a configuration file and does not say where its
/// format came from, by setup id.
///
/// A document is exempt: prose has no keys to spell wrong. Anything else is a
/// claim about a product's schema, and a claim with no source is the thing this
/// project spent a release removing from its declarations.
#[must_use]
pub fn unsourced(setups: &[Setup]) -> Vec<String> {
    let mut found = Vec::new();
    for setup in setups {
        // A document has no schema to get wrong. Asked through `extension`
        // rather than by comparing the tail of the name, because a file called
        // `NOTES.MD` is a document on every system this ships to and a string
        // comparison would have said otherwise on two of them.
        let document = |name: &String| {
            std::path::Path::new(name)
                .extension()
                .and_then(std::ffi::OsStr::to_str)
                .is_some_and(|extension| {
                    extension.eq_ignore_ascii_case("md") || extension.eq_ignore_ascii_case("mdc")
                })
        };
        let writes_configuration = files_under(&setup.payload)
            .iter()
            .any(|name| !document(name));
        if !writes_configuration {
            continue;
        }
        if setup.manifest.sources.is_empty() {
            found.push(format!(
                "{} writes a configuration file and names no source for its format",
                setup.manifest.id
            ));
            continue;
        }
        for source in &setup.manifest.sources {
            if !source.starts_with("https://") {
                found.push(format!(
                    "{} cites {source:?}, which is not a page anyone can open",
                    setup.manifest.id
                ));
            }
        }
    }
    found
}

/// One setup in the catalog, with the digest that identifies its content.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Setup {
    /// What the setup says about itself.
    pub manifest: SetupManifest,
    /// Where its verbatim tree lives.
    pub payload: PathBuf,
    /// The digest of that tree.
    ///
    /// Two setups with the same bytes have the same definition digest, whatever
    /// they are called — identity is content, not a name.
    pub definition_digest: String,
    /// The digest of the setup's **manifest**, which the one above does not cover.
    ///
    /// `definition_digest` is `of_tree(payload)` and nothing else, deliberately:
    /// two setups with identical bytes must produce the same value so
    /// [`identical`] can call one of them a posture in name only. Folding the
    /// manifest in would give every setup a distinct digest and retire that
    /// guard, because `id` alone would separate them.
    ///
    /// **The cost of that was a manifest bound by nothing.** `setup_catalogue_digest`
    /// is the aggregate of the definition digests, so `id`, `sources` and
    /// `description` could change with every check in this estate staying green
    /// -- and those three are exactly what a consumer renders on the surface
    /// that precedes an install. `full-auto`'s description runs to 3312
    /// characters on one harness and is safety context, not marketing copy;
    /// `sources` is what `check_authored_keys.py` reads to source every key a
    /// setup writes. The provenance chain ran through a file no digest held.
    ///
    /// Proved rather than reasoned: a description was rewritten and the whole
    /// gate stayed clean.
    ///
    /// So there are two digests rather than one wider digest. Content identity
    /// keeps its meaning, and the manifest is held against silent change.
    pub manifest_digest: String,
    /// How many files the tree holds.
    pub file_count: u64,
    /// Keeps a materialized catalog alive for as long as `payload` names it.
    ///
    /// A `Setup` outlives the `Catalog` it came from — `get` returns one and the
    /// catalog is dropped — and for an embedded catalog the drop deletes the
    /// directory `payload` points into. `list` did not notice, because it reads
    /// everything before returning; `install` failed with *cannot list
    /// …/baseline/home*, having been handed a path to bytes that no longer
    /// existed.
    lifeline: Lifeline,
}

/// A handle that keeps a materialized catalog on disk, and is never identity.
///
/// Two setups with the same bytes are the same setup — that is the whole claim
/// `definition_digest` makes — so where those bytes were written cannot
/// participate in equality. Comparing always-equal is not a shortcut here; it is
/// the statement that provenance is not identity.
#[derive(Debug, Clone, Default)]
struct Lifeline(
    #[expect(
        dead_code,
        reason = "held for its Drop: this is the handle that keeps a materialized \
                  catalog on disk, and dead-code analysis does not count a \
                  destructor as a use"
    )]
    Option<Arc<Materialized>>,
);

impl PartialEq for Lifeline {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

impl Eq for Lifeline {}

/// A compiled-in catalog written to a directory this process owns.
///
/// Removed when the last handle goes. A failure to remove it is deliberately
/// silent: the bytes are a copy of something already inside the binary, the
/// directory is inside the system's temporary space, and refusing a command
/// that has already succeeded because a cleanup did not would be the tail
/// wagging the dog.
#[derive(Debug)]
struct Materialized {
    root: PathBuf,
}

impl Materialized {
    /// Write every embedded file under a fresh directory.
    fn write(harness: &Harness) -> Option<Self> {
        // Unique without a dependency: the process cannot collide with itself,
        // and the counter separates two catalogs opened in one process — which
        // the tests do, in threads.
        //
        // The name is kept short on purpose, and the reason is Windows. A
        // classic `MAX_PATH` is 260, and the longest path here is
        // `<temp>/<this directory>/<deepest file in any setup>`. Measured
        // 2026-08-26: the deepest relative path any setup holds is 98 bytes
        // (cursor's `nddev-builder/home/plugins/…/installation-lifecycle.md`)
        // and a normal Windows temp root is around 42, which leaves this name
        // as the only part anyone here controls. `<provider_id>-<pid>-<n>` is
        // 46 for the longest provider id, for a worst case near 186 — enough
        // headroom for a long user name, which `…-setups-…` was eating for a
        // word that says nothing the provider id does not.
        static NEXT: AtomicU32 = AtomicU32::new(0);
        let root = std::env::temp_dir().join(format!(
            "{}-{}-{}",
            harness.provider_id,
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ));
        // A leftover from a crashed run of the same pid must not be read as
        // this one's catalog.
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).ok()?;

        let held = Self { root };
        for (relative, bytes) in harness.embedded_setups {
            let path = held.root.join(relative);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).ok()?;
            }
            fs::write(&path, bytes).ok()?;
        }
        Some(held)
    }

    fn path(&self) -> &Path {
        &self.root
    }
}

impl Drop for Materialized {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.root);
    }
}

/// The catalog this build ships.
#[derive(Debug, Clone)]
pub struct Catalog {
    root: PathBuf,
    /// Kept alive so a materialized catalog outlives every reader of it.
    ///
    /// Shared rather than owned because `Catalog` is cloned, and two owners of
    /// one temporary directory would delete it twice — the second time out from
    /// under whoever still held the first. Handed to every [`Setup`] this
    /// catalog produces, so the bytes outlive the catalog that found them.
    lifeline: Lifeline,
}

impl Catalog {
    /// Open the catalog at an explicit root.
    #[must_use]
    pub fn at(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            lifeline: Lifeline::default(),
        }
    }

    /// Find the catalog this harness ships.
    ///
    /// An explicit `<PROVIDER_ID>_SETUP_CATALOG` wins, so a caller can point the
    /// binary at a catalog of their own without rebuilding it — the owner's own
    /// setups are as legitimate a source as the shipped ones.
    ///
    /// Otherwise `setups/` is looked for beside the executable and upward, then
    /// in the working directory. Each candidate is tried twice: once as the
    /// catalog itself, and once with the harness id beneath it. A published tree
    /// ships one harness and uses the first shape; the workspace that authors
    /// them all uses the second, and a developer should not have to know which
    /// one they are standing in.
    ///
    /// That second shape was a claim rather than a fact until the embedded
    /// catalog existed: it joins the *harness id*, and two harness ids are not
    /// their tool names — `claude-code` against `setups/claude`, `grok-build`
    /// against `setups/grok`. Two of the seven could not find their own catalog
    /// from the workspace root, and the comment above said they could.
    ///
    /// When nothing is found on disk, the catalog compiled into this binary is
    /// materialized and used. That is the case for every user who installed the
    /// documented way, because the release ships binaries and no `setups/`.
    #[must_use]
    pub fn discover(harness: &Harness) -> Option<Self> {
        Self::on_disk(harness).or_else(|| Self::embedded(harness))
    }

    /// The catalog someone put on a disk, if there is one.
    #[must_use]
    fn on_disk(harness: &Harness) -> Option<Self> {
        let variable = format!(
            "{}_SETUP_CATALOG",
            harness.provider_id.to_uppercase().replace('-', "_")
        );
        if let Ok(explicit) = std::env::var(&variable) {
            let path = PathBuf::from(explicit);
            return path.is_dir().then_some(Self::at(path));
        }

        let mut roots: Vec<PathBuf> = Vec::new();
        if let Ok(executable) = std::env::current_exe()
            && let Some(directory) = executable.parent()
        {
            roots.push(directory.to_path_buf());
            let mut walk = directory;
            for _ in 0..3 {
                let Some(up) = walk.parent() else { break };
                roots.push(up.to_path_buf());
                walk = up;
            }
        }
        if let Ok(cwd) = std::env::current_dir() {
            roots.push(cwd);
        }

        roots
            .into_iter()
            .flat_map(|root| {
                let base = root.join(CATALOG_DIRECTORY);
                [base.join(harness.harness_id), base]
            })
            .find(|path| path.is_dir() && Self::holds_a_setup(path))
            .map(Self::at)
    }

    /// Write the compiled-in catalog somewhere real, and read it from there.
    ///
    /// Materializing rather than teaching every reader about a second kind of
    /// catalog is the whole point. A setup's identity is the digest of its
    /// tree, computed by walking a directory; a second in-memory implementation
    /// of that walk would be a second chance to disagree, and the two would
    /// disagree about exactly the thing that decides whether a target has
    /// drifted. Writing the bytes down means `list`, `get`, the digest and the
    /// copy are the same code they have always been, and the embedded catalog
    /// is provably the same setup as the on-disk one because it *is* one.
    ///
    /// The directory belongs to this process and is removed when the last
    /// handle to it goes.
    #[must_use]
    fn embedded(harness: &Harness) -> Option<Self> {
        if harness.embedded_setups.is_empty() {
            return None;
        }
        let root = Materialized::write(harness)?;
        let path = root.path().to_path_buf();
        Some(Self {
            root: path,
            lifeline: Lifeline(Some(Arc::new(root))),
        })
    }

    /// Whether a directory holds at least one readable setup manifest.
    ///
    /// Without this, the workspace's `setups/` — which holds one directory per
    /// harness and no manifests — would be chosen as an empty catalog and the
    /// harness-scoped directory beneath it never reached.
    fn holds_a_setup(path: &Path) -> bool {
        let Ok(read) = fs::read_dir(path) else {
            return false;
        };
        read.flatten()
            .any(|entry| entry.path().join(SETUP_MANIFEST).is_file())
    }

    /// The catalog root.
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Every readable setup, by identity.
    ///
    /// A directory that does not parse is skipped rather than fatal: one broken
    /// setup should not make its neighbours unlistable.
    ///
    /// # Errors
    ///
    /// Returns [`WireReason::ProviderUnavailable`] if the catalog cannot be
    /// listed at all.
    pub fn list(&self) -> Result<Vec<Setup>> {
        let read = match fs::read_dir(&self.root) {
            Ok(read) => read,
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(source) => {
                return Err(Error::refuse(
                    WireReason::ProviderUnavailable,
                    format!(
                        "cannot list the setup catalog at {}: {source}",
                        self.root.display()
                    ),
                ));
            }
        };
        let mut setups = Vec::new();
        for entry in read.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            if let Ok(setup) = read_setup(&path, &self.lifeline) {
                setups.push(setup);
            }
        }
        setups.sort_by(|left, right| left.manifest.id.cmp(&right.manifest.id));
        Ok(setups)
    }

    /// One setup by identity.
    ///
    /// # Errors
    ///
    /// Returns [`WireReason::ProviderUnavailable`] when no setup carries that
    /// identity, naming the ones that do.
    pub fn get(&self, id: &str) -> Result<Setup> {
        let available = self.list()?;
        available
            .iter()
            .find(|setup| setup.manifest.id == id)
            .cloned()
            .ok_or_else(|| {
                let names: Vec<&str> = available
                    .iter()
                    .map(|setup| setup.manifest.id.as_str())
                    .collect();
                Error::refuse(
                    WireReason::ProviderUnavailable,
                    if names.is_empty() {
                        format!("{id:?} is not a setup; this build ships no catalog")
                    } else {
                        format!(
                            "{id:?} is not a setup; this build ships {}",
                            names.join(", ")
                        )
                    },
                )
            })
    }
}

/// Read one setup directory, or say why it is not one.
fn read_setup(directory: &Path, lifeline: &Lifeline) -> Result<Setup> {
    let manifest_path = directory.join(SETUP_MANIFEST);
    let bytes = fs::read(&manifest_path).map_err(|source| {
        Error::refuse(
            WireReason::ProviderUnavailable,
            format!("cannot read {}: {source}", manifest_path.display()),
        )
    })?;
    let manifest: SetupManifest = serde_json::from_slice(&bytes).map_err(|source| {
        Error::refuse(
            WireReason::ProviderUnavailable,
            format!("{} does not parse: {source}", manifest_path.display()),
        )
    })?;
    if manifest.schema_version != SETUP_SCHEMA {
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{} is schema {} and this build writes {SETUP_SCHEMA}",
                manifest_path.display(),
                manifest.schema_version
            ),
        ));
    }
    // A setup whose directory and declared identity disagree would be
    // selectable by one name and recorded under another.
    let directory_name = directory.file_name().and_then(|name| name.to_str());
    if directory_name != Some(manifest.id.as_str()) {
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{} declares id {:?} but sits in {:?}",
                manifest_path.display(),
                manifest.id,
                directory_name.unwrap_or("?")
            ),
        ));
    }

    let payload = directory.join(SETUP_PAYLOAD);
    if !payload.is_dir() {
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!("{} has no {SETUP_PAYLOAD} tree", directory.display()),
        ));
    }
    Ok(Setup {
        definition_digest: digest::of_tree(&payload)?,
        // The manifest's own bytes, separately from the payload's, and the
        // separation is the point. See the field's documentation.
        manifest_digest: digest::of_bytes(&std::fs::read(&manifest_path).map_err(|error| {
            Error::refuse(
                WireReason::ProviderUnavailable,
                format!("{} cannot be re-read: {error}", manifest_path.display()),
            )
        })?),
        file_count: count_files(&payload)?,
        manifest,
        payload,
        lifeline: lifeline.clone(),
    })
}

impl Setup {
    /// Every file this setup would write, as a path relative to the target.
    ///
    /// Files rather than top-level entries, because a harness may own a nested
    /// namespace and nothing else beside it: listing only the first component
    /// cannot tell `antigravity-cli/settings.json`, which is owned, from
    /// `antigravity-cli` as a whole, which is not.
    ///
    /// # Errors
    ///
    /// Returns [`WireReason::ProviderUnavailable`] if the payload cannot be
    /// listed, or holds a name this provider cannot represent as a path.
    pub fn relative_paths(&self) -> Result<Vec<String>> {
        let mut found = Vec::new();
        let mut stack = vec![self.payload.clone()];
        while let Some(current) = stack.pop() {
            let read = fs::read_dir(&current).map_err(|source| {
                Error::refuse(
                    WireReason::ProviderUnavailable,
                    format!("cannot list {}: {source}", current.display()),
                )
            })?;
            for entry in read.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    stack.push(path);
                    continue;
                }
                let relative = path.strip_prefix(&self.payload).map_err(|_| {
                    Error::refuse(
                        WireReason::ProviderUnavailable,
                        format!("{} escaped the setup payload", path.display()),
                    )
                })?;
                let Some(text) = relative.to_str() else {
                    return Err(Error::refuse(
                        WireReason::ProviderUnavailable,
                        format!("{} is not representable as a path", relative.display()),
                    ));
                };
                found.push(text.replace('\\', "/"));
            }
        }
        found.sort();
        Ok(found)
    }

    /// Check that every entry this setup writes is one the harness owns.
    ///
    /// A setup that wrote outside the declared namespaces would put files into a
    /// target that `remove` would then leave behind, and that `status` would not
    /// account for. Refusing here keeps ownership and effect the same set.
    ///
    /// # Errors
    ///
    /// Returns [`WireReason::UnsupportedNativeSurface`] naming the first entry
    /// outside the harness's declared surface.
    pub fn check_within(&self, harness: &Harness) -> Result<()> {
        for path in self.relative_paths()? {
            if !harness.owns(&path) {
                return Err(Error::refuse(
                    WireReason::UnsupportedNativeSurface,
                    format!(
                        "setup {:?} writes {path:?}, which is outside the surface {} owns",
                        self.manifest.id, harness.provider_id
                    ),
                ));
            }
        }
        Ok(())
    }
}

fn count_files(root: &Path) -> Result<u64> {
    let mut total = 0_u64;
    let mut stack = vec![root.to_path_buf()];
    while let Some(current) = stack.pop() {
        let read = fs::read_dir(&current).map_err(|source| {
            Error::refuse(
                WireReason::ProviderUnavailable,
                format!("cannot list {}: {source}", current.display()),
            )
        })?;
        for entry in read.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else {
                total = total.saturating_add(1);
            }
        }
    }
    Ok(total)
}

/// Keys measured in Antigravity CLI settings. The historical 1.1.22 artifact
/// registry is retained; native 1.2.10 additionally reads `allowNonWorkspaceAccess`.
/// See the baseline setting compatibility evidence before adding another key.
pub const ANTIGRAVITY_MEASURED_SETTING_KEYS: &[&str] = &[
    "toolPermission",
    "enableTerminalSandbox",
    "allowAgentAccessNonWorkspaceFiles",
    "allowNonWorkspaceAccess",
    "allowCascadeAccessGitignoreFiles",
    "autoContinueOnMaxGeneratorInvocations",
    "permissions",
];

/// Whether `config_home` is an autonomous execution posture for `harness_id`.
///
/// `config_home` is the directory `launch` would export as the product's
/// configuration home — the catalog `home/` payload after it has been copied
/// to `--target`. Empty means autonomous. Each line is one missing required
/// marker or one leftover ask/on-request marker in the file that product
/// reads from this home.
#[must_use]
pub fn effective_autonomy(harness_id: &str, config_home: &Path) -> Vec<String> {
    let label = harness_id;
    match harness_id {
        "claude" => policy_markers(
            label,
            &config_home.join("settings.json"),
            &[
                r#""defaultMode": "bypassPermissions""#,
                r#""enabled": false"#,
            ],
            &["on-request", r#""ask""#, "request-review"],
        ),
        "codex" => policy_markers(
            label,
            &config_home.join("config.toml"),
            &[
                r#"approval_policy = "never""#,
                r#"sandbox_mode = "danger-full-access""#,
            ],
            &["on-request", "workspace-write"],
        ),
        "grok" => policy_markers(
            label,
            &config_home.join("config.toml"),
            &[
                r#"permission_mode = "always-approve""#,
                "yolo = true",
                r#"profile = "off""#,
            ],
            &["on-request", r#"permission_mode = "ask""#],
        ),
        "cursor" => policy_markers(
            label,
            &config_home.join("cli-config.json"),
            &[r#""approvalMode": "unrestricted""#, r#""mode": "disabled""#],
            &["on-request", r#""ask""#, "request-review"],
        ),
        "opencode" => policy_markers(
            label,
            &config_home.join("opencode.json"),
            &[r#""*": "allow""#],
            &[r#""ask""#],
        ),
        "pi" => policy_markers(
            label,
            &config_home.join("settings.json"),
            &[r#""defaultProjectTrust": "always""#],
            &[r#""ask""#],
        ),
        "antigravity" => policy_markers(
            label,
            &config_home.join("antigravity-cli/settings.json"),
            &[
                r#""toolPermission": "always-proceed""#,
                r#""enableTerminalSandbox": false"#,
            ],
            &["request-review", "on-request"],
        ),
        other => vec![format!("{other}: unknown harness")],
    }
}

fn policy_markers(label: &str, path: &Path, required: &[&str], forbidden: &[&str]) -> Vec<String> {
    let mut problems = Vec::new();
    let Ok(raw) = fs::read_to_string(path) else {
        problems.push(format!("{label}: missing {}", path.display()));
        return problems;
    };
    let text = if path.extension().is_some_and(|ext| ext == "toml") {
        raw.lines()
            .filter(|line| !line.trim_start().starts_with('#'))
            .collect::<Vec<_>>()
            .join("\n")
    } else {
        raw
    };
    for marker in required {
        if !text.contains(marker) {
            problems.push(format!(
                "{label}: {} does not contain {marker}",
                path.display()
            ));
        }
    }
    for marker in forbidden {
        if text.contains(marker) {
            problems.push(format!(
                "{label}: {} still contains {marker}",
                path.display()
            ));
        }
    }
    problems
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::panic)]

    use super::*;

    fn scratch(name: &str) -> PathBuf {
        let base =
            std::env::temp_dir().join(format!("harness-catalog-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(&base).unwrap();
        base
    }

    /// A path template names a class of file; a relative one names a document.
    ///
    /// `dangling_references` had no unit test at all -- it was exercised only
    /// through each leaf crate against the real setups, which means a change to
    /// its exemption list was checked by whatever the setups happened to
    /// contain that day. It cost a false refusal the day a generated reference
    /// quoted antigravity's own `{workspace}/.agents/skills/{skill_name}/
    /// SKILL.md`: braces are that vendor's placeholder spelling and the list
    /// knew only `<>` and `*`.
    ///
    /// Both directions, because an exemption that swallows the real case is
    /// worse than the refusal it replaced.
    #[test]
    fn a_placeholder_names_a_class_of_file_and_a_relative_path_names_a_document() {
        let root = scratch("dangling-placeholders");
        write_setup(
            &root,
            "templates",
            &[(
                "notes.md",
                "See `{workspace}/.agents/skills/{skill_name}/SKILL.md`, \
                 `<plugin>/agents/*.md` and `~/.cursor/skills/x/SKILL.md`.",
            )],
        );
        let listed = Catalog::at(&root).list().unwrap();
        assert_eq!(
            dangling_references(&listed),
            Vec::<String>::new(),
            "a placeholder or an out-of-setup root is not a document this setup carries"
        );

        // The control: a plain relative path, with nothing at the other end.
        let root = scratch("dangling-real");
        write_setup(
            &root,
            "broken",
            &[("notes.md", "Read `references/gone.md`.")],
        );
        let listed = Catalog::at(&root).list().unwrap();
        let found = dangling_references(&listed);
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(found[0].contains("references/gone.md"), "{found:?}");
    }

    /// A plugin with no manifest is neither checked nor mis-reported.
    ///
    /// Two of the six harnesses that declare `plugin` have no manifest at all:
    /// an OpenCode plugin is a module file exporting functions, and a Pi
    /// extension is a package. The manifest guards answer `false` for both, and
    /// this asserts that answering `false` is harmless rather than a hole —
    /// a module file cannot hold a `references/` directory, so no walk demands
    /// a `SKILL.md` beside it, and it carries no `name` field for `undescribed`
    /// to want.
    ///
    /// Written because the comment on those guards claimed the manifest shapes
    /// covered every product, and no setup here ships a plugin for OpenCode,
    /// Grok or Pi, so nothing had ever exercised the claim.
    #[test]
    fn a_plugin_that_is_a_module_file_needs_neither_guard() {
        let root = scratch("plugin-as-module");
        write_setup(
            &root,
            "module-plugin",
            &[(
                "plugins/nddev-builder.js",
                "export const hooks = () => ({});\n",
            )],
        );
        let listed = Catalog::at(&root).list().unwrap();

        assert!(
            undescribed(&listed).problems.is_empty(),
            "a module plugin was asked for fields it does not have: {:?}",
            undescribed(&listed).problems
        );
        assert!(
            unreachable_references(&listed).is_empty(),
            "a module plugin was walked as though it were a skill: {:?}",
            unreachable_references(&listed)
        );
    }

    /// A plugin manifest has to name itself, like every other entry point.
    ///
    /// `undescribed` requires a `SKILL.md` and an agent file to carry `name`
    /// and `description`, because a component the product names after its
    /// directory gives a model nothing to choose on. A plugin manifest carries
    /// the same two fields for the same reason -- the product shows
    /// `description` when browsing one.
    ///
    /// It escaped the check entirely until `skills` began routing two kinds.
    /// Before that every entry under a skills directory was a skill, so every
    /// entry had frontmatter and every one was read; a plugin has none, so it
    /// was no entry point and nothing looked at it. Recorded first as an
    /// observation that passed, then turned into this when the gap closed.
    ///
    /// Both directions, and both shapes: a manifest that names nothing is
    /// caught under the vendor-prefixed path and under Antigravity's root
    /// `plugin.json`, and one that names both is not.
    #[test]
    fn a_plugin_manifest_has_to_name_itself() {
        let root = scratch("plugin-describes-itself");
        write_setup(
            &root,
            "silent-plugin",
            &[(
                "skills/tool/.claude-plugin/plugin.json",
                "{\"name\": \"tool\", \"version\": \"1.0.0\"}",
            )],
        );
        write_setup(
            &root,
            "silent-at-the-root",
            &[("plugins/tool/plugin.json", "{\"version\": \"1.0.0\"}")],
        );
        write_setup(
            &root,
            "speaking-plugin",
            &[(
                "skills/tool/.claude-plugin/plugin.json",
                "{\"name\": \"tool\", \"description\": \"what it is for\"}",
            )],
        );

        let listed = Catalog::at(&root).list().unwrap();
        let found = undescribed(&listed).problems;

        assert!(
            found
                .iter()
                .any(|p| p.contains("silent-plugin") && p.contains("description")),
            "a manifest with no description was not caught: {found:?}"
        );
        assert!(
            found.iter().any(|p| p.contains("silent-at-the-root")),
            "the root-manifest shape was not checked: {found:?}"
        );
        assert!(
            found.iter().all(|p| !p.contains("speaking-plugin")),
            "a manifest naming both fields was reported anyway: {found:?}"
        );
    }

    /// A plugin folder is not a skill missing its entry point.
    ///
    /// `unreachable_references` was written when one directory held one kind.
    /// Claude Code loads a folder under `skills/` as a *plugin* when it carries
    /// `.claude-plugin/plugin.json`, and as a skill when it carries `SKILL.md`
    /// -- the product's own discriminator is the manifest, not the location. So
    /// a walk that assumes every entry under a skills path is a skill reports
    /// the plugin as one missing its entry point.
    ///
    /// Observed before it was fixed: the same tree, with and without the
    /// manifest, and the assertion is that only the second is a problem. The
    /// first is the case that had no name until `skills` began routing two
    /// kinds.
    #[test]
    fn a_plugin_folder_is_not_a_skill_that_lost_its_entry_point() {
        let root = scratch("plugin-under-skills");
        write_setup(
            &root,
            "with-manifest",
            &[
                (
                    "skills/tool/.claude-plugin/plugin.json",
                    "{\"name\": \"tool\", \"version\": \"1.0.0\"}",
                ),
                ("skills/tool/references/notes.md", "supporting prose"),
            ],
        );
        // The control: the same shape with no manifest is a skill, and a skill
        // with references and no SKILL.md is the defect this guard exists for.
        write_setup(
            &root,
            "without-manifest",
            &[("skills/tool/references/notes.md", "supporting prose")],
        );

        let listed = Catalog::at(&root).list().unwrap();
        let found = unreachable_references(&listed);

        assert!(
            found
                .iter()
                .all(|problem| !problem.contains("with-manifest")),
            "a plugin folder was reported as a skill missing SKILL.md: {found:?}"
        );
        assert!(
            found
                .iter()
                .any(|problem| problem.contains("without-manifest")),
            "the guard stopped catching a skill with no entry point: {found:?}"
        );
    }

    #[test]
    fn a_manifest_carries_corpus_identity_without_replacing_its_directory_id() {
        let manifest: SetupManifest = serde_json::from_slice(
            br#"{
                "schema_version": 1,
                "id": "full-auto",
                "description": "full auto",
                "setup_stable_id": "setup_01TESTIDENTITY000000000000",
                "setup_version": "1.4",
                "setup_passport_digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "component_refs": [
                    {
                        "stable_id": "cmp_01TESTIDENTITY0000000000000",
                        "version": "1.0",
                        "passport_digest": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
                        "adaptation_id": "adp_01TESTIDENTITY0000000000000"
                    }
                ]
            }"#,
        )
        .unwrap();
        assert_eq!(manifest.id, "full-auto");
        assert_eq!(
            manifest.setup_stable_id.as_deref(),
            Some("setup_01TESTIDENTITY000000000000")
        );
        assert_eq!(manifest.setup_version.as_deref(), Some("1.4"));
        assert_eq!(manifest.component_refs.len(), 1);
        assert_eq!(
            manifest.component_refs[0].stable_id,
            "cmp_01TESTIDENTITY0000000000000"
        );
        assert_eq!(
            manifest.component_refs[0].adaptation_id,
            "adp_01TESTIDENTITY0000000000000"
        );
    }

    fn write_setup(root: &Path, id: &str, files: &[(&str, &str)]) {
        let directory = root.join(id);
        fs::create_dir_all(directory.join(SETUP_PAYLOAD)).unwrap();
        fs::write(
            directory.join(SETUP_MANIFEST),
            serde_json::to_vec_pretty(&SetupManifest {
                schema_version: SETUP_SCHEMA,
                id: id.to_owned(),
                description: format!("the {id} setup"),
                sources: Vec::new(),
                setup_stable_id: None,
                setup_version: None,
                setup_passport_digest: None,
                component_refs: Vec::new(),
            })
            .unwrap(),
        )
        .unwrap();
        for (relative, content) in files {
            let path = directory.join(SETUP_PAYLOAD).join(relative);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).unwrap();
            }
            fs::write(path, content).unwrap();
        }
    }

    #[test]
    fn an_absent_catalog_lists_nothing_rather_than_failing() {
        let catalog = Catalog::at(scratch("absent").join("nowhere"));
        assert!(catalog.list().unwrap().is_empty());
    }

    #[test]
    fn setups_are_listed_by_identity_with_a_content_digest() {
        let root = scratch("list");
        write_setup(&root, "safe", &[("AGENTS.md", "# safe\n")]);
        write_setup(&root, "full-auto", &[("AGENTS.md", "# full\n")]);

        let listed = Catalog::at(&root).list().unwrap();
        assert_eq!(
            listed
                .iter()
                .map(|s| s.manifest.id.as_str())
                .collect::<Vec<_>>(),
            vec!["full-auto", "safe"]
        );
        assert!(listed[0].definition_digest.starts_with("sha256:"));
        assert_ne!(listed[0].definition_digest, listed[1].definition_digest);
        assert_eq!(listed[0].file_count, 1);
    }

    #[test]
    fn identity_is_content_so_two_names_over_the_same_bytes_agree() {
        let root = scratch("same-bytes");
        write_setup(&root, "one", &[("AGENTS.md", "identical\n")]);
        write_setup(&root, "two", &[("AGENTS.md", "identical\n")]);
        let listed = Catalog::at(&root).list().unwrap();
        assert_eq!(listed[0].definition_digest, listed[1].definition_digest);
    }

    #[test]
    fn a_setup_whose_directory_and_declared_id_disagree_is_not_listed() {
        // It would be selectable by one name and recorded under another.
        let root = scratch("mismatch");
        write_setup(&root, "safe", &[("AGENTS.md", "x")]);
        fs::rename(root.join("safe"), root.join("renamed")).unwrap();
        assert!(Catalog::at(&root).list().unwrap().is_empty());
    }

    #[test]
    fn one_broken_setup_does_not_make_the_others_unlistable() {
        let root = scratch("partly-broken");
        write_setup(&root, "good", &[("AGENTS.md", "x")]);
        fs::create_dir_all(root.join("broken")).unwrap();
        fs::write(root.join("broken").join(SETUP_MANIFEST), "{ not json").unwrap();

        let listed = Catalog::at(&root).list().unwrap();
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].manifest.id, "good");
    }

    #[test]
    fn a_setup_with_no_payload_tree_is_refused() {
        let root = scratch("no-payload");
        write_setup(&root, "empty", &[]);
        fs::remove_dir_all(root.join("empty").join(SETUP_PAYLOAD)).unwrap();
        assert!(Catalog::at(&root).list().unwrap().is_empty());
    }

    #[test]
    fn asking_for_an_unknown_setup_names_the_ones_that_exist() {
        let root = scratch("unknown");
        write_setup(&root, "safe", &[("AGENTS.md", "x")]);
        let error = Catalog::at(&root).get("nope").unwrap_err();
        assert!(error.detail().contains("safe"), "{error}");
    }

    #[test]
    fn a_setup_writing_outside_the_declared_surface_is_refused() {
        let root = scratch("outside");
        write_setup(
            &root,
            "sneaky",
            &[("AGENTS.md", "x"), ("elsewhere.txt", "y")],
        );
        let setup = Catalog::at(&root).get("sneaky").unwrap();
        let harness = crate::harness_runtime::wire::tests_support::TEST;
        let error = setup.check_within(&harness).unwrap_err();
        assert_eq!(error.reason(), Some(WireReason::UnsupportedNativeSurface));
        assert!(error.detail().contains("elsewhere.txt"));
    }

    #[test]
    fn a_setup_inside_the_declared_surface_is_accepted() {
        let root = scratch("inside");
        write_setup(&root, "fine", &[("AGENTS.md", "x"), ("skills/a.md", "y")]);
        let setup = Catalog::at(&root).get("fine").unwrap();
        assert!(
            setup
                .check_within(&crate::harness_runtime::wire::tests_support::TEST)
                .is_ok()
        );
        assert_eq!(setup.file_count, 2);
    }

    /// The same two files a real setup holds, as the build script would embed
    /// them: relative slash paths and bytes, nothing else.
    const EMBEDDED: &[(&str, &[u8])] = &[
        (
            "baseline/setup.json",
            br#"{"schema_version":1,"id":"baseline","description":"the baseline setup"}"#,
        ),
        ("baseline/home/AGENTS.md", b"# instructions\n"),
        ("baseline/home/skills/a.md", b"a skill\n"),
    ];

    fn harness_carrying_the_embedded_catalog() -> Harness {
        let mut harness = crate::harness_runtime::wire::tests_support::TEST;
        harness.embedded_setups = EMBEDDED;
        harness
    }

    /// The defect this exists for: `get` returns a `Setup` and the `Catalog`
    /// that produced it is dropped on the next line. For an embedded catalog
    /// that drop deletes the directory `payload` points into, so the caller is
    /// handed a path to bytes that no longer exist.
    ///
    /// `list` never noticed, because it reads everything before returning. The
    /// first thing that did was a real `install` from a binary with no `setups/`
    /// beside it, which refused with *cannot list …/baseline/home*.
    #[test]
    fn a_setup_outlives_the_embedded_catalog_it_came_from() {
        let harness = harness_carrying_the_embedded_catalog();
        let setup = Catalog::embedded(&harness)
            .unwrap()
            .get("baseline")
            .unwrap();

        // Everything that found the setup is gone; only the setup is held.
        assert_eq!(
            fs::read_to_string(setup.payload.join("AGENTS.md")).unwrap(),
            "# instructions\n",
            "the bytes were deleted while a caller still held the path to them"
        );
        assert_eq!(setup.file_count, 2);
    }

    /// A setup is its content, so the same bytes must have the same identity
    /// whether they were shipped inside the binary or found on a disk. If these
    /// two ever disagree, one target configured from the release and another
    /// from a checkout would report different identities for the same setup, and
    /// every drift, restore and `setup_definition_digest` downstream inherits
    /// the disagreement.
    #[test]
    fn the_embedded_catalog_and_the_same_bytes_on_disk_are_one_setup() {
        let root = scratch("embedded-equals-disk");
        write_setup(
            &root,
            "baseline",
            &[
                ("AGENTS.md", "# instructions\n"),
                ("skills/a.md", "a skill\n"),
            ],
        );
        let on_disk = Catalog::at(&root).get("baseline").unwrap();

        let harness = harness_carrying_the_embedded_catalog();
        let embedded = Catalog::embedded(&harness)
            .unwrap()
            .get("baseline")
            .unwrap();

        assert_eq!(
            embedded.definition_digest, on_disk.definition_digest,
            "the binary and the tree disagree about what the baseline setup is"
        );
        assert_eq!(embedded.file_count, on_disk.file_count);
    }

    /// A harness that ships no catalog says so by finding nothing, rather than
    /// by producing an empty directory that reads as a catalog with no setups.
    /// The two are different answers: one is "this build has none", the other is
    /// "this build has a catalog and it is empty".
    #[test]
    fn a_build_carrying_no_embedded_catalog_finds_none() {
        assert!(Catalog::embedded(&crate::harness_runtime::wire::tests_support::TEST).is_none());
    }

    /// The temporary directory belongs to the process, and two catalogs opened
    /// in one process must not be handed the same one — the second would delete
    /// the first's bytes when it cleared a stale directory before writing.
    #[test]
    fn two_embedded_catalogs_in_one_process_do_not_share_a_directory() {
        let harness = harness_carrying_the_embedded_catalog();
        let first = Catalog::embedded(&harness).unwrap();
        let second = Catalog::embedded(&harness).unwrap();
        assert_ne!(first.root(), second.root());
        assert!(first.get("baseline").is_ok());
        assert!(second.get("baseline").is_ok());
    }

    /// Every shipped standard variant uses the same autonomous execution posture.
    ///
    /// Content footprint may differ; asking the user or sandboxing by default
    /// may not. A planted ask/on-request/request-review setting in any standard
    /// variant must fail this test.
    ///
    /// The shared source tree nests `setups/{harness}/{variant}`. A public
    /// provider keeps `setups/{variant}` at the root. Counting only the nested
    /// shape reported `found 0` on every rendered provider.
    #[test]
    fn standard_variants_share_autonomous_posture() {
        let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
        let harnesses = harnesses_in_workspace(&workspace);
        let rows = standard_setup_dirs(&workspace.join("setups"), &harnesses);
        let expected = harnesses.len() * STANDARD_VARIANTS.len();
        assert_eq!(
            rows.len(),
            expected,
            "expected {expected} standard variants for {:?}, found {}",
            harnesses,
            rows.len()
        );
        let mut problems = Vec::new();
        for (harness, variant_dir) in &rows {
            problems.extend(autonomy_problems(harness, variant_dir));
        }
        assert!(
            problems.is_empty(),
            "standard variants are not uniformly autonomous:\n{}",
            problems.join("\n")
        );
    }

    const STANDARD_VARIANTS: &[&str] = &["baseline", "minimal", "full-auto", "nddev-builder"];

    fn harnesses_in_workspace(workspace: &Path) -> Vec<String> {
        let crates = workspace.join("crates");
        let mut names = Vec::new();
        for name in [
            "claude",
            "codex",
            "grok",
            "pi",
            "cursor",
            "opencode",
            "antigravity",
        ] {
            if crates.join(format!("{name}-setup-system")).is_dir() {
                names.push(name.to_owned());
            }
        }
        names
    }

    fn standard_setup_dirs(setups: &Path, harnesses: &[String]) -> Vec<(String, PathBuf)> {
        let mut rows = Vec::new();
        if harnesses.len() == 1 {
            let harness = &harnesses[0];
            for variant in STANDARD_VARIANTS {
                let variant_dir = setups.join(variant);
                if variant_dir.join(SETUP_MANIFEST).is_file() {
                    rows.push((harness.clone(), variant_dir));
                }
            }
            return rows;
        }
        for harness in harnesses {
            for variant in STANDARD_VARIANTS {
                let variant_dir = setups.join(harness).join(variant);
                if variant_dir.join(SETUP_MANIFEST).is_file() {
                    rows.push((harness.clone(), variant_dir));
                }
            }
        }
        rows
    }

    #[test]
    fn a_single_harness_tree_reads_top_level_standard_variants() {
        let root = scratch("public-layout-setups");
        for variant in STANDARD_VARIANTS {
            fs::create_dir_all(root.join(variant)).unwrap();
            fs::write(root.join(variant).join(SETUP_MANIFEST), "{}").unwrap();
        }
        let rows = standard_setup_dirs(&root, &["claude".to_owned()]);
        assert_eq!(rows.len(), STANDARD_VARIANTS.len());
        assert!(rows.iter().all(|(harness, _)| harness == "claude"));
    }

    #[test]
    fn a_planted_ask_posture_fails_the_autonomy_matrix() {
        let root = scratch("planted-ask");
        fs::create_dir_all(root.join("home")).unwrap();
        fs::write(
            root.join("home/opencode.json"),
            r#"{"permission":{"edit":"ask"}}"#,
        )
        .unwrap();
        let problems = autonomy_problems("opencode", &root);
        assert!(
            problems.iter().any(|line| line.contains(r#""ask""#)),
            "planted ask did not fail: {problems:?}"
        );
    }

    fn autonomy_problems(harness: &str, variant_dir: &Path) -> Vec<String> {
        effective_autonomy(harness, &variant_dir.join(SETUP_PAYLOAD))
    }

    fn copy_tree(from: &Path, to: &Path) {
        fs::create_dir_all(to).unwrap();
        for entry in fs::read_dir(from).unwrap() {
            let entry = entry.unwrap();
            let dest = to.join(entry.file_name());
            if entry.path().is_dir() {
                copy_tree(&entry.path(), &dest);
            } else {
                fs::copy(entry.path(), dest).unwrap();
            }
        }
    }

    /// Policy file under config home plus bytes that
    /// [`effective_autonomy`] reports as leftover ask/on-request.
    fn planted_ask_file(harness: &str) -> (&'static str, &'static [u8]) {
        match harness {
            "claude" => ("settings.json", br#"{"defaultMode":"ask"}"#),
            "codex" => ("config.toml", b"approval_policy = \"on-request\"\n"),
            "grok" => ("config.toml", b"permission_mode = \"ask\"\n"),
            "cursor" => ("cli-config.json", br#"{"approvalMode":"ask"}"#),
            "opencode" => ("opencode.json", br#"{"permission":{"*":"ask"}}"#),
            "pi" => ("settings.json", br#"{"defaultProjectTrust":"ask"}"#),
            "antigravity" => (
                "antigravity-cli/settings.json",
                br#"{"toolPermission":"request-review"}"#,
            ),
            other => panic!("{other}: no planted-ask fixture"),
        }
    }

    fn write_planted_ask(home: &Path, harness: &str) {
        let (relative, bytes) = planted_ask_file(harness);
        let path = home.join(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(path, bytes).unwrap();
    }

    /// The first full-auto payload this workspace actually ships.
    ///
    /// Authoring has seven harnesses; a public tree has one. Hard-coding
    /// `opencode` panics on every rendered provider except opencode itself.
    fn present_full_auto() -> (String, PathBuf) {
        let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
        let harnesses = harnesses_in_workspace(&workspace);
        let rows = standard_setup_dirs(&workspace.join("setups"), &harnesses);
        rows.into_iter()
            .find(|(_, dir)| dir.file_name().is_some_and(|leaf| leaf == "full-auto"))
            .map_or_else(
                || panic!("no full-auto home among {harnesses:?}"),
                |(name, dir)| (name, dir.join(SETUP_PAYLOAD)),
            )
    }

    /// Catalog `home/` is the payload copied to `--target`. `launch` then
    /// exports that target as the product config home. Measuring a different
    /// directory must not be reported as the launched posture.
    #[test]
    fn effective_autonomy_is_the_launched_config_home_not_a_decoy() {
        let (harness, full_auto) = present_full_auto();
        let launched = scratch("launched-config-home");
        copy_tree(&full_auto, &launched);
        assert!(
            effective_autonomy(&harness, &launched).is_empty(),
            "copied {harness} full-auto home was not autonomous: {:?}",
            effective_autonomy(&harness, &launched)
        );

        let decoy = scratch("decoy-config-home");
        write_planted_ask(&decoy, &harness);
        let decoy_problems = effective_autonomy(&harness, &decoy);
        assert!(
            decoy_problems
                .iter()
                .any(|line| line.contains("still contains")),
            "decoy ask was not reported as leftover policy: {decoy_problems:?}"
        );
        assert!(
            effective_autonomy(&harness, &launched).is_empty(),
            "decoy taint leaked into the launched home"
        );

        write_planted_ask(&launched, &harness);
        let overwritten = effective_autonomy(&harness, &launched);
        assert!(
            overwritten
                .iter()
                .any(|line| line.contains("still contains")),
            "overwriting the launched policy file did not fail: {overwritten:?}"
        );
    }

    #[test]
    fn antigravity_settings_only_use_keys_measured_in_the_pin() {
        let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
        let harnesses = harnesses_in_workspace(&workspace);
        if !harnesses.iter().any(|name| name == "antigravity") {
            // Public tree for another product. The pin-key contract still
            // runs in authoring and in the antigravity public tree.
            return;
        }
        let rows = standard_setup_dirs(&workspace.join("setups"), &harnesses);
        let mut seen = 0;
        for (harness, variant_dir) in rows {
            if harness != "antigravity" {
                continue;
            }
            seen += 1;
            let path = variant_dir
                .join(SETUP_PAYLOAD)
                .join("antigravity-cli/settings.json");
            let value: serde_json::Value =
                serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
            let object = value.as_object().unwrap();
            if variant_dir.file_name().unwrap() != "minimal" {
                assert_eq!(
                    object.get("allowNonWorkspaceAccess"),
                    Some(&serde_json::Value::Bool(true)),
                    "{path:?} does not enable the setting read by Antigravity CLI 1.2.10"
                );
            }
            for key in object.keys() {
                assert!(
                    ANTIGRAVITY_MEASURED_SETTING_KEYS.contains(&key.as_str()),
                    "{path:?} writes unmeasured key {key}"
                );
            }
            assert!(
                !object.contains_key("artifactReviewPolicy"),
                "{path:?} wrote artifactReviewPolicy, which the 1.1.22 pin registry does not name"
            );
        }
        assert_eq!(
            seen,
            STANDARD_VARIANTS.len(),
            "expected {} antigravity variants, found {seen}",
            STANDARD_VARIANTS.len()
        );
    }
}