autumn-cli 0.9.0

CLI tool for the Autumn web framework
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
//! The curated plugin index (issue #1625).
//!
//! The index is a TOML file in this repository (`autumn-cli/plugin-index/`).
//! A maintainer reviews each listing in a pull request. The CLI embeds the
//! file, so `autumn plugin list` works offline and shows only listings that
//! were reviewed for this release.
//!
//! Each listing records the trust facts a consumer needs before install: the
//! supported `autumn-web` range, the last `autumn plugin-check` result, the
//! trust class, and the #1601 stability tier.

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

use serde::{Deserialize, Serialize};

use super::install::Compat;

/// The index schema this CLI reads.
pub const SCHEMA: u32 = 1;

/// The index that ships with this CLI.
pub const BUNDLED: &str = include_str!("../../plugin-index/index.toml");

/// Env var that points the CLI at a different index file.
pub const OVERRIDE_ENV: &str = "AUTUMN_PLUGIN_INDEX";

/// The label for a native plugin.
pub const FULL_TRUST_LABEL: &str = "full trust: native code";

/// The whole index file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PluginIndex {
    /// Schema version. Must be [`SCHEMA`].
    pub schema: u32,
    /// The listings, in `plugin list` order.
    #[serde(default, rename = "plugin")]
    pub plugins: Vec<Listing>,
}

/// Where a listed plugin comes from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ListingOrigin {
    /// A crate in this workspace, released in lockstep with `autumn-web`.
    FirstParty,
    /// A crate a third party publishes on crates.io.
    Community,
}

/// The #1601 plugin API tier a listing builds on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Tier {
    /// Only stable plugin surface.
    Stable,
    /// At least one experimental surface. It can break in any release.
    Experimental,
}

/// The trust class of a listing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Trust {
    /// A `Plugin`-trait crate. It gets the whole `AppBuilder`.
    Native,
    /// A #1609 sandboxed plugin. The capability manifest limits it.
    Sandboxed,
}

/// The state of a listing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Status {
    /// Verified against the current release.
    Listed,
    /// Failed re-verification. Shown with a flag; `add` refuses on the
    /// failed release.
    Incompatible,
    /// Failed re-verification on two different releases. Not shown.
    Delisted,
}

/// The result `autumn plugin-check` gave.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CheckOutcome {
    /// All checks passed.
    Pass,
    /// One or more checks failed.
    Fail,
    /// `plugin-check` does not apply (the crate is not a `Plugin`). First-party
    /// only; the install gate verifies it instead.
    Exempt,
}

/// The last conformance run for a listing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Conformance {
    /// The result.
    pub result: CheckOutcome,
    /// The `autumn-web` release the check ran against.
    pub autumn_web: String,
    /// The date of the run, `YYYY-MM-DD`.
    pub checked: String,
    /// Why the result is [`CheckOutcome::Exempt`]. Empty otherwise.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub reason: String,
}

/// The manifest's `[grants]` lists, as `autumn plugin inspect` prints them.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Grants {
    /// Hostnames `http-outbound` may call.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub hosts: Vec<String>,
    /// Logical tables `db` owns.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tables: Vec<String>,
    /// Job types `jobs` may enqueue.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub job_types: Vec<String>,
    /// Render slots `render` may fill.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub slots: Vec<String>,
}

impl Grants {
    /// Whether no list holds anything.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.hosts.is_empty()
            && self.tables.is_empty()
            && self.job_types.is_empty()
            && self.slots.is_empty()
    }
}

/// One plugin in the index.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Listing {
    /// crates.io name.
    pub name: String,
    /// One-line description.
    pub description: String,
    /// First-party or community.
    pub origin: ListingOrigin,
    /// Source repository, `https://`.
    pub repository: String,
    /// The plugin version that was verified.
    pub version: String,
    /// The supported `autumn-web` range (a Cargo version requirement).
    pub autumn_web: String,
    /// The #1601 tier.
    pub tier: Tier,
    /// The experimental surfaces the plugin declares. Empty for
    /// [`Tier::Stable`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub experimental_surfaces: Vec<String>,
    /// The trust class.
    pub trust: Trust,
    /// The manifest capabilities of a sandboxed plugin. Empty for native.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<String>,
    /// The routes a sandboxed plugin serves, as `METHOD /path` (the consent
    /// screen's form, implied `HEAD` included). A new one is authority, so
    /// a replacement artifact is compared with this. Sandboxed only.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub routes: Vec<String>,
    /// The reviewed `.autumn-plugin` artifact digest, as
    /// `autumn plugin inspect` prints it. Sandboxed only.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub artifact_sha256: String,
    /// What each sandboxed capability is scoped to. Sandboxed only.
    #[serde(default, skip_serializing_if = "Grants::is_empty")]
    pub grants: Grants,
    /// The per-request quotas the manifest declares, as `inspect` prints
    /// them. Sandboxed only.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub quotas: BTreeMap<String, u32>,
    /// The per-request resource limits the manifest declares (fuel, memory,
    /// body sizes, timeouts, concurrency). Sandboxed only.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub limits: BTreeMap<String, u64>,
    /// The listing state.
    pub status: Status,
    /// Why the listing is not [`Status::Listed`]. Empty otherwise.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub note: String,
    /// The route prefix `plugin-check` verifies. Empty for a plugin with no
    /// routes.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub prefix: String,
    /// The plugin mounts no routes: `plugin-check --no-routes`. An empty
    /// `prefix` alone does not say so.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub no_routes: bool,
    /// `PATH:DESCRIPTION` pairs for `plugin-check --sensitive-route`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sensitive_routes: Vec<String>,
    /// The last conformance run.
    pub conformance: Conformance,
}

/// Why an index could not be read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IndexError {
    /// The file could not be read.
    Io(String),
    /// The TOML did not parse into the schema.
    Toml(String),
    /// The schema version is not [`SCHEMA`].
    Schema(u32),
}

impl std::fmt::Display for IndexError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(msg) => write!(f, "cannot read the plugin index: {msg}"),
            Self::Toml(msg) => write!(f, "the plugin index is not valid: {msg}"),
            Self::Schema(found) => write!(
                f,
                "the plugin index uses schema {found}; this CLI reads schema {SCHEMA}"
            ),
        }
    }
}

impl std::error::Error for IndexError {}

/// One problem `check` found.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Finding {
    /// The listing name, or `index` for a file-level problem.
    pub plugin: String,
    /// What is wrong, and what to do.
    pub message: String,
}

/// Parse an index file.
///
/// # Errors
///
/// [`IndexError::Toml`] when the text does not match the schema, and
/// [`IndexError::Schema`] when the schema version is not [`SCHEMA`].
pub fn parse(src: &str) -> Result<PluginIndex, IndexError> {
    // Read the schema first, so a newer file gives a clear message rather
    // than a field error.
    #[derive(Deserialize)]
    struct Header {
        schema: u32,
    }
    let header: Header = toml::from_str(src).map_err(|e| IndexError::Toml(e.to_string()))?;
    if header.schema != SCHEMA {
        return Err(IndexError::Schema(header.schema));
    }
    toml::from_str(src).map_err(|e| IndexError::Toml(e.to_string()))
}

/// Largest index file the CLI reads.
pub const MAX_INDEX_BYTES: u64 = 1024 * 1024;

/// Escape characters that can drive or disguise terminal output.
#[must_use]
pub fn sanitize(text: &str) -> String {
    use std::fmt::Write as _;

    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        if is_unsafe_char(c) {
            let _ = write!(out, "\\u{{{:x}}}", u32::from(c));
        } else {
            out.push(c);
        }
    }
    out
}

/// Control, line-separator, format and default-ignorable characters: any a
/// terminal may reorder or render as nothing. The same set as the sandbox's
/// `is_display_reordering` (Unicode Cf, plus the full `Default_Ignorable_Code_Point`
/// property), which autumn-web keeps private.
#[must_use]
pub fn is_unsafe_char(c: char) -> bool {
    c.is_control()
        || matches!(
            c,
            // Format characters (Cf) that are not also default-ignorable.
            '\u{0600}'..='\u{0605}'
                | '\u{06DD}'
                | '\u{070F}'
                | '\u{0890}'..='\u{0891}'
                | '\u{08E2}'
                | '\u{110BD}'
                | '\u{110CD}'
                | '\u{13430}'..='\u{1343F}'
                | '\u{FFF9}'..='\u{FFFB}'
                // `Default_Ignorable_Code_Point`, in full.
                | '\u{00AD}'
                | '\u{034F}'
                | '\u{061C}'
                | '\u{115F}'..='\u{1160}'
                | '\u{17B4}'..='\u{17B5}'
                | '\u{180B}'..='\u{180F}'
                | '\u{200B}'..='\u{200F}'
                | '\u{2028}'..='\u{202E}'
                | '\u{2060}'..='\u{206F}'
                | '\u{3164}'
                | '\u{FE00}'..='\u{FE0F}'
                | '\u{FEFF}'
                | '\u{FFA0}'
                | '\u{FFF0}'..='\u{FFF8}'
                | '\u{1BCA0}'..='\u{1BCA3}'
                | '\u{1D173}'..='\u{1D17A}'
                | '\u{E0000}'..='\u{E0FFF}'
        )
}

/// The crates.io identity of a name: case and `-`/`_` do not count.
#[must_use]
pub fn canonical(name: &str) -> String {
    name.to_ascii_lowercase().replace('_', "-")
}

/// Where a loaded index came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
    /// The copy embedded in this CLI.
    Bundled,
    /// A file named by [`OVERRIDE_ENV`].
    Override(PathBuf),
}

/// A parsed index and its source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Loaded {
    /// The index.
    pub index: PluginIndex,
    /// Where it came from.
    pub source: Source,
}

/// Load the index from `path`, or the bundled copy when `path` is `None`.
///
/// # Errors
///
/// Any [`IndexError`]. An override that fails is an error, never a silent
/// fall back to the bundled copy.
pub fn load(path: Option<&Path>) -> Result<Loaded, IndexError> {
    let Some(path) = path else {
        return Ok(Loaded {
            index: parse(BUNDLED)?,
            source: Source::Bundled,
        });
    };
    let src = read_bounded(path)?;
    Ok(Loaded {
        index: parse(&src)?,
        source: Source::Override(path.to_path_buf()),
    })
}

/// Read a regular file of at most [`MAX_INDEX_BYTES`].
fn read_bounded(path: &Path) -> Result<String, IndexError> {
    use std::io::Read as _;

    let io = |e: &dyn std::fmt::Display| IndexError::Io(format!("{}: {e}", path.display()));
    let file = std::fs::File::open(path).map_err(|e| io(&e))?;
    let meta = file.metadata().map_err(|e| io(&e))?;
    if !meta.is_file() {
        return Err(io(&"not a regular file"));
    }
    let mut bytes = Vec::new();
    file.take(MAX_INDEX_BYTES + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| io(&e))?;
    if bytes.len() as u64 > MAX_INDEX_BYTES {
        return Err(io(&format!("larger than {MAX_INDEX_BYTES} bytes")));
    }
    String::from_utf8(bytes).map_err(|_| io(&"not UTF-8"))
}

/// Load the index named by [`OVERRIDE_ENV`], or the bundled copy.
///
/// # Errors
///
/// Any [`IndexError`] from [`load`].
pub fn load_from_env() -> Result<Loaded, IndexError> {
    let path = std::env::var_os(OVERRIDE_ENV)
        .filter(|value| !value.is_empty())
        .map(PathBuf::from);
    load(path.as_deref())
}

impl PluginIndex {
    /// The listing for `name`, in any state.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&Listing> {
        let name = canonical(name);
        self.plugins
            .iter()
            .find(|listing| canonical(&listing.name) == name)
    }

    /// The listings `plugin list` shows: all but [`Status::Delisted`].
    pub fn visible(&self) -> impl Iterator<Item = &Listing> {
        self.plugins
            .iter()
            .filter(|listing| listing.status != Status::Delisted)
    }
}

impl Listing {
    /// The trust line shown at discovery and before install.
    #[must_use]
    pub fn trust_label(&self) -> String {
        match self.trust {
            Trust::Native => FULL_TRUST_LABEL.to_owned(),
            Trust::Sandboxed => {
                let mut label = format!(
                    "sandboxed: capability manifest grants {}",
                    self.capabilities.join(", ")
                );
                let scopes: Vec<String> = [
                    ("hosts", &self.grants.hosts),
                    ("tables", &self.grants.tables),
                    ("job types", &self.grants.job_types),
                    ("render slots", &self.grants.slots),
                ]
                .into_iter()
                .filter(|(_, list)| !list.is_empty())
                .map(|(what, list)| format!("{what} {}", list.join(", ")))
                .collect();
                if !scopes.is_empty() {
                    label.push_str("; scoped to ");
                    label.push_str(&scopes.join("; "));
                }
                // The routes it serves are authority a reviewer consents to.
                if !self.routes.is_empty() {
                    label.push_str("; serves ");
                    label.push_str(&self.routes.join(", "));
                }
                // Defaults go unsaid; a changed ceiling is authority.
                let defaults = autumn_web::plugin_sandbox::CapabilityQuotas::default();
                let changed: Vec<String> = defaults
                    .fields()
                    .into_iter()
                    .filter_map(|(key, default)| {
                        self.quotas
                            .get(key)
                            .filter(|v| **v != default)
                            .map(|v| format!("{key}={v}"))
                    })
                    .collect();
                if !changed.is_empty() {
                    label.push_str("; quotas ");
                    label.push_str(&changed.join(", "));
                }
                let defaults = autumn_web::plugin_sandbox::ResourceLimits::default();
                let changed: Vec<String> = defaults
                    .fields()
                    .into_iter()
                    .filter_map(|(key, default)| {
                        self.limits
                            .get(key)
                            .filter(|v| u128::from(**v) != default)
                            .map(|v| format!("{key}={v}"))
                    })
                    .collect();
                if !changed.is_empty() {
                    label.push_str("; limits ");
                    label.push_str(&changed.join(", "));
                }
                label
            }
        }
    }

    /// Whether this listing works with an app on `app` (the app's
    /// `autumn-web` requirement, e.g. `0.7.0`).
    #[must_use]
    pub fn compat(&self, app: &str) -> Compat {
        let Some(low) = concrete(app) else {
            // A range (`>=0.7, <0.8`, `0.7.*`) is compatible when every
            // version it admits is inside the listing's range. A flag cannot
            // be ruled out for a range, so a flagged listing stays unknown.
            return if self.status != Status::Incompatible && range_within(app, &self.autumn_web) {
                Compat::Compatible
            } else {
                Compat::Unknown
            };
        };
        // A flag wins over the declared range: the range is a claim, the
        // failed run is evidence.
        if self.flag_applies(&low.to_string()) {
            return Compat::Incompatible;
        }
        let Ok(req) = semver::VersionReq::parse(&self.autumn_web) else {
            return Compat::Unknown;
        };
        if !req.matches(&low) {
            return Compat::Incompatible;
        }
        // An unresolved requirement (`^0.7.0`) may resolve to any release of
        // its series: compatible only when the range admits all of it.
        if let Some(top) = requirement_top(app, &low)
            && !req.matches(&top)
        {
            return Compat::Unknown;
        }
        Compat::Compatible
    }

    /// Whether a failed re-verification applies to an app on `app`: the
    /// listing is flagged, and `app` is on the failed series or later. A
    /// flagged sandboxed listing applies to every app.
    #[must_use]
    pub fn flag_applies(&self, app: &str) -> bool {
        // A sandboxed artifact is not tied to an `autumn-web` series.
        if self.status == Status::Incompatible && self.trust == Trust::Sandboxed {
            return true;
        }
        self.status == Status::Incompatible
            && concrete(app)
                .zip(concrete(&self.conformance.autumn_web))
                .is_some_and(|(app, failed)| {
                    // The start of the failed series: `0.x` is its own series,
                    // a later major is one series from `x.0.0`.
                    let series = if failed.major == 0 {
                        semver::Version::new(0, failed.minor, 0)
                    } else {
                        semver::Version::new(failed.major, 0, 0)
                    };
                    app >= series
                })
    }

    /// Whether the last conformance run covers the `autumn-web` series of
    /// `app`.
    #[must_use]
    pub fn verified_for(&self, app: &str) -> bool {
        match (concrete(app), concrete(&self.conformance.autumn_web)) {
            (Some(app), Some(checked)) => same_series(&app, &checked),
            _ => false,
        }
    }
}

/// Check each listing against the admission rules.
#[must_use]
pub fn validate(index: &PluginIndex) -> Vec<Finding> {
    let mut findings = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for listing in &index.plugins {
        let mut add = |message: String| {
            findings.push(Finding {
                plugin: listing.name.clone(),
                message,
            });
        };
        if !seen.insert(canonical(&listing.name)) {
            add("listed more than once".to_owned());
        }
        for message in admission_problems(listing) {
            add(message);
        }
    }
    findings
}

/// Every admission rule one listing breaks.
fn admission_problems(listing: &Listing) -> Vec<String> {
    let mut out = Vec::new();
    check_text(listing, &mut out);
    check_identity(listing, &mut out);
    check_versions(listing, &mut out);
    check_conformance(listing, &mut out);
    check_tier(listing, &mut out);
    check_trust(listing, &mut out);
    check_routes(listing, &mut out);
    out
}

/// Text fields are printed to a terminal, so control characters are refused.
fn check_text(listing: &Listing, out: &mut Vec<String>) {
    let fields = [
        ("name", listing.name.as_str()),
        ("description", listing.description.as_str()),
        ("repository", listing.repository.as_str()),
        ("note", listing.note.as_str()),
        ("prefix", listing.prefix.as_str()),
        ("conformance.reason", listing.conformance.reason.as_str()),
    ];
    let lists = listing
        .sensitive_routes
        .iter()
        .map(|route| ("sensitive_routes", route.as_str()))
        .chain(
            listing
                .experimental_surfaces
                .iter()
                .map(|s| ("experimental_surfaces", s.as_str())),
        )
        .chain(
            listing
                .capabilities
                .iter()
                .map(|c| ("capabilities", c.as_str())),
        )
        .chain(listing.routes.iter().map(|r| ("routes", r.as_str())))
        .chain(
            [
                &listing.grants.hosts,
                &listing.grants.tables,
                &listing.grants.job_types,
                &listing.grants.slots,
            ]
            .into_iter()
            .flatten()
            .map(|g| ("grants", g.as_str())),
        );
    for (field, value) in fields.into_iter().chain(lists) {
        if value.chars().any(is_unsafe_char) {
            out.push(format!("`{field}` holds a control character"));
        }
    }
    if listing.description.trim().is_empty() {
        out.push("`description` is empty".to_owned());
    }
    if !listing.repository.starts_with("https://") {
        out.push("`repository` must be an https:// URL".to_owned());
    }
}

fn check_identity(listing: &Listing, out: &mut Vec<String>) {
    match listing.origin {
        ListingOrigin::FirstParty if super::catalog::lookup(&listing.name).is_none() => {
            out.push("origin is first-party, but the CLI catalog has no such crate".to_owned());
        }
        ListingOrigin::Community if !super::catalog::is_community_name(&listing.name) => {
            out.push(format!(
                "a community name must be `{}<name>`",
                super::catalog::COMMUNITY_PREFIX
            ));
        }
        ListingOrigin::FirstParty | ListingOrigin::Community => {}
    }
}

fn check_versions(listing: &Listing, out: &mut Vec<String>) {
    if semver::Version::parse(&listing.version).is_err() {
        out.push(format!(
            "`version` {:?} is not a semver version",
            listing.version
        ));
    }
    match semver::VersionReq::parse(&listing.autumn_web) {
        Err(_) => out.push(format!(
            "`autumn_web` {:?} is not a Cargo version requirement; declare the supported range",
            listing.autumn_web
        )),
        // A range with no upper bound claims releases nobody has checked.
        Ok(req) if req.matches(&semver::Version::new(u64::from(u32::MAX), 0, 0)) => {
            out.push(format!(
                "`autumn_web` {:?} has no upper bound; name the series you verified",
                listing.autumn_web
            ));
        }
        Ok(_) => {}
    }
    if semver::Version::parse(&listing.conformance.autumn_web).is_err() {
        out.push(format!(
            "`conformance.autumn_web` {:?} is not a semver version",
            listing.conformance.autumn_web
        ));
    }
    if chrono::NaiveDate::parse_from_str(&listing.conformance.checked, "%Y-%m-%d").is_err() {
        out.push(format!(
            "`conformance.checked` {:?} is not a YYYY-MM-DD date",
            listing.conformance.checked
        ));
    }
}

fn check_conformance(listing: &Listing, out: &mut Vec<String>) {
    let result = listing.conformance.result;
    match (listing.status, result) {
        (Status::Listed, CheckOutcome::Fail) => {
            out.push("status is listed, but the last `autumn plugin-check` run failed".to_owned());
        }
        (Status::Incompatible, CheckOutcome::Pass | CheckOutcome::Exempt) => {
            out.push(
                "status is incompatible, but the last conformance run did not fail".to_owned(),
            );
        }
        // Only `record` delists, after a second failure. A delisted entry is
        // hidden and never re-verified, so a passing one would vanish unseen.
        (Status::Delisted, CheckOutcome::Pass | CheckOutcome::Exempt) => {
            out.push("status is delisted, but the last conformance run did not fail".to_owned());
        }
        _ => {}
    }
    if listing.status != Status::Listed && listing.note.trim().is_empty() {
        out.push("a flagged or delisted listing needs a `note` that says why".to_owned());
    }
    if result == CheckOutcome::Exempt {
        if listing.origin != ListingOrigin::FirstParty {
            out.push("only a first-party listing can be exempt from plugin-check".to_owned());
        }
        if listing.conformance.reason.trim().is_empty() {
            out.push("an exempt result needs a `conformance.reason`".to_owned());
        }
    }
    // Exempt, or a failure that kept its exemption: the catalog, not the
    // listing, says whether the crate is a `Plugin` plugin-check can run.
    let exempt_class =
        result == CheckOutcome::Exempt || !listing.conformance.reason.trim().is_empty();
    if exempt_class && !is_non_plugin(listing) {
        out.push(
            "only a first-party crate that is not a `Plugin` (the catalog mounts it with \
             something other than `.plugin(`) can be exempt from plugin-check"
                .to_owned(),
        );
    }
}

/// Whether the catalog mounts this first-party crate through something other
/// than `.plugin(` (`autumn-storage-s3`: `.with_blob_store(`), so
/// `plugin-check` has no `Plugin` to check.
fn is_non_plugin(listing: &Listing) -> bool {
    listing.origin == ListingOrigin::FirstParty
        && super::catalog::lookup(&listing.name).is_some_and(|entry| entry.mount_call != ".plugin(")
}

fn check_tier(listing: &Listing, out: &mut Vec<String>) {
    use autumn_web::plugin_contract::{SurfaceTier, surface};

    match (listing.tier, listing.experimental_surfaces.is_empty()) {
        (Tier::Experimental, true) => {
            out.push("tier is experimental, but `experimental_surfaces` is empty".to_owned());
        }
        (Tier::Stable, false) => out.push(
            "`experimental_surfaces` is not empty, so the tier must be experimental".to_owned(),
        ),
        _ => {}
    }
    for name in &listing.experimental_surfaces {
        match surface(name) {
            Some(found) if found.tier == SurfaceTier::Experimental => {}
            Some(_) => out.push(format!("`{name}` is a stable surface, not experimental")),
            None => out.push(format!("`{name}` is not a known plugin surface")),
        }
    }
}

fn check_routes(listing: &Listing, out: &mut Vec<String>) {
    if listing.no_routes && !listing.prefix.is_empty() {
        out.push("`no_routes` and a `prefix` contradict each other".to_owned());
    }
    // plugin-check runs with `--prefix` or `--no-routes`; with neither, no
    // prefix constraint would ever be evaluated.
    if listing.trust == Trust::Native
        && !is_non_plugin(listing)
        && listing.prefix.is_empty()
        && !listing.no_routes
    {
        out.push(
            "a native plugin listing needs a `prefix`, or `no_routes = true` for one that mounts \
             no routes"
                .to_owned(),
        );
    }
}

fn check_trust(listing: &Listing, out: &mut Vec<String>) {
    use autumn_web::plugin_sandbox::SandboxCapability;

    match listing.trust {
        Trust::Native if !listing.capabilities.is_empty() => out.push(
            "a native plugin has full trust; remove `capabilities` or set trust to sandboxed"
                .to_owned(),
        ),
        Trust::Sandboxed if listing.capabilities.is_empty() => {
            out.push("a sandboxed listing must copy `capabilities` from its manifest".to_owned());
        }
        Trust::Native | Trust::Sandboxed => {}
    }
    if listing.trust == Trust::Native && !listing.routes.is_empty() {
        out.push(
            "`routes` records a sandboxed manifest; a native plugin's routes are checked by \
             `plugin-check`"
                .to_owned(),
        );
    }
    let digest = &listing.artifact_sha256;
    match listing.trust {
        Trust::Sandboxed
            if digest.len() != 64 || !digest.chars().all(|c| c.is_ascii_hexdigit()) =>
        {
            out.push(
                "a sandboxed listing must record `artifact_sha256` from `autumn plugin inspect`"
                    .to_owned(),
            );
        }
        Trust::Native if !digest.is_empty() => {
            out.push("`artifact_sha256` is for a sandboxed listing only".to_owned());
        }
        Trust::Native if !listing.grants.is_empty() => {
            out.push("`grants` is for a sandboxed listing only".to_owned());
        }
        Trust::Native if !listing.quotas.is_empty() => {
            out.push("`quotas` is for a sandboxed listing only".to_owned());
        }
        Trust::Native if !listing.limits.is_empty() => {
            out.push("`limits` is for a sandboxed listing only".to_owned());
        }
        Trust::Native | Trust::Sandboxed => {}
    }
    let known = autumn_web::plugin_sandbox::CapabilityQuotas::default().fields();
    for key in listing.quotas.keys() {
        if !known.iter().any(|(k, _)| k == key) {
            out.push(format!("`{key}` is not a sandbox quota"));
        }
    }
    let sandboxed = listing.trust == Trust::Sandboxed;
    // A sandboxed listing records the whole authority `inspect` reported:
    // a missing ceiling would publish as unknown, not as approved.
    let missing: Vec<&str> = known
        .iter()
        .filter(|(k, _)| sandboxed && !listing.quotas.contains_key(*k))
        .map(|(k, _)| *k)
        .collect();
    if !missing.is_empty() {
        out.push(format!("`quotas` is missing {}", missing.join(", ")));
    }
    let known = autumn_web::plugin_sandbox::ResourceLimits::default().fields();
    for key in listing.limits.keys() {
        if !known.iter().any(|(k, _)| k == key) {
            out.push(format!("`{key}` is not a sandbox resource limit"));
        }
    }
    let missing: Vec<&str> = known
        .iter()
        .filter(|(k, _)| sandboxed && !listing.limits.contains_key(*k))
        .map(|(k, _)| *k)
        .collect();
    if !missing.is_empty() {
        out.push(format!("`limits` is missing {}", missing.join(", ")));
    }
    for name in &listing.capabilities {
        if !SandboxCapability::ALL.iter().any(|c| c.as_str() == name) {
            out.push(format!("`{name}` is not a sandbox capability"));
        }
    }
}

/// Check that each live listing was verified against `against`, the current
/// `autumn-web` release.
#[must_use]
pub fn staleness(index: &PluginIndex, against: &str) -> Vec<Finding> {
    let mut findings = Vec::new();
    for listing in &index.plugins {
        let mut add = |message: String| {
            findings.push(Finding {
                plugin: listing.name.clone(),
                message,
            });
        };
        let checked = &listing.conformance.autumn_web;
        match listing.status {
            Status::Delisted => continue,
            Status::Incompatible => {
                if checked != against {
                    add(format!(
                        "flagged since autumn-web {checked}; re-verify against {against} to \
                         relist it, or delist it"
                    ));
                }
                continue;
            }
            Status::Listed => {}
        }
        if checked != against {
            add(format!(
                "last verified against autumn-web {checked}; re-verify against {against}"
            ));
        }
        // An RC of a series is that series, as `plugin_contract::evaluate`
        // treats it: match with the prerelease stripped.
        let excluded = semver::VersionReq::parse(&listing.autumn_web)
            .ok()
            .zip(semver::Version::parse(against).ok())
            .is_some_and(|(req, version)| {
                !req.matches(&semver::Version::new(
                    version.major,
                    version.minor,
                    version.patch,
                ))
            });
        if excluded {
            add(format!(
                "its range `{}` excludes autumn-web {against}; flag it incompatible or widen \
                 the range",
                listing.autumn_web
            ));
        }
        if listing.origin == ListingOrigin::FirstParty && listing.version != against {
            add(format!(
                "first-party version {} is not the release {against}",
                listing.version
            ));
        }
    }
    findings
}

/// Read a version or a simple requirement (`0.7.0`, `^0.7`, `=0.7.2`) as a
/// concrete version. `None` for a range such as `>=0.6`.
fn concrete(version: &str) -> Option<semver::Version> {
    // A full version keeps its prerelease: `0.7.0-alpha.1` is outside `0.7`,
    // and reading it as `0.7.0` would admit it.
    let full = version.trim().trim_start_matches(['=', '^', '~', ' ']);
    semver::Version::parse(full)
        .ok()
        .or_else(|| {
            super::install::parse_version(version)
                .map(|(major, minor, patch)| semver::Version::new(major, minor, patch))
        })
        // A major alone (`^1`, `~1`) starts at `major.0.0`; `requirement_top`
        // bounds the rest.
        .or_else(|| {
            full.parse()
                .ok()
                .map(|major| semver::Version::new(major, 0, 0))
        })
}

/// The versions a requirement admits, as `[low, high)`; `high` is `None`
/// when unbounded. Cargo's rules for each operator, intersected across the
/// comparators. `None` for an unparsable or empty requirement. Prereleases
/// are not modelled: a requirement without one never resolves to one.
fn req_interval(req: &str) -> Option<(semver::Version, Option<semver::Version>)> {
    use semver::{Op, Version};
    let req = semver::VersionReq::parse(req).ok()?;
    let mut low = Version::new(0, 0, 0);
    let mut high: Option<Version> = None;
    for c in &req.comparators {
        // A prerelease bound admits prereleases this model does not order
        // against a stable range: fail closed.
        if !c.pre.is_empty() {
            return None;
        }
        let (major, minor, patch) = (c.major, c.minor, c.patch);
        let base = Version::new(major, minor.unwrap_or(0), patch.unwrap_or(0));
        // The first version after everything the named parts cover.
        let past = match (minor, patch) {
            (Some(minor), Some(patch)) => Version::new(major, minor, patch + 1),
            (Some(minor), None) => Version::new(major, minor + 1, 0),
            (None, _) => Version::new(major + 1, 0, 0),
        };
        let caret_top = match (major, minor, patch) {
            (0, None, _) => Version::new(1, 0, 0),
            (0, Some(0), None) => Version::new(0, 1, 0),
            (0, Some(0), Some(patch)) => Version::new(0, 0, patch + 1),
            (0, Some(minor), _) => Version::new(0, minor + 1, 0),
            _ => Version::new(major + 1, 0, 0),
        };
        let tilde_top = minor.map_or_else(
            || Version::new(major + 1, 0, 0),
            |minor| Version::new(major, minor + 1, 0),
        );
        let (lo, hi) = match c.op {
            Op::Exact | Op::Wildcard => (base, Some(past)),
            Op::Greater => (past, None),
            Op::GreaterEq => (base, None),
            Op::Less => (Version::new(0, 0, 0), Some(base)),
            Op::LessEq => (Version::new(0, 0, 0), Some(past)),
            Op::Tilde => (base, Some(tilde_top)),
            Op::Caret => (base, Some(caret_top)),
            _ => return None,
        };
        low = low.max(lo);
        high = match (high, hi) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (a, b) => a.or(b),
        };
    }
    high.as_ref()
        .is_none_or(|high| low < *high)
        .then_some((low, high))
}

/// Whether every version the requirement `app` admits is admitted by
/// `range`.
fn range_within(app: &str, range: &str) -> bool {
    let (Some((app_low, app_high)), Some((low, high))) = (req_interval(app), req_interval(range))
    else {
        return false;
    };
    let high_ok = match (&app_high, &high) {
        (_, None) => true,
        (None, Some(_)) => false,
        (Some(app_high), Some(high)) => app_high <= high,
    };
    app_low >= low && high_ok
}

/// The highest version an unresolved `^`/`~` requirement `app` (lowest
/// version `low`) admits; `None` for a concrete version. A caret spans the
/// compatibility series; a tilde stays within its minor (`~1.2`, `~0.7.3`),
/// or its major when it names only one (`~1`).
fn requirement_top(app: &str, low: &semver::Version) -> Option<semver::Version> {
    let app = app.trim_start();
    if let Some(rest) = app.strip_prefix('~') {
        return Some(if rest.trim().split('.').count() == 1 {
            semver::Version::new(low.major, u64::MAX, u64::MAX)
        } else {
            semver::Version::new(low.major, low.minor, u64::MAX)
        });
    }
    // `^0` (a major alone) admits every 0.x, not just 0.0.x.
    let rest = app.strip_prefix('^')?;
    Some(if rest.trim().split('.').count() == 1 {
        semver::Version::new(low.major, u64::MAX, u64::MAX)
    } else {
        series_top(low)
    })
}

/// The highest version in `v`'s compatibility series.
const fn series_top(v: &semver::Version) -> semver::Version {
    if v.major == 0 {
        semver::Version::new(0, v.minor, u64::MAX)
    } else {
        semver::Version::new(v.major, u64::MAX, u64::MAX)
    }
}

/// Whether two versions share a compatibility series: `MAJOR.MINOR` below
/// 1.0, `MAJOR` from 1.0 on.
const fn same_series(a: &semver::Version, b: &semver::Version) -> bool {
    if a.major == 0 || b.major == 0 {
        a.major == b.major && a.minor == b.minor
    } else {
        a.major == b.major
    }
}

/// [`validate`] and [`staleness`] together: the gate CI runs.
#[must_use]
pub fn check(index: &PluginIndex, against: &str) -> Vec<Finding> {
    let mut findings = validate(index);
    findings.extend(staleness(index, against));
    findings
}

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

    const RELEASE: &str = env!("CARGO_PKG_VERSION");

    fn native(name: &str, origin: ListingOrigin) -> Listing {
        Listing {
            name: name.to_owned(),
            description: "A plugin".to_owned(),
            origin,
            repository: "https://example.com/repo".to_owned(),
            version: "0.7.0".to_owned(),
            autumn_web: "0.7".to_owned(),
            tier: Tier::Stable,
            experimental_surfaces: vec![],
            trust: Trust::Native,
            capabilities: vec![],
            routes: vec![],
            artifact_sha256: String::new(),
            grants: Grants::default(),
            quotas: BTreeMap::new(),
            limits: BTreeMap::new(),
            status: Status::Listed,
            note: String::new(),
            prefix: "/audit".to_owned(),
            no_routes: false,
            sensitive_routes: vec![],
            conformance: Conformance {
                result: CheckOutcome::Pass,
                autumn_web: "0.7.0".to_owned(),
                checked: "2026-09-27".to_owned(),
                reason: String::new(),
            },
        }
    }

    fn community() -> Listing {
        native("autumn-plugin-audit", ListingOrigin::Community)
    }

    fn index_of(plugins: Vec<Listing>) -> PluginIndex {
        PluginIndex {
            schema: SCHEMA,
            plugins,
        }
    }

    fn messages(findings: &[Finding]) -> String {
        findings
            .iter()
            .map(|f| format!("{}: {}", f.plugin, f.message))
            .collect::<Vec<_>>()
            .join("\n")
    }

    // ── The bundled index ───────────────────────────────────────────────

    /// AC 1: the bundled index parses and passes its own gate against this
    /// release. A version bump fails here until each listing is re-verified.
    #[test]
    fn the_bundled_index_passes_the_gate_for_this_release() {
        let index = parse(BUNDLED).expect("bundled index parses");
        let findings = check(&index, RELEASE);
        assert!(findings.is_empty(), "{}", messages(&findings));
    }

    /// AC 1: every first-party plugin the CLI can install has a listing.
    #[test]
    fn the_bundled_index_lists_every_first_party_plugin() {
        let index = parse(BUNDLED).expect("bundled index parses");
        for entry in super::super::catalog::FIRST_PARTY {
            let listing = index
                .get(entry.crate_name)
                .unwrap_or_else(|| panic!("{} has no listing", entry.crate_name));
            // Any status: `record` may commit a failed re-verification as
            // `incompatible` or `delisted`, and the gate above judges that.
            assert_eq!(listing.origin, ListingOrigin::FirstParty);
            assert_eq!(
                listing.description, entry.summary,
                "{} description drifted from the catalog",
                entry.crate_name
            );
        }
    }

    /// AC 1 names these three by name.
    #[test]
    fn the_bundled_index_seeds_the_three_named_plugins() {
        let index = parse(BUNDLED).expect("bundled index parses");
        for name in [
            "autumn-admin-plugin",
            "autumn-cache-redis",
            "autumn-storage-s3",
        ] {
            assert!(index.get(name).is_some(), "{name}");
        }
    }

    /// AC 1: every listing carries a trust class; every native one says so.
    #[test]
    fn every_bundled_listing_has_a_trust_label() {
        let index = parse(BUNDLED).expect("bundled index parses");
        for listing in &index.plugins {
            let label = listing.trust_label();
            assert!(!label.is_empty(), "{}", listing.name);
            if listing.trust == Trust::Native {
                assert_eq!(label, FULL_TRUST_LABEL);
            }
        }
    }

    // ── Parse ───────────────────────────────────────────────────────────

    #[test]
    fn parse_rejects_an_unknown_schema() {
        let err = parse("schema = 2\n").unwrap_err();
        assert_eq!(err, IndexError::Schema(2));
    }

    #[test]
    fn parse_rejects_an_unknown_field_value() {
        let src = BUNDLED.replacen("trust = \"native\"", "trust = \"root\"", 1);
        assert!(matches!(parse(&src), Err(IndexError::Toml(_))));
    }

    /// A mistyped key (`experimental_surface`) must not drop a trust fact
    /// without a word.
    #[test]
    fn parse_rejects_an_unknown_key() {
        let src = BUNDLED.replacen(
            "tier = \"stable\"",
            "tier = \"stable\"\nexperimental_surface = [\"x\"]",
            1,
        );
        assert!(matches!(parse(&src), Err(IndexError::Toml(_))));
        let src = BUNDLED.replacen(
            "result = \"pass\"",
            "result = \"pass\"\nverdict = \"ok\"",
            1,
        );
        assert!(matches!(parse(&src), Err(IndexError::Toml(_))));
    }

    #[test]
    fn parse_accepts_an_empty_index() {
        let index = parse("schema = 1\n").expect("empty index");
        assert!(index.plugins.is_empty());
    }

    // ── Load ────────────────────────────────────────────────────────────

    #[test]
    fn load_without_a_path_uses_the_bundled_copy() {
        let loaded = load(None).expect("bundled");
        assert_eq!(loaded.source, Source::Bundled);
        assert!(!loaded.index.plugins.is_empty());
    }

    #[test]
    fn load_reads_an_override_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("index.toml");
        std::fs::write(&path, "schema = 1\n").expect("write");
        let loaded = load(Some(&path)).expect("override");
        assert_eq!(loaded.source, Source::Override(path));
        assert!(loaded.index.plugins.is_empty());
    }

    /// A broken override is an error, not a silent fall back.
    #[test]
    fn load_fails_on_a_missing_override() {
        let err = load(Some(Path::new("/nonexistent/autumn-index.toml"))).unwrap_err();
        assert!(matches!(err, IndexError::Io(_)), "{err:?}");
    }

    // ── Lookup ──────────────────────────────────────────────────────────

    #[test]
    fn visible_hides_delisted_listings() {
        let mut gone = community();
        gone.name = "autumn-plugin-gone".to_owned();
        gone.status = Status::Delisted;
        let index = index_of(vec![community(), gone]);
        let names: Vec<&str> = index.visible().map(|l| l.name.as_str()).collect();
        assert_eq!(names, ["autumn-plugin-audit"]);
        assert!(index.get("autumn-plugin-gone").is_some());
    }

    // ── Trust label ─────────────────────────────────────────────────────

    #[test]
    fn a_sandboxed_label_names_its_capabilities() {
        let mut listing = community();
        listing.trust = Trust::Sandboxed;
        listing.capabilities = vec!["http-request".to_owned(), "kv".to_owned()];
        assert_eq!(
            listing.trust_label(),
            "sandboxed: capability manifest grants http-request, kv"
        );
    }

    // ── Compat ──────────────────────────────────────────────────────────

    /// A bounded range the listing's range contains is compatible: every
    /// version the app can resolve was covered. A wider one, or one next to
    /// a flag, stays unknown.
    #[test]
    fn a_range_inside_the_listing_is_compatible() {
        let listing = community();
        assert_eq!(listing.autumn_web, "0.7");
        for app in [">=0.7, <0.8", "0.7.*", ">=0.7.2, <0.7.9", ">0.7.0, <=0.7.5"] {
            assert_eq!(listing.compat(app), Compat::Compatible, "{app}");
        }
        for app in [">=0.7, <0.9", ">=0.6, <0.8", ">=0.7", "*", "0.*"] {
            assert_eq!(listing.compat(app), Compat::Unknown, "{app}");
        }
        let mut flagged = community();
        flagged.status = Status::Incompatible;
        assert_eq!(flagged.compat(">=0.7, <0.8"), Compat::Unknown);
        // A prerelease-only range is not inside a stable one.
        assert_eq!(
            listing.compat(">=0.7.0-alpha.1, <=0.7.0-alpha.5"),
            Compat::Unknown
        );
    }

    #[test]
    fn req_interval_follows_cargo() {
        let v = |major, minor, patch| semver::Version::new(major, minor, patch);
        for (req, low, high) in [
            ("0.7", v(0, 7, 0), Some(v(0, 8, 0))),
            ("^0.0.3", v(0, 0, 3), Some(v(0, 0, 4))),
            ("~1.2", v(1, 2, 0), Some(v(1, 3, 0))),
            ("=0.7", v(0, 7, 0), Some(v(0, 8, 0))),
            ("0.7.*", v(0, 7, 0), Some(v(0, 8, 0))),
            (">0.7", v(0, 8, 0), None),
            (">0.7.2, <=0.7.5", v(0, 7, 3), Some(v(0, 7, 6))),
            ("*", v(0, 0, 0), None),
        ] {
            assert_eq!(req_interval(req), Some((low, high)), "{req}");
        }
        assert_eq!(req_interval(">=0.8, <0.7"), None);
    }

    #[test]
    fn compat_follows_the_declared_range() {
        let listing = community();
        assert_eq!(listing.compat("0.7.0"), Compat::Compatible);
        assert_eq!(listing.compat("^0.7.2"), Compat::Compatible);
        assert_eq!(listing.compat("0.6.0"), Compat::Incompatible);
        assert_eq!(listing.compat("0.8.0"), Compat::Incompatible);
        assert_eq!(listing.compat(">=0.6"), Compat::Unknown);
        // A tilde stays within its minor: `~1.2` fits a `~1.2` listing.
        let mut one_two = community();
        one_two.autumn_web = "~1.2".to_owned();
        assert_eq!(one_two.compat("~1.2"), Compat::Compatible);
        assert_eq!(one_two.compat("^1.2"), Compat::Unknown);
        // A major alone is a range too, from `major.0.0`.
        let one = Listing {
            autumn_web: "1".to_owned(),
            ..community()
        };
        assert_eq!(one.compat("^1"), Compat::Compatible);
        assert_eq!(one.compat("~1"), Compat::Compatible);
        // `^0` admits every 0.x: a listing below 0.8 does not cover it.
        let below = Listing {
            autumn_web: ">=0, <0.8".to_owned(),
            ..community()
        };
        assert_eq!(below.compat("^0"), Compat::Unknown);
        // `~1` starts below `~1.2`: refused, like any range whose floor is
        // outside the listing.
        assert_eq!(one_two.compat("~1"), Compat::Incompatible);
        // A prerelease is not in the stable range Cargo matches it against.
        assert_eq!(listing.compat("0.7.0-alpha.1"), Compat::Incompatible);
    }

    /// AC 4: a flagged listing is refused on the release it failed on and
    /// on later ones, even when its declared range still matches.
    #[test]
    fn a_flagged_listing_is_incompatible_from_the_failed_release_on() {
        let mut listing = community();
        listing.autumn_web = ">=0.6".to_owned();
        listing.status = Status::Incompatible;
        listing.conformance.result = CheckOutcome::Fail;
        listing.conformance.autumn_web = "0.7.0".to_owned();
        assert_eq!(listing.compat("0.7.1"), Compat::Incompatible);
        assert_eq!(listing.compat("0.8.0"), Compat::Incompatible);
        assert_ne!(listing.compat("0.6.0"), Compat::Incompatible);
    }

    #[test]
    fn verified_for_compares_the_series() {
        let listing = community();
        assert!(listing.verified_for("0.7.3"));
        assert!(!listing.verified_for("0.8.0"));
        assert!(!listing.verified_for("not a version"));
    }

    // ── Validate: admission rules ───────────────────────────────────────

    #[test]
    fn a_well_formed_index_has_no_findings() {
        let index = index_of(vec![community()]);
        assert!(
            validate(&index).is_empty(),
            "{}",
            messages(&validate(&index))
        );
    }

    /// AC 3: listing is granted only with a passing conformance run.
    #[test]
    fn a_listed_plugin_must_pass_conformance() {
        let mut listing = community();
        listing.conformance.result = CheckOutcome::Fail;
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("plugin-check"), "{text}");
    }

    /// AC 3: listing is granted only with a declared, parseable range.
    #[test]
    fn a_listing_must_declare_a_parseable_range() {
        let mut listing = community();
        listing.autumn_web = "zero point seven".to_owned();
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("autumn_web"), "{text}");
    }

    #[test]
    fn only_first_party_listings_can_be_exempt() {
        let mut listing = community();
        listing.conformance.result = CheckOutcome::Exempt;
        listing.conformance.reason = "trust me".to_owned();
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("exempt"), "{text}");
    }

    #[test]
    fn an_exemption_needs_a_reason() {
        let mut listing = native("autumn-storage-s3", ListingOrigin::FirstParty);
        listing.conformance.result = CheckOutcome::Exempt;
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("reason"), "{text}");
    }

    #[test]
    fn a_community_name_must_follow_the_convention() {
        let mut listing = community();
        listing.name = "serde".to_owned();
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("autumn-plugin-"), "{text}");
    }

    #[test]
    fn a_first_party_listing_must_name_a_catalog_crate() {
        let listing = native("autumn-plugin-audit", ListingOrigin::FirstParty);
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("first-party"), "{text}");
    }

    #[test]
    fn duplicate_listings_are_refused() {
        let text = messages(&validate(&index_of(vec![community(), community()])));
        assert!(text.contains("more than once"), "{text}");
    }

    /// AC 5: the tier must match the declared surfaces, and each surface
    /// must be a real experimental one.
    #[test]
    fn the_tier_must_match_the_declared_surfaces() {
        let mut listing = community();
        listing.tier = Tier::Experimental;
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("experimental_surfaces"), "{text}");

        let mut listing = community();
        listing.experimental_surfaces = vec!["no-such-surface".to_owned()];
        listing.tier = Tier::Experimental;
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("no-such-surface"), "{text}");

        let mut listing = community();
        listing.experimental_surfaces = vec![first_experimental_surface()];
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("tier"), "{text}");
    }

    #[test]
    fn an_experimental_listing_with_real_surfaces_is_valid() {
        let mut listing = community();
        listing.tier = Tier::Experimental;
        listing.experimental_surfaces = vec![first_experimental_surface()];
        assert!(validate(&index_of(vec![listing])).is_empty());
    }

    fn first_experimental_surface() -> String {
        autumn_web::plugin_contract::experimental_surface_names()
            .next()
            .expect("at least one experimental surface")
            .to_owned()
    }

    /// AC 1 / AC 6: a sandboxed listing must carry its capabilities, and
    /// only known ones.
    #[test]
    fn a_sandboxed_listing_must_name_known_capabilities() {
        let mut listing = community();
        listing.trust = Trust::Sandboxed;
        let text = messages(&validate(&index_of(vec![listing.clone()])));
        assert!(text.contains("capabilities"), "{text}");

        listing.capabilities = vec!["root-shell".to_owned()];
        let text = messages(&validate(&index_of(vec![listing.clone()])));
        assert!(text.contains("root-shell"), "{text}");

        listing.capabilities = vec!["http-request".to_owned()];
        listing.artifact_sha256 = "ab".repeat(32);
        let listing = with_full_sandbox_maps(listing);
        assert!(validate(&index_of(vec![listing])).is_empty());
    }

    /// Grants scope a sandboxed capability; a native plugin has none.
    #[test]
    fn grants_are_for_sandboxed_listings_only() {
        let mut native = community();
        native.grants.hosts = vec!["api.example.com".to_owned()];
        let text = messages(&validate(&index_of(vec![native])));
        assert!(text.contains("grants"), "{text}");
    }

    #[test]
    fn a_sandboxed_label_names_its_scoped_grants() {
        let mut listing = community();
        listing.trust = Trust::Sandboxed;
        listing.capabilities = vec!["http-outbound".to_owned()];
        listing.grants.hosts = vec!["api.example.com".to_owned()];
        assert!(
            listing.trust_label().contains("hosts api.example.com"),
            "{}",
            listing.trust_label()
        );
    }

    /// A sandboxed listing with every quota and limit at its default.
    fn with_full_sandbox_maps(mut listing: Listing) -> Listing {
        listing.quotas = autumn_web::plugin_sandbox::CapabilityQuotas::default()
            .fields()
            .into_iter()
            .map(|(k, v)| (k.to_owned(), v))
            .collect();
        listing.limits = autumn_web::plugin_sandbox::ResourceLimits::default()
            .fields()
            .into_iter()
            .map(|(k, v)| (k.to_owned(), u64::try_from(v).unwrap()))
            .collect();
        listing
    }

    /// A sandboxed listing publishes its whole authority: a partial map
    /// is refused.
    #[test]
    fn a_sandboxed_listing_needs_complete_quotas_and_limits() {
        let mut listing = community();
        listing.trust = Trust::Sandboxed;
        listing.capabilities = vec!["kv".to_owned()];
        listing.artifact_sha256 = "ab".repeat(32);
        let text = messages(&validate(&index_of(vec![listing.clone()])));
        assert!(text.contains("`quotas` is missing"), "{text}");
        assert!(text.contains("`limits` is missing"), "{text}");
        let mut full = with_full_sandbox_maps(listing);
        assert!(validate(&index_of(vec![full.clone()])).is_empty());
        full.limits.remove("fuel");
        let text = messages(&validate(&index_of(vec![full])));
        assert!(text.contains("fuel"), "{text}");
    }

    /// Quotas: sandboxed only, and only names the sandbox enforces.
    #[test]
    fn quotas_are_validated() {
        let mut native = community();
        native.quotas.insert("kv_reads".to_owned(), 10);
        let text = messages(&validate(&index_of(vec![native])));
        assert!(text.contains("quotas"), "{text}");

        let mut listing = community();
        listing.trust = Trust::Sandboxed;
        listing.capabilities = vec!["kv".to_owned()];
        listing.artifact_sha256 = "ab".repeat(32);
        listing.quotas.insert("warp_drives".to_owned(), 1);
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("warp_drives"), "{text}");
    }

    /// Limits: sandboxed only, known names only, and the label names the
    /// ones that differ from the default.
    #[test]
    fn limits_are_validated_and_labelled() {
        let mut native = community();
        native.limits.insert("fuel".to_owned(), 1);
        let text = messages(&validate(&index_of(vec![native])));
        assert!(text.contains("limits"), "{text}");

        let mut listing = community();
        listing.trust = Trust::Sandboxed;
        listing.capabilities = vec!["kv".to_owned()];
        listing.artifact_sha256 = "ab".repeat(32);
        listing.limits.insert("warp".to_owned(), 1);
        let text = messages(&validate(&index_of(vec![listing.clone()])));
        assert!(text.contains("warp"), "{text}");

        listing.limits.clear();
        listing.limits.insert("fuel".to_owned(), 7);
        assert!(
            listing.trust_label().contains("fuel=7"),
            "{}",
            listing.trust_label()
        );
    }

    /// The label names quotas that differ from the sandbox default.
    #[test]
    fn a_sandboxed_label_names_its_non_default_quotas() {
        let mut listing = community();
        listing.trust = Trust::Sandboxed;
        listing.capabilities = vec!["kv".to_owned()];
        listing.quotas = autumn_web::plugin_sandbox::CapabilityQuotas::default()
            .fields()
            .into_iter()
            .map(|(k, v)| (k.to_owned(), v))
            .collect();
        assert!(
            !listing.trust_label().contains("quotas"),
            "{}",
            listing.trust_label()
        );
        listing.quotas.insert("kv_reads".to_owned(), 99_999);
        assert!(
            listing.trust_label().contains("kv_reads=99999"),
            "{}",
            listing.trust_label()
        );
    }

    /// AC 6: the manifest shown is bound to reviewed bytes.
    #[test]
    fn a_sandboxed_listing_must_record_its_artifact_digest() {
        let mut listing = community();
        listing.trust = Trust::Sandboxed;
        listing.capabilities = vec!["http-request".to_owned()];
        let text = messages(&validate(&index_of(vec![listing.clone()])));
        assert!(text.contains("artifact_sha256"), "{text}");
        listing.artifact_sha256 = "not hex".to_owned();
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("artifact_sha256"), "{text}");

        let mut native = community();
        native.artifact_sha256 = "ab".repeat(32);
        let text = messages(&validate(&index_of(vec![native])));
        assert!(text.contains("artifact_sha256"), "{text}");
    }

    #[test]
    fn a_native_listing_cannot_claim_capabilities() {
        let mut listing = community();
        listing.capabilities = vec!["kv".to_owned()];
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("native"), "{text}");
    }

    #[test]
    fn a_flagged_listing_needs_a_failed_run_and_a_note() {
        let mut listing = community();
        listing.status = Status::Incompatible;
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("fail"), "{text}");
        assert!(text.contains("note"), "{text}");
    }

    /// Index text is printed to a terminal. Control characters could drive
    /// it, so the gate refuses them.
    #[test]
    fn control_characters_are_refused() {
        let mut listing = community();
        listing.description = "safe\u{1b}[2Jevil".to_owned();
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("control"), "{text}");
    }

    /// Bidi, zero-width and line-separator characters can reorder or hide
    /// text in a terminal. `char::is_control` does not catch them.
    #[test]
    fn bidi_and_invisible_characters_are_refused() {
        for bad in ["\u{202E}", "\u{2066}", "\u{200B}", "\u{2028}", "\u{FEFF}"] {
            let mut listing = community();
            listing.note = format!("safe{bad}evil");
            let text = messages(&validate(&index_of(vec![listing])));
            assert!(text.contains("control"), "{bad:?}: {text}");
        }
    }

    /// Finding text is printed. It must not carry an escape sequence even
    /// when the listing does.
    #[test]
    fn sanitize_escapes_unsafe_characters() {
        assert_eq!(sanitize("a\u{1b}[2Jb\u{202E}c"), "a\\u{1b}[2Jb\\u{202e}c");
        assert_eq!(sanitize("plain text"), "plain text");
    }

    /// crates.io treats `-`/`_` and case as the same name.
    #[test]
    fn lookup_ignores_case_and_separator_variants() {
        let index = index_of(vec![community()]);
        assert!(index.get("autumn_plugin_AUDIT").is_some());
        let mut twin = community();
        twin.name = "autumn-plugin_audit".to_owned();
        let text = messages(&validate(&index_of(vec![community(), twin])));
        assert!(text.contains("more than once"), "{text}");
    }

    /// A range with no upper bound calls every future release compatible.
    #[test]
    fn a_range_without_an_upper_bound_is_refused() {
        for open in ["*", ">=0.6"] {
            let mut listing = community();
            listing.autumn_web = open.to_owned();
            let text = messages(&validate(&index_of(vec![listing])));
            assert!(text.contains("upper bound"), "{open}: {text}");
        }
    }

    #[test]
    fn load_refuses_an_override_that_is_not_a_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let err = load(Some(dir.path())).unwrap_err();
        assert!(matches!(err, IndexError::Io(_)), "{err:?}");
    }

    #[test]
    fn load_refuses_an_oversized_override() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("big.toml");
        let mut text = String::from("schema = 1\n");
        text.push_str(&"#".repeat(usize::try_from(MAX_INDEX_BYTES).unwrap() + 1));
        std::fs::write(&path, text).expect("write");
        let err = load(Some(&path)).unwrap_err();
        assert!(matches!(err, IndexError::Io(_)), "{err:?}");
    }

    #[test]
    fn the_repository_must_be_https() {
        let mut listing = community();
        listing.repository = "http://example.com".to_owned();
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("https"), "{text}");
    }

    #[test]
    fn the_check_date_must_be_a_date() {
        let mut listing = community();
        listing.conformance.checked = "last tuesday".to_owned();
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("checked"), "{text}");
    }

    // ── Staleness: re-verification (AC 4) ───────────────────────────────

    #[test]
    fn a_listing_verified_on_this_release_is_fresh() {
        let index = index_of(vec![community()]);
        assert!(staleness(&index, "0.7.0").is_empty());
    }

    #[test]
    fn a_listing_verified_on_an_older_release_is_stale() {
        let index = index_of(vec![community()]);
        let text = messages(&staleness(&index, "0.7.1"));
        assert!(text.contains("re-verify"), "{text}");
    }

    /// An RC of a series is that series: `0.8` covers `0.8.0-rc.1`.
    #[test]
    fn a_prerelease_release_is_covered_by_its_series() {
        let mut listing = community();
        listing.autumn_web = "0.8".to_owned();
        listing.conformance.autumn_web = "0.8.0-rc.1".to_owned();
        let text = messages(&staleness(&index_of(vec![listing]), "0.8.0-rc.1"));
        assert!(text.is_empty(), "{text}");
    }

    /// A sandboxed artifact is not tied to a series: its flag applies to
    /// every app, so discovery agrees with the install gate.
    #[test]
    fn a_sandboxed_flag_applies_to_every_app() {
        let mut listing = flagged();
        listing.trust = Trust::Sandboxed;
        listing.conformance.autumn_web = "0.9.0".to_owned();
        listing.autumn_web = ">=0.1, <1".to_owned();
        assert!(listing.flag_applies("0.2.0"));
        assert_eq!(listing.compat("0.2.0"), Compat::Incompatible);
    }

    /// The flag applies from the failed series on, not to older apps.
    #[test]
    fn a_flag_applies_from_the_failed_series() {
        let mut listing = flagged();
        listing.conformance.autumn_web = "0.8.0".to_owned();
        assert!(listing.flag_applies("0.8.2"));
        assert!(listing.flag_applies("0.9.0"));
        assert!(!listing.flag_applies("0.7.0"));
        assert!(!community().flag_applies("0.8.0"));
        // After 1.0 the series is the major: a 1.2 failure covers 1.1.
        listing.conformance.autumn_web = "1.2.0".to_owned();
        assert!(listing.flag_applies("1.1.0"));
        assert!(listing.flag_applies("2.0.0"));
        assert!(!listing.flag_applies("0.9.0"));
    }

    /// An unresolved app requirement is compatible only when the range
    /// admits its whole series; a lower series is still incompatible.
    #[test]
    fn an_unresolved_app_requirement_needs_the_whole_series() {
        let mut exact = community();
        exact.autumn_web = "=0.7.0".to_owned();
        assert_eq!(exact.compat("0.7.0"), Compat::Compatible);
        assert_eq!(exact.compat("^0.7.0"), Compat::Unknown);
        let caret = community();
        assert_eq!(caret.compat("^0.7.0"), Compat::Compatible);
        assert_eq!(caret.compat("^0.6.0"), Compat::Incompatible);
    }

    #[test]
    fn a_sandboxed_label_names_its_routes() {
        let mut listing = community();
        listing.trust = Trust::Sandboxed;
        listing.capabilities = vec!["kv".to_owned()];
        listing.routes = vec!["GET /hello".to_owned(), "HEAD /hello".to_owned()];
        let label = listing.trust_label();
        assert!(label.contains("serves GET /hello, HEAD /hello"), "{label}");
    }

    /// Only a catalog crate that is not a `Plugin` can be exempt: a
    /// `Plugin` listing cannot mark itself exempt to skip plugin-check.
    #[test]
    fn a_plugin_listing_cannot_be_exempt() {
        let mut admin = native("autumn-admin-plugin", ListingOrigin::FirstParty);
        admin.conformance.result = CheckOutcome::Exempt;
        admin.conformance.reason = "trust me".to_owned();
        let text = messages(&validate(&index_of(vec![admin])));
        assert!(text.contains("not a `Plugin`"), "{text}");
        let mut s3 = native("autumn-storage-s3", ListingOrigin::FirstParty);
        s3.prefix.clear();
        s3.conformance.result = CheckOutcome::Exempt;
        s3.conformance.reason = "a BlobStore, not a Plugin".to_owned();
        assert!(
            validate(&index_of(vec![s3])).is_empty(),
            "{:?}",
            validate(&index_of(vec![]))
        );
    }

    /// A native plugin listing names its route mode: a prefix, or none.
    #[test]
    fn a_native_listing_needs_a_route_mode() {
        let mut listing = community();
        listing.prefix.clear();
        let text = messages(&validate(&index_of(vec![listing.clone()])));
        assert!(text.contains("needs a `prefix`"), "{text}");
        listing.no_routes = true;
        assert!(validate(&index_of(vec![listing])).is_empty());
    }

    /// Recorded routes are printed in the trust label, so they are scanned.
    #[test]
    fn a_route_with_a_terminal_control_is_refused() {
        let mut listing = community();
        listing.trust = Trust::Sandboxed;
        listing.capabilities = vec!["kv".to_owned()];
        listing.routes = vec!["GET /safe\u{1b}[2J".to_owned()];
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(
            text.contains("`routes` holds a control character"),
            "{text}"
        );
    }

    #[test]
    fn no_routes_and_a_prefix_contradict() {
        let mut listing = community();
        listing.no_routes = true;
        listing.prefix = "/x".to_owned();
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("no_routes"), "{text}");
    }

    #[test]
    fn a_native_listing_cannot_record_routes() {
        let mut listing = community();
        listing.routes = vec!["GET /x".to_owned()];
        let text = messages(&validate(&index_of(vec![listing])));
        assert!(text.contains("`routes`"), "{text}");
    }

    #[test]
    fn a_range_that_excludes_the_release_must_be_flagged() {
        let mut listing = community();
        listing.conformance.autumn_web = "0.8.0".to_owned();
        let text = messages(&staleness(&index_of(vec![listing]), "0.8.0"));
        assert!(text.contains("incompatible"), "{text}");
    }

    #[test]
    fn a_first_party_listing_must_carry_the_release_version() {
        let mut listing = native("autumn-admin-plugin", ListingOrigin::FirstParty);
        listing.version = "0.6.0".to_owned();
        let text = messages(&staleness(&index_of(vec![listing]), "0.7.0"));
        assert!(text.contains("0.6.0"), "{text}");
    }

    fn flagged() -> Listing {
        let mut listing = community();
        listing.status = Status::Incompatible;
        listing.conformance.result = CheckOutcome::Fail;
        listing.note = "failed on 0.7.0".to_owned();
        listing
    }

    /// A flag is fresh on the release it was set on.
    #[test]
    fn a_flag_on_this_release_is_fresh() {
        assert!(staleness(&index_of(vec![flagged()]), "0.7.0").is_empty());
    }

    /// AC 4: a flag does not stay forever. On the next release the listing
    /// is re-verified (relisted) or delisted.
    #[test]
    fn a_flag_from_an_older_release_must_be_resolved() {
        let text = messages(&staleness(&index_of(vec![flagged()]), "0.8.0"));
        assert!(text.contains("delist"), "{text}");
    }

    /// Every bidi and format mark that can reorder terminal text is unsafe.
    #[test]
    fn bidi_format_marks_are_unsafe() {
        for c in [
            '\u{061C}', '\u{200E}', '\u{202E}', '\u{2066}', '\u{2069}', '\u{206A}', '\u{206F}',
        ] {
            assert!(is_unsafe_char(c), "U+{:04X}", u32::from(c));
            assert!(!sanitize(&format!("a{c}b")).contains(c));
        }
        assert!(!is_unsafe_char('é'));
        // Default-ignorable letters and marks that render as nothing.
        for c in [
            '\u{00AD}',
            '\u{034F}',
            '\u{115F}',
            '\u{3164}',
            '\u{FE0F}',
            '\u{E0041}',
        ] {
            assert!(is_unsafe_char(c), "U+{:04X}", u32::from(c));
        }
    }

    #[test]
    fn a_delisted_listing_must_have_failed() {
        let mut gone = community();
        gone.status = Status::Delisted;
        gone.note = "removed".to_owned();
        let text = messages(&validate(&index_of(vec![gone.clone()])));
        assert!(
            text.contains("delisted, but the last conformance run did not fail"),
            "{text}"
        );
        gone.conformance.result = CheckOutcome::Fail;
        assert!(validate(&index_of(vec![gone])).is_empty());
    }

    #[test]
    fn delisted_listings_are_never_stale() {
        let mut gone = flagged();
        gone.status = Status::Delisted;
        assert!(staleness(&index_of(vec![gone]), "0.9.0").is_empty());
    }
}