autumn-cli 0.10.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
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
//! `autumn plugin index check` and `autumn plugin index record`: the
//! maintainer side of the plugin index (issue #1625).
//!
//! `check` is the gate: admission rules plus re-verification against the
//! current release. `record` writes an `autumn plugin-check --format json`
//! report into a listing. A pass lists it. A fail flags it incompatible. A
//! second fail on a later release delists it.

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

use super::index::{self, CheckOutcome, Listing, ListingOrigin, Status, Tier};
use crate::plugin_check::{CheckStatus, ConformanceReport};

/// What `record` did to a listing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Transition {
    /// The run passed: the listing is listed.
    Listed,
    /// The run failed: the listing is flagged incompatible.
    Flagged,
    /// The run failed again on a later release: the listing is delisted.
    Delisted,
}

/// Write `report` into `listing`, as a run against `against` on `date`.
///
/// # Errors
///
/// When the report names a different plugin.
pub fn apply_report(
    listing: &mut Listing,
    report: &ConformanceReport,
    against: &str,
    date: &str,
) -> Result<Transition, String> {
    if index::canonical(&report.plugin_name) != index::canonical(&listing.name) {
        return Err(format!(
            "the report is for `{}`, not `{}`",
            index::sanitize(&report.plugin_name),
            listing.name
        ));
    }
    if listing.trust == index::Trust::Sandboxed {
        return Err(format!(
            "`{}` is sandboxed; record its `autumn plugin inspect --format json` report with \
             `--inspect` instead",
            listing.name
        ));
    }
    check_report_shape(report, &listing.prefix, listing.no_routes)?;
    // The contract is the machine-checked source of the range and the tier.
    // Only a pass replaces them: a failed contract may not even parse, and
    // the listing keeps what was last verified.
    if let Some(contract) = report.contract.as_ref().filter(|_| report.passed()) {
        // The pin is the version that was built and checked. A contract that
        // reports another one is refused, never used to move the pin, and
        // one that reports none cannot show which release was built.
        if listing.origin == ListingOrigin::Community {
            match &contract.plugin_version {
                None => {
                    return Err(format!(
                        "the report for `{}` passes, but its contract names no \
                         `plugin_version`, so it cannot show that {} was built. Declare \
                         `.plugin_version(env!(\"CARGO_PKG_VERSION\"))` in `Plugin::contract` \
                         and re-run the check",
                        listing.name, listing.version
                    ));
                }
                Some(version) if version != &listing.version => {
                    return Err(format!(
                        "the report for `{}` says version {}, but the index verified {}. \
                         Change `version` in the listing and re-run the check",
                        listing.name,
                        index::sanitize(version),
                        listing.version
                    ));
                }
                Some(_) => {}
            }
        }
        if let Some(range) = &contract.autumn_web {
            listing.autumn_web.clone_from(range);
        }
        // A first-party crate is lockstep: it is built from this workspace,
        // so its contract version is the release.
        if let Some(version) = &contract.plugin_version
            && listing.origin == ListingOrigin::FirstParty
        {
            listing.version.clone_from(version);
        }
        listing
            .experimental_surfaces
            .clone_from(&contract.experimental_surfaces);
        listing.tier = if listing.experimental_surfaces.is_empty() {
            Tier::Stable
        } else {
            Tier::Experimental
        };
    }

    let failed: Vec<&str> = report
        .checks
        .iter()
        .filter(|c| c.status == CheckStatus::Fail)
        .map(|c| c.name.as_str())
        .collect();
    let failed = (!report.passed()).then(|| failed.join(", "));
    Ok(transition(listing, failed.as_deref(), against, date))
}

/// A report is recorded only for the release it tested: a pass from an older
/// release proves nothing about this one, even when its range admits both.
/// A failing report that names no release (an install that failed before
/// plugin-check ran) is still recorded as a failure.
///
/// # Errors
///
/// When the report tested another release, or passes without naming one.
pub fn check_tested_release(report: &ConformanceReport, against: &str) -> Result<(), String> {
    let name = index::sanitize(&report.plugin_name);
    match report.autumn_web.as_deref() {
        Some(tested) if tested == against => Ok(()),
        Some(tested) => Err(format!(
            "the report for `{name}` tested autumn-web {}, not {against}. Re-run \
             `autumn plugin-check` against {against}",
            index::sanitize(tested)
        )),
        None if !report.passed() => Ok(()),
        None => Err(format!(
            "the report for `{name}` does not say which autumn-web it tested. Re-run it with \
             this CLI's `autumn plugin-check --format json`"
        )),
    }
}

/// Record one run: `failed` is `None` for a pass, or the failed checks.
fn transition(
    listing: &mut Listing,
    failed: Option<&str>,
    against: &str,
    date: &str,
) -> Transition {
    let previous = std::mem::replace(&mut listing.conformance.autumn_web, against.to_owned());
    date.clone_into(&mut listing.conformance.checked);
    listing.conformance.reason.clear();

    let Some(failed) = failed else {
        listing.conformance.result = CheckOutcome::Pass;
        listing.status = Status::Listed;
        listing.note.clear();
        return Transition::Listed;
    };

    listing.conformance.result = CheckOutcome::Fail;
    let second_release = listing.status != Status::Listed && previous != against;
    if second_release {
        listing.status = Status::Delisted;
        listing.note =
            format!("failed re-verification on autumn-web {previous} and {against} ({failed})");
        Transition::Delisted
    } else if listing.status == Status::Delisted {
        // A retry on the same release does not bring a delisted plugin back.
        Transition::Delisted
    } else {
        listing.status = Status::Incompatible;
        listing.note = format!("failed re-verification on autumn-web {against} ({failed})");
        Transition::Flagged
    }
}

/// The checks every `autumn plugin-check` report carries. A pass without
/// one of them was not made by `plugin-check`, or had the failing one cut.
/// `route-prefix` is added when the listing declares a prefix.
const REQUIRED_CHECKS: [&str; 7] = [
    "installability",
    "route-attribution",
    "route-collision",
    "sensitive-surfaces",
    "duplicate-registration",
    "plugin-contract",
    "experimental-surface",
];

/// Refuse a report that `plugin-check` did not make, or a pass with no
/// declared range (AC 3: a listing needs the #1601 contract).
fn check_report_shape(
    report: &ConformanceReport,
    prefix: &str,
    no_routes: bool,
) -> Result<(), String> {
    let name = index::sanitize(&report.plugin_name);
    // A failing report is always taken: it can only flag, never vouch.
    if !report.passed() {
        return Ok(());
    }
    let with_prefix = (!prefix.is_empty()).then_some("route-prefix");
    for required in REQUIRED_CHECKS.into_iter().chain(with_prefix) {
        if !report.checks.iter().any(|c| c.name == required) {
            return Err(format!(
                "the report for `{name}` has no `{required}` check; use a report from \
                 `autumn plugin-check --format json`"
            ));
        }
    }
    // A `route-prefix` pass proves only the prefix it tested: `--prefix /`
    // admits every route, and is no evidence for `/admin`.
    let normalized = |p: &str| p.trim_end_matches('/').to_owned();
    if !prefix.is_empty() && report.prefix.as_deref().map(normalized) != Some(normalized(prefix)) {
        return Err(format!(
            "the report for `{name}` checked routes under {}, but the listing's prefix is \
             `{prefix}`; re-run `autumn plugin-check --prefix {prefix}`",
            report.prefix.as_deref().map_or_else(
                || "no prefix".to_owned(),
                |p| format!("`{}`", index::sanitize(p))
            )
        ));
    }
    // A `route-prefix` pass that leaned on `--intentional-root` exemptions is
    // not evidence the index can keep: a listing has no field for them, so
    // reverification would re-run without them and fail (issue #2828).
    if !report.intentional_root.is_empty() {
        return Err(format!(
            "the report for `{name}` exempted intentional root routes from `route-prefix`, \
             which a plugin index listing cannot record; re-run `autumn plugin-check` \
             without `--intentional-root`"
        ));
    }
    // `no_routes` exempts a listing from a prefix, so its report must show
    // the assertion held: `route-attribution` skips only under `plugin-check
    // --no-routes` with no routes found. A run without it passes a plugin
    // that mounts routes, and none of them would have been prefix-checked.
    if no_routes
        && !report
            .checks
            .iter()
            .any(|c| c.name == "route-attribution" && c.status == CheckStatus::Skip)
    {
        return Err(format!(
            "the listing for `{name}` says `no_routes`, but the report does not show that \
             no routes were found; re-run `autumn plugin-check --no-routes`"
        ));
    }
    let contract_passed = report
        .checks
        .iter()
        .any(|c| c.name == "plugin-contract" && c.status == CheckStatus::Pass);
    let range = report.contract.as_ref().and_then(|c| c.autumn_web.as_ref());
    if !contract_passed || range.is_none() {
        return Err(format!(
            "the report for `{name}` has no passing contract with an autumn-web range; \
             implement `Plugin::contract`"
        ));
    }
    Ok(())
}

/// The fields `record --inspect` reads from `autumn plugin inspect --format
/// json`.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct InspectReport {
    /// The manifest name.
    pub name: String,
    /// The manifest version.
    pub version: String,
    /// The digest of the whole artifact.
    pub artifact_sha256: Option<String>,
    /// The capabilities the manifest asks for.
    pub capabilities: Vec<String>,
    /// The routes the artifact serves. Required: a route is authority.
    pub routes: Vec<InspectRoute>,
    /// Whether the module loads into the sandbox.
    pub loads: bool,
    /// The route-conformance report.
    pub conformance: ConformanceReport,
    /// What the artifact asks for beyond the one named by `--against`.
    #[serde(default)]
    pub upgrade: Option<serde_json::Value>,
    /// The artifact digest of the `--against` baseline.
    #[serde(default)]
    pub upgrade_against: Option<String>,
    /// What each granted capability is scoped to. Required, as every other
    /// authority field: a missing one would erase the recorded scopes.
    pub grants: InspectGrants,
    /// The per-request quotas the manifest declares.
    #[serde(default)]
    pub quotas: std::collections::BTreeMap<String, u32>,
    /// The per-request resource limits the manifest declares.
    #[serde(default)]
    pub limits: std::collections::BTreeMap<String, u64>,
    /// The `autumn-web` whose sandbox the artifact was loaded in.
    #[serde(default)]
    pub autumn_web: Option<String>,
}

/// The `grants` object `inspect` emits. Every list is required: `inspect`
/// always prints all four, empty or not.
/// One route of an inspect report.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct InspectRoute {
    /// HTTP method.
    pub method: String,
    /// Full mounted path.
    pub path: String,
}

impl InspectReport {
    /// The routes as the listing records them: `METHOD /path`.
    fn route_names(&self) -> Vec<String> {
        self.routes
            .iter()
            .map(|r| format!("{} {}", r.method, r.path))
            .collect()
    }
}

#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct InspectGrants {
    /// Hostnames `http-outbound` may call.
    pub hosts: Vec<String>,
    /// Logical tables `db` owns.
    pub tables: Vec<String>,
    /// Job types `jobs` may enqueue.
    pub job_types: Vec<String>,
    /// Render slots `render` may fill.
    pub slots: Vec<String>,
}

impl From<&InspectGrants> for index::Grants {
    fn from(g: &InspectGrants) -> Self {
        Self {
            hosts: g.hosts.clone(),
            tables: g.tables.clone(),
            job_types: g.job_types.clone(),
            slots: g.slots.clone(),
        }
    }
}

impl InspectReport {
    /// Whether `--against` found new authority: any non-empty list in the
    /// delta. Read generically, so a field added later still counts.
    #[must_use]
    pub fn needs_consent(&self) -> bool {
        self.upgrade.as_ref().is_some_and(|delta| {
            delta.as_object().is_some_and(|fields| {
                fields
                    .values()
                    .any(|v| v.as_array().is_some_and(|a| !a.is_empty()))
            })
        })
    }
}

/// Refuse an inspect report this CLI's `inspect` did not make: the route
/// checks, every quota and limit, and a complete upgrade delta.
fn check_inspect_shape(listing: &Listing, report: &InspectReport) -> Result<(), String> {
    // `inspect` runs the route checks from `plugin-check` over the manifest.
    // A report without them was not made by `inspect`.
    if index::canonical(&report.conformance.plugin_name) != index::canonical(&listing.name) {
        return Err(format!(
            "the inspect report's conformance is for `{}`, not `{}`",
            index::sanitize(&report.conformance.plugin_name),
            listing.name
        ));
    }
    // Over a manifest's routes these checks pass or fail; `inspect` never
    // skips them. A skip would hide a failure, and sandboxed listings are
    // not re-verified.
    for required in ["route-attribution", "route-prefix", "route-collision"] {
        match report
            .conformance
            .checks
            .iter()
            .find(|c| c.name == required)
        {
            None => {
                return Err(format!(
                    "the inspect report for `{}` has no `{required}` check; use a report from \
                     `autumn plugin inspect --format json`",
                    listing.name
                ));
            }
            Some(check) if check.status == CheckStatus::Skip => {
                return Err(format!(
                    "the inspect report for `{}` skips `{required}`, which `autumn plugin \
                     inspect` always runs; use an unedited report",
                    listing.name
                ));
            }
            Some(_) => {}
        }
    }
    // `inspect` emits every quota and limit. A report missing one would
    // erase the recorded ceilings, so it was not made by this `inspect`.
    let quotas = autumn_web::plugin_sandbox::CapabilityQuotas::default().fields();
    let limits = autumn_web::plugin_sandbox::ResourceLimits::default().fields();
    let missing: Vec<String> = quotas
        .iter()
        .filter(|(key, _)| !report.quotas.contains_key(*key))
        .map(|(key, _)| format!("quotas.{key}"))
        .chain(
            limits
                .iter()
                .filter(|(key, _)| !report.limits.contains_key(*key))
                .map(|(key, _)| format!("limits.{key}")),
        )
        .collect();
    if !missing.is_empty() {
        return Err(format!(
            "the inspect report for `{}` has no {}; use a report from this CLI's \
             `autumn plugin inspect --format json`",
            listing.name,
            missing.join(", ")
        ));
    }
    // A delta must carry every `ConsentDelta` field as a list: `{}` or a
    // partial one would read as "nothing new".
    if let Some(upgrade) = &report.upgrade {
        let expected = serde_json::to_value(autumn_web::plugin_sandbox::ConsentDelta::default())
            .unwrap_or_default();
        let missing: Vec<&str> = expected
            .as_object()
            .into_iter()
            .flat_map(|fields| fields.keys())
            .filter(|key| upgrade.get(key.as_str()).is_none_or(|v| !v.is_array()))
            .map(String::as_str)
            .collect();
        if !upgrade.is_object() || !missing.is_empty() {
            return Err(format!(
                "the inspect report's `upgrade` for `{}` is not a complete delta (missing {}); \
                 use `autumn plugin inspect --against`",
                listing.name,
                missing.join(", ")
            ));
        }
    }
    Ok(())
}

/// Write an `autumn plugin inspect --format json` result into a sandboxed
/// listing. The capabilities and digest come from the artifact, not a hand
/// edit.
///
/// # Errors
///
/// When the listing is not sandboxed, or the report names another plugin.
pub fn apply_inspect(
    listing: &mut Listing,
    report: &InspectReport,
    against: &str,
    date: &str,
) -> Result<Transition, String> {
    if listing.trust != index::Trust::Sandboxed {
        return Err(format!(
            "`{}` is not sandboxed; record its `autumn plugin-check` report instead",
            listing.name
        ));
    }
    if index::canonical(&report.name) != index::canonical(&listing.name) {
        return Err(format!(
            "the inspect report is for `{}`, not `{}`",
            index::sanitize(&report.name),
            listing.name
        ));
    }
    check_inspect_shape(listing, report)?;
    // Recorded only for the release whose sandbox loaded it: automated
    // re-verification skips sandboxed listings, so nothing else would catch
    // a stale report.
    match report.autumn_web.as_deref() {
        Some(tested) if tested == against => {}
        tested => {
            return Err(format!(
                "the inspect report for `{}` {}. Re-run `autumn plugin inspect --format json` \
                 with the autumn {against} CLI",
                listing.name,
                tested.map_or_else(
                    || "does not say which autumn-web loaded it".to_owned(),
                    |v| format!(
                        "was made on autumn-web {}, not {against}",
                        index::sanitize(v)
                    )
                )
            ));
        }
    }
    // Replacing a recorded artifact needs a consent check against it. Without
    // `--against` the report has no delta, and new authority would pass.
    let replacing = !listing.artifact_sha256.is_empty()
        && report.artifact_sha256.as_deref() != Some(listing.artifact_sha256.as_str());
    // The delta must be against the recorded artifact, not any baseline:
    // `--against new.autumn-plugin` would compare the artifact with itself.
    if replacing
        && (report.upgrade.is_none()
            || report.upgrade_against.as_deref() != Some(listing.artifact_sha256.as_str()))
    {
        return Err(format!(
            "`{}` records artifact sha256 {}, and this report is for other bytes. Run \
             `autumn plugin inspect <new>.autumn-plugin --against <recorded>.autumn-plugin \
             --format json` and record that",
            listing.name, listing.artifact_sha256
        ));
    }
    // The same bytes carry the same manifest. A report that repeats the
    // recorded digest with other metadata is edited, and would rewrite what
    // the listing says the artifact can do.
    if !replacing && !listing.artifact_sha256.is_empty() {
        let changed = changed_metadata(listing, report);
        if !changed.is_empty() {
            return Err(format!(
                "the inspect report for `{}` names the recorded artifact sha256 {}, but its {} \
                 differ from the listing's. One artifact has one manifest: re-run \
                 `autumn plugin inspect --format json` on the recorded artifact",
                listing.name,
                listing.artifact_sha256,
                changed.join(", ")
            ));
        }
    }
    // The delta is the report's own claim. Compare the authority it reports
    // with what the listing recorded, and refuse a delta that hides growth.
    let widened = widened_authority(listing, report);
    if !widened.is_empty() && !report.needs_consent() {
        return Err(format!(
            "the inspect report for `{}` grants more than the listing records ({}), but its \
             `upgrade` delta says nothing is new. Re-run `autumn plugin inspect --against`",
            listing.name,
            widened.join(", ")
        ));
    }
    let mut failed = Vec::new();
    if !report.loads {
        failed.push("load".to_owned());
    }
    // `inspect --against` exits 1 when the artifact grows its authority. A
    // listing must not vouch for a grant nobody consented to.
    if report.needs_consent() || !widened.is_empty() {
        failed.push("upgrade-consent".to_owned());
    }
    failed.extend(
        report
            .conformance
            .checks
            .iter()
            .filter(|c| c.status == CheckStatus::Fail)
            .map(|c| c.name.clone()),
    );
    if report.artifact_sha256.is_none() {
        failed.push("artifact-digest".to_owned());
    }
    // Only a pass replaces the reviewed artifact. On a fail the listing keeps
    // the version, capabilities and digest that were consented to.
    if failed.is_empty()
        && let Some(digest) = &report.artifact_sha256
    {
        digest.clone_into(&mut listing.artifact_sha256);
        report.version.clone_into(&mut listing.version);
        listing.capabilities.clone_from(&report.capabilities);
        listing.routes = report.route_names();
        listing.grants = index::Grants::from(&report.grants);
        listing.quotas.clone_from(&report.quotas);
        listing.limits.clone_from(&report.limits);
    }
    let failed = (!failed.is_empty()).then(|| failed.join(", "));
    Ok(transition(listing, failed.as_deref(), against, date))
}

/// The artifact-derived fields where `report` differs from `listing`.
fn changed_metadata(listing: &Listing, report: &InspectReport) -> Vec<&'static str> {
    let mut changed = Vec::new();
    if report.version != listing.version {
        changed.push("version");
    }
    if report.capabilities != listing.capabilities {
        changed.push("capabilities");
    }
    if report.route_names() != listing.routes {
        changed.push("routes");
    }
    if index::Grants::from(&report.grants) != listing.grants {
        changed.push("grants");
    }
    if report.quotas != listing.quotas {
        changed.push("quotas");
    }
    if report.limits != listing.limits {
        changed.push("limits");
    }
    changed
}

/// Authority `report` has beyond what `listing` recorded: a capability, a
/// scoped grant, or a quota or limit that is new or higher. Empty for a
/// listing with no recorded artifact, whose first review is the PR itself.
fn widened_authority(listing: &Listing, report: &InspectReport) -> Vec<String> {
    fn added(label: &str, before: &[String], after: &[String], out: &mut Vec<String>) {
        for item in after.iter().filter(|item| !before.contains(item)) {
            out.push(format!("{label} {}", index::sanitize(item)));
        }
    }
    fn raised<T: PartialOrd + Copy>(
        label: &str,
        before: &std::collections::BTreeMap<String, T>,
        after: &std::collections::BTreeMap<String, T>,
        out: &mut Vec<String>,
    ) {
        for (key, value) in after {
            if before.get(key).is_none_or(|old| value > old) {
                out.push(format!("{label} {}", index::sanitize(key)));
            }
        }
    }

    let mut out = Vec::new();
    if listing.artifact_sha256.is_empty() {
        return out;
    }
    let granted = &listing.grants;
    added(
        "capability",
        &listing.capabilities,
        &report.capabilities,
        &mut out,
    );
    added("route", &listing.routes, &report.route_names(), &mut out);
    added("host", &granted.hosts, &report.grants.hosts, &mut out);
    added("table", &granted.tables, &report.grants.tables, &mut out);
    added(
        "job type",
        &granted.job_types,
        &report.grants.job_types,
        &mut out,
    );
    added("slot", &granted.slots, &report.grants.slots, &mut out);
    // A quota for a capability the artifact no longer has governs nothing,
    // as `ConsentDelta` treats it.
    let live_quotas: std::collections::BTreeMap<String, u32> = report
        .quotas
        .iter()
        .filter(|(key, _)| {
            autumn_web::plugin_sandbox::CapabilityQuotas::governed_by(key)
                .is_none_or(|cap| report.capabilities.iter().any(|c| c == cap.as_str()))
        })
        .map(|(k, v)| (k.clone(), *v))
        .collect();
    raised("quota", &listing.quotas, &live_quotas, &mut out);
    raised("limit", &listing.limits, &report.limits, &mut out);
    out
}

/// Refresh an exempt listing after the install gate passed on `against`.
///
/// # Errors
///
/// When the listing is not exempt: a `Plugin` must bring a report.
pub fn apply_exempt(listing: &mut Listing, against: &str, date: &str) -> Result<(), String> {
    require_exempt_class(listing)?;
    listing.conformance.result = CheckOutcome::Exempt;
    listing.status = Status::Listed;
    listing.note.clear();
    against.clone_into(&mut listing.conformance.autumn_web);
    date.clone_into(&mut listing.conformance.checked);
    // First-party crates are lockstep: the release is their version, and its
    // series is their range.
    if listing.origin == ListingOrigin::FirstParty {
        against.clone_into(&mut listing.version);
        listing.autumn_web = autumn_web::plugin_contract::lockstep_range(against);
    }
    Ok(())
}

/// Record a failed install gate for an exempt listing: flag it, or delist it
/// on a second release. The exemption stays, so a later pass recovers it.
///
/// # Errors
///
/// When the listing is not exempt.
pub fn apply_exempt_failed(
    listing: &mut Listing,
    against: &str,
    date: &str,
) -> Result<Transition, String> {
    require_exempt_class(listing)?;
    let reason = std::mem::take(&mut listing.conformance.reason);
    let t = transition(listing, Some("installability"), against, date);
    listing.conformance.reason = reason;
    Ok(t)
}

/// An exempt listing is verified by its install gate, not by plugin-check:
/// its result is `exempt`, or a failure that kept its exemption `reason`.
fn require_exempt_class(listing: &Listing) -> Result<(), String> {
    let exempt = listing.conformance.result == CheckOutcome::Exempt
        || (listing.conformance.result == CheckOutcome::Fail
            && !listing.conformance.reason.trim().is_empty());
    if exempt {
        Ok(())
    } else {
        Err(format!(
            "`{}` is not exempt; record its `autumn plugin-check` report instead",
            listing.name
        ))
    }
}

/// Write the fields `record` owns back into the index text, and keep every
/// other line (comments, order) as it is.
///
/// # Errors
///
/// When the text does not parse or has no listing for `listing.name`.
pub fn write_listing(src: &str, listing: &Listing) -> Result<String, String> {
    use toml_edit::{Array, DocumentMut, Item, Table, value};

    fn set_or_remove(table: &mut Table, key: &str, text: &str) {
        if text.is_empty() {
            table.remove(key);
        } else {
            table[key] = value(text);
        }
    }
    fn to_value<T: serde::Serialize>(v: &T) -> String {
        serde_json::to_value(v)
            .ok()
            .and_then(|v| v.as_str().map(str::to_owned))
            .unwrap_or_default()
    }

    let mut doc: DocumentMut = src
        .parse()
        .map_err(|e| format!("the index does not parse: {e}"))?;
    let tables = doc
        .get_mut("plugin")
        .and_then(Item::as_array_of_tables_mut)
        .ok_or("the index has no [[plugin]] listings")?;
    let table = tables
        .iter_mut()
        .find(|t| t.get("name").and_then(Item::as_str) == Some(listing.name.as_str()))
        .ok_or_else(|| format!("the index has no listing for `{}`", listing.name))?;

    table["version"] = value(&listing.version);
    table["autumn_web"] = value(&listing.autumn_web);
    table["tier"] = value(to_value(&listing.tier));
    table["status"] = value(to_value(&listing.status));
    set_or_remove(table, "note", &listing.note);
    if listing.experimental_surfaces.is_empty() {
        table.remove("experimental_surfaces");
    } else {
        table["experimental_surfaces"] =
            value(listing.experimental_surfaces.iter().collect::<Array>());
    }
    if listing.capabilities.is_empty() {
        table.remove("capabilities");
    } else {
        table["capabilities"] = value(listing.capabilities.iter().collect::<Array>());
    }
    if listing.routes.is_empty() {
        table.remove("routes");
    } else {
        table["routes"] = value(listing.routes.iter().collect::<Array>());
    }
    set_or_remove(table, "artifact_sha256", &listing.artifact_sha256);
    if listing.grants.is_empty() {
        table.remove("grants");
    } else {
        let mut grants = toml_edit::Table::new();
        for (key, list) in [
            ("hosts", &listing.grants.hosts),
            ("tables", &listing.grants.tables),
            ("job_types", &listing.grants.job_types),
            ("slots", &listing.grants.slots),
        ] {
            if !list.is_empty() {
                grants[key] = value(list.iter().collect::<Array>());
            }
        }
        table["grants"] = Item::Table(grants);
    }
    if listing.quotas.is_empty() {
        table.remove("quotas");
    } else {
        let mut quotas = toml_edit::Table::new();
        for (key, v) in &listing.quotas {
            quotas[key.as_str()] = value(i64::from(*v));
        }
        table["quotas"] = Item::Table(quotas);
    }
    if listing.limits.is_empty() {
        table.remove("limits");
    } else {
        let mut limits = toml_edit::Table::new();
        for (key, v) in &listing.limits {
            // TOML integers are i64; a limit past that is written as the max.
            limits[key.as_str()] = value(i64::try_from(*v).unwrap_or(i64::MAX));
        }
        table["limits"] = Item::Table(limits);
    }
    let run = &listing.conformance;
    let conformance = table
        .get_mut("conformance")
        .and_then(Item::as_table_mut)
        .ok_or_else(|| format!("`{}` has no [plugin.conformance] table", listing.name))?;
    conformance["result"] = value(to_value(&run.result));
    conformance["autumn_web"] = value(&run.autumn_web);
    conformance["checked"] = value(&run.checked);
    set_or_remove(conformance, "reason", &run.reason);
    Ok(doc.to_string())
}

/// Render the findings `check` found.
#[must_use]
pub fn render_findings(findings: &[index::Finding], source: &str, against: &str) -> String {
    use std::fmt::Write as _;

    if findings.is_empty() {
        return format!("Plugin index {source} passes for autumn-web {against}.");
    }
    let mut out = format!(
        "Plugin index {source}: {} finding{} for autumn-web {against}:\n",
        findings.len(),
        if findings.len() == 1 { "" } else { "s" }
    );
    for finding in findings {
        let _ = writeln!(
            out,
            "  {}: {}",
            index::sanitize(&finding.plugin),
            index::sanitize(&finding.message)
        );
    }
    out.push_str(
        "\nRe-verify with `autumn plugin-check --format json`, then \
         `autumn plugin index record`. See autumn-cli/plugin-index/README.md.",
    );
    out
}

/// Options for `autumn plugin index check`.
#[derive(Debug, Clone, Copy)]
pub struct CheckOptions<'a> {
    /// The index file. `None`: [`index::OVERRIDE_ENV`] or the bundled copy.
    pub index: Option<&'a Path>,
    /// The current `autumn-web` release.
    pub against: &'a str,
    /// Emit JSON.
    pub json: bool,
}

/// The JSON document `check --format json` prints.
#[must_use]
pub fn check_json(loaded: &index::Loaded, against: &str) -> serde_json::Value {
    let findings = index::check(&loaded.index, against);
    serde_json::json!({
        "index": source_label(&loaded.source),
        "autumn_web": against,
        "passed": findings.is_empty(),
        "findings": findings,
    })
}

/// Where the index came from, for output.
fn source_label(source: &index::Source) -> String {
    match source {
        index::Source::Bundled => "(bundled)".to_owned(),
        index::Source::Override(path) => path.display().to_string(),
    }
}

/// Run `autumn plugin index check`. Returns the exit code.
#[must_use]
pub fn run_check(opts: &CheckOptions<'_>) -> i32 {
    let loaded = opts
        .index
        .map_or_else(index::load_from_env, |path| index::load(Some(path)));
    let loaded = match loaded {
        Ok(loaded) => loaded,
        Err(err) => {
            eprintln!("autumn plugin index check: {err}");
            return 1;
        }
    };
    let findings = index::check(&loaded.index, opts.against);
    if opts.json {
        let document = check_json(&loaded, opts.against);
        println!(
            "{}",
            serde_json::to_string_pretty(&document).unwrap_or_else(|_| "{}".to_owned())
        );
    } else {
        let source = source_label(&loaded.source);
        println!("{}", render_findings(&findings, &source, opts.against));
    }
    i32::from(!findings.is_empty())
}

/// Options for `autumn plugin index record`.
#[derive(Debug, Clone)]
pub struct RecordOptions<'a> {
    /// The index file to update.
    pub index: &'a Path,
    /// `autumn plugin-check --format json` reports.
    pub reports: &'a [PathBuf],
    /// `autumn plugin inspect --format json` reports, for sandboxed listings.
    pub inspects: &'a [PathBuf],
    /// Exempt listings whose install gate passed.
    pub exempt: &'a [String],
    /// Exempt listings whose install gate failed.
    pub exempt_failed: &'a [String],
    /// The `autumn-web` release the runs used.
    pub against: &'a str,
    /// The run date, `YYYY-MM-DD`.
    pub date: &'a str,
}

/// Run `autumn plugin index record`. Returns the exit code.
#[must_use]
pub fn run_record(opts: &RecordOptions<'_>) -> i32 {
    match record(opts) {
        Ok(lines) => {
            for line in lines {
                println!("{line}");
            }
            0
        }
        Err(err) => {
            eprintln!(
                "autumn plugin index record: {}. The index was not changed.",
                index::sanitize(&err)
            );
            1
        }
    }
}

/// The listing for `name` in the index text as it stands now, so each
/// result builds on the last.
fn listing_in(src: &str, name: &str) -> Result<Listing, String> {
    index::parse(src)
        .map_err(|e| e.to_string())?
        .get(name)
        .cloned()
        .ok_or_else(|| format!("the index has no listing for `{}`", index::sanitize(name)))
}

/// Apply every report and exemption, then write the file once. Nothing is
/// written when any step fails, or when the result breaks an admission rule.
fn record(opts: &RecordOptions<'_>) -> Result<Vec<String>, String> {
    if chrono::NaiveDate::parse_from_str(opts.date, "%Y-%m-%d").is_err() {
        return Err(format!("`--date {}` is not a YYYY-MM-DD date", opts.date));
    }
    if semver::Version::parse(opts.against).is_err() {
        return Err(format!(
            "`--against {}` is not a semver version",
            opts.against
        ));
    }
    let mut src = std::fs::read_to_string(opts.index)
        .map_err(|e| format!("{}: {e}", opts.index.display()))?;
    let mut lines = Vec::new();
    // One result per listing per run: with two, the order of the arguments
    // would decide the trust state.
    let mut seen: Vec<String> = Vec::new();
    let mut claim = |name: &str| {
        let key = index::canonical(name);
        if seen.contains(&key) {
            return Err(format!(
                "`{name}` has more than one result in this run (--report, --inspect, --exempt \
                 or --exempt-failed). Record one per listing; nothing was written"
            ));
        }
        seen.push(key);
        Ok(())
    };

    for path in opts.reports {
        let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
        let report: ConformanceReport = serde_json::from_str(&text)
            .map_err(|e| format!("{} is not a plugin-check JSON report: {e}", path.display()))?;
        check_tested_release(&report, opts.against)?;
        let mut listing = listing_in(&src, &report.plugin_name)?;
        claim(&listing.name)?;
        let transition = apply_report(&mut listing, &report, opts.against, opts.date)?;
        src = write_listing(&src, &listing)?;
        lines.push(format!(
            "{}: {transition:?} on autumn-web {}",
            listing.name, opts.against
        ));
    }
    for path in opts.inspects {
        let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
        let report: InspectReport = serde_json::from_str(&text).map_err(|e| {
            format!(
                "{} is not a plugin inspect JSON report: {e}",
                path.display()
            )
        })?;
        let mut listing = listing_in(&src, &report.name)?;
        claim(&listing.name)?;
        let transition = apply_inspect(&mut listing, &report, opts.against, opts.date)?;
        src = write_listing(&src, &listing)?;
        lines.push(format!(
            "{}: {transition:?} on autumn-web {}",
            listing.name, opts.against
        ));
    }
    for name in opts.exempt {
        let mut listing = listing_in(&src, name)?;
        claim(&listing.name)?;
        apply_exempt(&mut listing, opts.against, opts.date)?;
        src = write_listing(&src, &listing)?;
        lines.push(format!(
            "{name}: exempt, refreshed for autumn-web {}",
            opts.against
        ));
    }
    for name in opts.exempt_failed {
        let mut listing = listing_in(&src, name)?;
        claim(&listing.name)?;
        let transition = apply_exempt_failed(&mut listing, opts.against, opts.date)?;
        src = write_listing(&src, &listing)?;
        lines.push(format!(
            "{name}: exempt, {transition:?} on autumn-web {}",
            opts.against
        ));
    }

    let result = index::parse(&src).map_err(|e| e.to_string())?;
    let findings = index::validate(&result);
    if !findings.is_empty() {
        return Err(format!(
            "the result breaks {} admission rule(s), first: {}: {}",
            findings.len(),
            findings[0].plugin,
            findings[0].message
        ));
    }
    std::fs::write(opts.index, &src).map_err(|e| format!("{}: {e}", opts.index.display()))?;
    Ok(lines)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugin_check::CheckResult;
    use autumn_web::plugin_contract::PluginContract;

    fn listing(name: &str) -> Listing {
        index::parse(index::BUNDLED)
            .expect("bundled")
            .get(name)
            .expect("listing")
            .clone()
    }

    fn check(name: &str, status: CheckStatus) -> CheckResult {
        CheckResult {
            name: name.to_owned(),
            status,
            message: String::new(),
            diagnostics: vec![],
        }
    }

    fn report(name: &str, pass: bool, contract: Option<PluginContract>) -> ConformanceReport {
        ConformanceReport {
            plugin_name: name.to_owned(),
            checks: vec![
                check("installability", CheckStatus::Pass),
                check("route-attribution", CheckStatus::Pass),
                check(
                    "route-collision",
                    if pass {
                        CheckStatus::Pass
                    } else {
                        CheckStatus::Fail
                    },
                ),
                check("plugin-contract", CheckStatus::Pass),
                check("experimental-surface", CheckStatus::Pass),
                check("route-prefix", CheckStatus::Pass),
                check("sensitive-surfaces", CheckStatus::Pass),
                check("duplicate-registration", CheckStatus::Pass),
            ],
            contract,
            autumn_web: None,
            // The prefix its `route-prefix` check tested: the fixtures'.
            prefix: Some("/admin".to_owned()),
            intentional_root: Vec::new(),
        }
    }

    fn lockstep(name: &str, version: &str) -> PluginContract {
        autumn_web::plugin_contract::lockstep_contract(name, version)
    }

    // ── apply_report ────────────────────────────────────────────────────

    /// A `no_routes` listing needs a report made under `--no-routes` that
    /// found none: a plain run passes a plugin that mounts routes.
    #[test]
    fn a_routeless_listing_needs_a_no_routes_report() {
        let mut l = listing("autumn-search");
        assert!(l.no_routes);
        let before = l.clone();
        let contract = Some(lockstep("autumn-search", "0.7.0"));
        let err = apply_report(
            &mut l,
            &report("autumn-search", true, contract.clone()),
            "0.7.0",
            "2026-10-01",
        )
        .unwrap_err();
        assert!(err.contains("--no-routes"), "{err}");
        assert_eq!(l, before);
        let mut r = report("autumn-search", true, contract);
        for c in &mut r.checks {
            if c.name == "route-attribution" {
                c.status = CheckStatus::Skip;
            }
        }
        apply_report(&mut l, &r, "0.7.0", "2026-10-01").expect("no routes were found");
    }

    /// A `route-prefix` pass is evidence only for the prefix it tested:
    /// `--prefix /` admits every route and cannot vouch for `/admin`.
    #[test]
    fn a_report_must_test_the_listings_prefix() {
        let mut l = listing("autumn-admin-plugin");
        assert_eq!(l.prefix, "/admin");
        let before = l.clone();
        let contract = Some(lockstep("autumn-admin-plugin", "0.7.0"));
        for tested in [Some("/"), Some("/other"), None] {
            let mut r = report("autumn-admin-plugin", true, contract.clone());
            r.prefix = tested.map(str::to_owned);
            let err = apply_report(&mut l, &r, "0.7.0", "2026-10-01").unwrap_err();
            assert!(err.contains("/admin"), "{tested:?}: {err}");
            assert_eq!(l, before);
        }
        // A trailing slash is the same prefix.
        let mut r = report("autumn-admin-plugin", true, contract);
        r.prefix = Some("/admin/".to_owned());
        apply_report(&mut l, &r, "0.7.0", "2026-10-01").expect("the listing's prefix");
    }

    /// A pass that leaned on `--intentional-root` cannot be replayed by
    /// reverification, which has no way to pass the exemption, so the index
    /// refuses it rather than listing a plugin that would then fail (#2828).
    /// A failing report still flags.
    #[test]
    fn a_pass_that_leans_on_intentional_root_routes_is_refused() {
        let mut l = listing("autumn-admin-plugin");
        let before = l.clone();
        let contract = Some(lockstep("autumn-admin-plugin", "0.7.0"));
        let mut r = report("autumn-admin-plugin", true, contract.clone());
        r.intentional_root = vec!["/webhook".to_owned()];
        let err = apply_report(&mut l, &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("--intentional-root"), "{err}");
        assert_eq!(l, before);

        let mut failing = report("autumn-admin-plugin", false, contract);
        failing.intentional_root = vec!["/webhook".to_owned()];
        apply_report(&mut l, &failing, "0.7.0", "2026-10-01").expect("a fail still flags");
    }

    /// AC 4: a pass on a new release refreshes the listing for it.
    #[test]
    fn a_pass_lists_the_plugin_on_the_new_release() {
        let mut l = listing("autumn-admin-plugin");
        let r = report(
            "autumn-admin-plugin",
            true,
            Some(lockstep("autumn-admin-plugin", "0.8.0")),
        );
        let t = apply_report(&mut l, &r, "0.8.0", "2026-10-01").expect("apply");
        assert_eq!(t, Transition::Listed);
        assert_eq!(l.status, Status::Listed);
        assert_eq!(l.conformance.result, CheckOutcome::Pass);
        assert_eq!(l.conformance.autumn_web, "0.8.0");
        assert_eq!(l.conformance.checked, "2026-10-01");
        // The range and version come from the contract, not a hand edit.
        assert_eq!(l.autumn_web, "0.8");
        assert_eq!(l.version, "0.8.0");
    }

    /// AC 4: a failed re-verification flags the listing incompatible and
    /// names the failed checks.
    #[test]
    fn a_fail_flags_the_listing() {
        let mut l = listing("autumn-admin-plugin");
        let r = report("autumn-admin-plugin", false, None);
        let t = apply_report(&mut l, &r, "0.8.0", "2026-10-01").expect("apply");
        assert_eq!(t, Transition::Flagged);
        assert_eq!(l.status, Status::Incompatible);
        assert_eq!(l.conformance.result, CheckOutcome::Fail);
        assert!(l.note.contains("route-collision"), "{}", l.note);
        assert!(l.note.contains("0.8.0"), "{}", l.note);
    }

    /// AC 4: a second fail on a later release delists it.
    #[test]
    fn a_second_fail_on_a_later_release_delists_the_listing() {
        let mut l = listing("autumn-admin-plugin");
        let r = report("autumn-admin-plugin", false, None);
        apply_report(&mut l, &r, "0.8.0", "2026-10-01").expect("flag");
        let t = apply_report(&mut l, &r, "0.9.0", "2026-11-01").expect("delist");
        assert_eq!(t, Transition::Delisted);
        assert_eq!(l.status, Status::Delisted);
        assert!(
            l.note.contains("0.8.0") && l.note.contains("0.9.0"),
            "{}",
            l.note
        );
    }

    /// A second run on the SAME release is a retry, not a second release.
    #[test]
    fn a_repeat_fail_on_the_same_release_stays_flagged() {
        let mut l = listing("autumn-admin-plugin");
        let r = report("autumn-admin-plugin", false, None);
        apply_report(&mut l, &r, "0.8.0", "2026-10-01").expect("flag");
        let t = apply_report(&mut l, &r, "0.8.0", "2026-10-02").expect("retry");
        assert_eq!(t, Transition::Flagged);
    }

    /// A pass after a flag relists and clears the note.
    #[test]
    fn a_pass_after_a_flag_relists() {
        let mut l = listing("autumn-admin-plugin");
        apply_report(
            &mut l,
            &report("autumn-admin-plugin", false, None),
            "0.8.0",
            "2026-10-01",
        )
        .expect("flag");
        apply_report(
            &mut l,
            &report(
                "autumn-admin-plugin",
                true,
                Some(lockstep("autumn-admin-plugin", "0.8.0")),
            ),
            "0.8.0",
            "2026-10-02",
        )
        .expect("relist");
        assert_eq!(l.status, Status::Listed);
        assert!(l.note.is_empty(), "{}", l.note);
    }

    /// AC 5: the tier comes from the contract the report carries.
    #[test]
    fn the_tier_follows_the_declared_experimental_surface() {
        let surface = autumn_web::plugin_contract::experimental_surface_names()
            .next()
            .expect("surface");
        let contract = lockstep("autumn-admin-plugin", "0.7.0").uses_experimental(surface);
        let mut l = listing("autumn-admin-plugin");
        apply_report(
            &mut l,
            &report("autumn-admin-plugin", true, Some(contract)),
            "0.7.0",
            "2026-10-01",
        )
        .expect("apply");
        assert_eq!(l.tier, Tier::Experimental);
        assert_eq!(l.experimental_surfaces, [surface]);
    }

    /// AC 3: a pass lists only with a declared range, from the contract.
    #[test]
    fn a_passing_report_without_a_contract_is_refused() {
        let mut l = listing("autumn-admin-plugin");
        let r = report("autumn-admin-plugin", true, None);
        let err = apply_report(&mut l, &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("contract"), "{err}");
    }

    /// A hand-made report with no checks is not a plugin-check run.
    #[test]
    fn a_report_without_the_standard_checks_is_refused() {
        let mut l = listing("autumn-admin-plugin");
        let contract = Some(lockstep("autumn-admin-plugin", "0.7.0"));
        let mut r = report("autumn-admin-plugin", true, contract);
        r.checks.retain(|c| c.name != "plugin-contract");
        let err = apply_report(&mut l, &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("plugin-contract"), "{err}");
        r.checks.clear();
        assert!(apply_report(&mut l, &r, "0.7.0", "2026-10-01").is_err());
    }

    /// A delisted listing stays delisted when a retry fails again.
    #[test]
    fn a_delisted_listing_stays_delisted_on_a_retry() {
        let mut l = listing("autumn-admin-plugin");
        let r = report("autumn-admin-plugin", false, None);
        apply_report(&mut l, &r, "0.8.0", "2026-10-01").expect("flag");
        apply_report(&mut l, &r, "0.9.0", "2026-11-01").expect("delist");
        let t = apply_report(&mut l, &r, "0.9.0", "2026-11-02").expect("retry");
        assert_eq!(t, Transition::Delisted);
        assert_eq!(l.status, Status::Delisted);
    }

    /// The pin is what was built. A contract that reports another version
    /// does not move it.
    #[test]
    fn a_community_contract_version_must_match_the_pin() {
        let mut l = listing("autumn-admin-plugin");
        l.origin = ListingOrigin::Community;
        l.name = "autumn-plugin-x".to_owned();
        l.version = "0.3.0".to_owned();
        let before = l.clone();
        let mut contract = lockstep("autumn-plugin-x", "0.7.0");
        contract.plugin_version = Some("0.4.0".to_owned());
        let r = report("autumn-plugin-x", true, Some(contract));
        let err = apply_report(&mut l, &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("0.4.0") && err.contains("0.3.0"), "{err}");
        assert_eq!(l, before);
    }

    /// A passing community report must name the version it built: without
    /// one, a check of 0.2 could verify a listing pinned at 0.3.
    #[test]
    fn a_community_contract_must_name_its_version() {
        let mut l = listing("autumn-admin-plugin");
        l.origin = ListingOrigin::Community;
        l.name = "autumn-plugin-x".to_owned();
        l.version = "0.3.0".to_owned();
        let before = l.clone();
        let mut contract = lockstep("autumn-plugin-x", "0.7.0");
        contract.plugin_version = None;
        let r = report("autumn-plugin-x", true, Some(contract.clone()));
        let err = apply_report(&mut l, &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("plugin_version"), "{err}");
        assert_eq!(l, before);
        // The pinned version passes.
        contract.plugin_version = Some("0.3.0".to_owned());
        let r = report("autumn-plugin-x", true, Some(contract));
        apply_report(&mut l, &r, "0.7.0", "2026-10-01").expect("the pin was built");
    }

    /// A sandboxed listing is verified by `inspect`, never by plugin-check.
    #[test]
    fn a_plugin_check_report_for_a_sandboxed_listing_is_refused() {
        let mut l = sandboxed();
        let before = l.clone();
        let contract = Some(lockstep("autumn-plugin-hello", "0.7.0"));
        let r = report("autumn-plugin-hello", true, contract);
        let err = apply_report(&mut l, &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("--inspect"), "{err}");
        assert_eq!(l, before);
    }

    #[test]
    fn a_report_for_another_plugin_is_refused() {
        let mut l = listing("autumn-admin-plugin");
        let err = apply_report(
            &mut l,
            &report("autumn-search", true, None),
            "0.7.0",
            "2026-10-01",
        )
        .unwrap_err();
        assert!(err.contains("autumn-search"), "{err}");
    }

    // ── apply_inspect ───────────────────────────────────────────────────

    fn sandboxed() -> Listing {
        let mut l = listing("autumn-admin-plugin");
        l.name = "autumn-plugin-hello".to_owned();
        l.origin = ListingOrigin::Community;
        l.trust = index::Trust::Sandboxed;
        // The consented authority: what `inspect(true)` reports.
        let r = inspect(true);
        l.version.clone_from(&r.version);
        l.capabilities.clone_from(&r.capabilities);
        l.routes = r.route_names();
        l.grants = index::Grants::from(&r.grants);
        l.quotas.clone_from(&r.quotas);
        l.limits.clone_from(&r.limits);
        l.artifact_sha256 = "00".repeat(32);
        l
    }

    /// A delta that says nothing is new, over a report that grants more
    /// than the listing records, is refused. With a delta that admits it,
    /// the listing is flagged and keeps the consented authority.
    #[test]
    fn widened_authority_is_checked_against_the_listing() {
        let widen: [fn(&mut InspectReport); 5] = [
            |r| r.capabilities.push("sql".to_owned()),
            |r| {
                r.routes.push(InspectRoute {
                    method: "POST".to_owned(),
                    path: "/hello/admin".to_owned(),
                });
            },
            |r| r.grants.hosts.push("evil.example".to_owned()),
            |r| *r.quotas.values_mut().next().unwrap() += 1,
            |r| *r.limits.get_mut("fuel").unwrap() += 1,
        ];
        for grow in widen {
            let mut r = inspect(true);
            grow(&mut r);
            let before = sandboxed();
            let mut l = before.clone();
            let err = apply_inspect(&mut l, &r, "0.7.0", "2026-10-01").unwrap_err();
            assert!(
                err.contains("grants more than the listing records"),
                "{err}"
            );
            assert_eq!(l, before);

            r.upgrade = Some(delta(&["sql"]));
            let t = apply_inspect(&mut l, &r, "0.7.0", "2026-10-01").expect("apply");
            assert_eq!(t, Transition::Flagged);
            assert_eq!(l.quotas, before.quotas);
            assert_eq!(l.limits, before.limits);
            assert_eq!(l.grants, before.grants);
            assert_eq!(l.capabilities, before.capabilities);
            assert_eq!(l.routes, before.routes);
        }
        // A raised quota for a dropped capability governs nothing.
        let mut r = inspect(true);
        r.capabilities.retain(|c| c != "kv");
        *r.quotas.get_mut("kv_reads").unwrap() += 1;
        let t = apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").expect("apply");
        assert_eq!(t, Transition::Listed);
        // Lower ceilings are less authority, not more.
        let mut r = inspect(true);
        *r.limits.get_mut("fuel").unwrap() -= 1;
        let t = apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").expect("apply");
        assert_eq!(t, Transition::Listed);
    }

    /// A complete `ConsentDelta`, with `added` capabilities.
    fn delta(added: &[&str]) -> serde_json::Value {
        let mut value =
            serde_json::to_value(autumn_web::plugin_sandbox::ConsentDelta::default()).unwrap();
        value["added_capabilities"] = serde_json::json!(added);
        value
    }

    /// An inspect report is recorded only for the release whose sandbox
    /// loaded it.
    #[test]
    fn an_inspect_report_must_name_the_release_it_loaded_in() {
        let mut r = inspect(true);
        r.autumn_web = Some("0.6.9".to_owned());
        let err = apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("autumn-web 0.6.9, not 0.7.0"), "{err}");
        r.autumn_web = None;
        let err = apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("does not say"), "{err}");
    }

    /// An empty or partial delta is not "nothing new": it is not a delta
    /// `inspect --against` wrote.
    #[test]
    fn a_partial_upgrade_delta_is_refused() {
        for partial in [
            serde_json::json!({}),
            serde_json::json!({"added_capabilities": []}),
        ] {
            let mut r = inspect(true);
            r.upgrade = Some(partial);
            let err = apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").unwrap_err();
            assert!(err.contains("upgrade"), "{err}");
        }
        let mut r = inspect(true);
        r.upgrade = Some(serde_json::json!({"added_hosts": "api.example.com"}));
        assert!(apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").is_err());
    }

    fn inspect(pass: bool) -> InspectReport {
        InspectReport {
            name: "autumn-plugin-hello".to_owned(),
            version: "0.2.0".to_owned(),
            artifact_sha256: Some("ab".repeat(32)),
            capabilities: vec!["http-request".to_owned(), "kv".to_owned()],
            routes: vec![InspectRoute {
                method: "GET".to_owned(),
                path: "/hello".to_owned(),
            }],
            loads: pass,
            conformance: ConformanceReport {
                plugin_name: "autumn-plugin-hello".to_owned(),
                checks: vec![
                    check("route-attribution", CheckStatus::Pass),
                    check("route-prefix", CheckStatus::Pass),
                    check("route-collision", CheckStatus::Pass),
                ],
                contract: None,
                autumn_web: None,
                prefix: None,
                intentional_root: Vec::new(),
            },
            // A baseline with nothing new: the new artifact asks for no more.
            upgrade: Some(delta(&[])),
            upgrade_against: Some("00".repeat(32)),
            grants: InspectGrants::default(),
            autumn_web: Some("0.7.0".to_owned()),
            quotas: autumn_web::plugin_sandbox::CapabilityQuotas::default()
                .fields()
                .into_iter()
                .map(|(k, v)| (k.to_owned(), v))
                .collect(),
            limits: autumn_web::plugin_sandbox::ResourceLimits::default()
                .fields()
                .into_iter()
                .map(|(k, v)| (k.to_owned(), u64::try_from(v).unwrap()))
                .collect(),
        }
    }

    /// `grants` and each of its lists are required, not defaulted.
    #[test]
    fn an_inspect_report_without_grants_does_not_parse() {
        let full = serde_json::json!({
            "name": "autumn-plugin-hello", "version": "0.2.0",
            "artifact_sha256": "ab".repeat(32), "capabilities": [], "routes": [], "loads": true,
            "conformance": {"plugin_name": "autumn-plugin-hello", "checks": []},
            "quotas": {}, "limits": {},
            "grants": {"hosts": [], "tables": [], "job_types": [], "slots": []},
        });
        assert!(serde_json::from_value::<InspectReport>(full.clone()).is_ok());
        let mut no_grants = full.clone();
        no_grants.as_object_mut().unwrap().remove("grants");
        assert!(serde_json::from_value::<InspectReport>(no_grants).is_err());
        let mut no_hosts = full;
        no_hosts["grants"].as_object_mut().unwrap().remove("hosts");
        assert!(serde_json::from_value::<InspectReport>(no_hosts).is_err());
    }

    /// A report missing an authority map (older, truncated or hand-edited)
    /// would erase the recorded ceilings. `inspect` always emits every key.
    #[test]
    fn an_inspect_report_missing_quotas_or_limits_is_refused() {
        let mut r = inspect(true);
        r.quotas.clear();
        let err = apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("quotas"), "{err}");
        let mut r = inspect(true);
        r.limits.remove("fuel");
        let err = apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("fuel"), "{err}");
    }

    /// A failed run keeps the last verified range, version and tier: the
    /// failed contract may not even parse, and the flag must still be written.
    #[test]
    fn a_failed_report_keeps_the_last_verified_contract_fields() {
        let mut l = listing("autumn-admin-plugin");
        let before = l.clone();
        let mut contract = lockstep("autumn-admin-plugin", "9.9.9");
        contract.autumn_web = Some("not a range".to_owned());
        let r = report("autumn-admin-plugin", false, Some(contract));
        apply_report(&mut l, &r, "0.7.0", "2026-10-01").expect("flag");
        assert_eq!(l.status, Status::Incompatible);
        assert_eq!(l.autumn_web, before.autumn_web);
        assert_eq!(l.version, before.version);
        assert_eq!(l.tier, before.tier);
        let one = index::PluginIndex {
            schema: index::SCHEMA,
            plugins: vec![l],
        };
        assert!(index::validate(&one).is_empty());
    }

    /// A new artifact must be compared with the recorded one: without
    /// `--against` there is no consent check, so `record` refuses it.
    #[test]
    fn a_new_artifact_without_a_baseline_is_refused() {
        let mut l = sandboxed();
        let before = l.clone();
        let mut no_baseline = inspect(true);
        no_baseline.upgrade = None;
        let err = apply_inspect(&mut l, &no_baseline, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("--against"), "{err}");
        assert_eq!(l, before, "a refusal changes nothing");

        // A delta against any other artifact (here: itself) is refused too.
        let mut self_baseline = inspect(true);
        self_baseline.upgrade_against = self_baseline.artifact_sha256.clone();
        let err = apply_inspect(&mut l, &self_baseline, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("--against"), "{err}");
        assert_eq!(l, before);

        // The same digest needs no baseline: nothing changed.
        let mut same = inspect(true);
        same.upgrade = None;
        same.artifact_sha256 = Some(l.artifact_sha256.clone());
        assert!(apply_inspect(&mut l, &same, "0.7.0", "2026-10-01").is_ok());
    }

    /// `inspect` always runs the route checks over the manifest. A report
    /// that skips one was edited, and would hide a failure.
    #[test]
    fn an_inspect_report_that_skips_a_route_check_is_refused() {
        for name in ["route-attribution", "route-prefix", "route-collision"] {
            let mut r = inspect(true);
            for c in &mut r.conformance.checks {
                if c.name == name {
                    c.status = CheckStatus::Skip;
                }
            }
            let err = apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").unwrap_err();
            assert!(err.contains(&format!("skips `{name}`")), "{err}");
        }
    }

    /// AC 6: the scoped grants are recorded, not only capability names.
    #[test]
    fn an_inspect_pass_records_the_scoped_grants() {
        // A first recording: no consented artifact to compare with.
        let mut l = sandboxed();
        l.artifact_sha256.clear();
        let mut r = inspect(true);
        r.grants.hosts = vec!["api.example.com".to_owned()];
        r.grants.tables = vec!["notes".to_owned()];
        apply_inspect(&mut l, &r, "0.7.0", "2026-10-01").expect("apply");
        assert_eq!(l.grants.hosts, ["api.example.com"]);
        assert_eq!(l.grants.tables, ["notes"]);
    }

    /// An inspect report with no route checks, or checks for another plugin,
    /// is not an `inspect` run.
    #[test]
    fn an_inspect_report_without_its_route_checks_is_refused() {
        let mut r = inspect(true);
        r.conformance.checks.clear();
        let err = apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("route-attribution"), "{err}");

        let mut r = inspect(true);
        r.conformance.plugin_name = "autumn-plugin-other".to_owned();
        assert!(apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").is_err());
    }

    /// A raised resource limit is authority too.
    #[test]
    fn an_inspect_pass_records_the_limits() {
        let mut l = sandboxed();
        let mut r = inspect(true);
        r.limits.insert("fuel".to_owned(), 1_000);
        apply_inspect(&mut l, &r, "0.7.0", "2026-10-01").expect("apply");
        assert_eq!(l.limits.get("fuel"), Some(&1_000));
    }

    /// A raised quota is authority: the approved ceilings are recorded.
    #[test]
    fn an_inspect_pass_records_the_quotas() {
        // A first recording: no consented artifact to compare with.
        let mut l = sandboxed();
        l.artifact_sha256.clear();
        let mut r = inspect(true);
        r.quotas.insert("kv_reads".to_owned(), 500);
        apply_inspect(&mut l, &r, "0.7.0", "2026-10-01").expect("apply");
        assert_eq!(l.quotas.get("kv_reads"), Some(&500));
    }

    /// A failed inspect keeps the artifact that was consented to.
    #[test]
    fn a_failed_inspect_keeps_the_consented_artifact() {
        let mut l = sandboxed();
        let before = l.clone();
        let mut r = inspect(true);
        r.upgrade = Some(delta(&["kv"]));
        apply_inspect(&mut l, &r, "0.7.0", "2026-10-01").expect("flag");
        assert_eq!(l.status, Status::Incompatible);
        assert_eq!(l.capabilities, before.capabilities);
        assert_eq!(l.artifact_sha256, before.artifact_sha256);
        assert_eq!(l.version, before.version);
    }

    /// `inspect --against` refuses an artifact that grows its authority.
    /// `record` must not turn that refusal into a listing.
    #[test]
    fn an_upgrade_that_needs_consent_is_flagged() {
        let mut l = sandboxed();
        let mut r = inspect(true);
        r.upgrade = Some(delta(&["kv"]));
        let t = apply_inspect(&mut l, &r, "0.7.0", "2026-10-01").expect("apply");
        assert_eq!(t, Transition::Flagged);
        assert!(l.note.contains("upgrade-consent"), "{}", l.note);

        let mut r = inspect(true);
        r.upgrade = Some(delta(&[]));
        let t = apply_inspect(&mut sandboxed(), &r, "0.7.0", "2026-10-01").expect("apply");
        assert_eq!(t, Transition::Listed);
    }

    /// AC 1: a sandboxed listing's manifest comes from the artifact.
    #[test]
    fn an_inspect_pass_records_the_manifest_and_digest() {
        let mut l = sandboxed();
        let t = apply_inspect(&mut l, &inspect(true), "0.7.0", "2026-10-01").expect("apply");
        assert_eq!(t, Transition::Listed);
        assert_eq!(l.capabilities, ["http-request", "kv"]);
        assert_eq!(l.artifact_sha256, "ab".repeat(32));
        assert_eq!(l.version, "0.2.0");
        assert_eq!(l.conformance.result, CheckOutcome::Pass);
    }

    /// One digest, one manifest: a report repeating the recorded digest must
    /// repeat its metadata, or it would rewrite what the listing vouches for.
    #[test]
    fn an_unchanged_digest_with_changed_metadata_is_refused() {
        let mut l = sandboxed();
        apply_inspect(&mut l, &inspect(true), "0.7.0", "2026-10-01").expect("apply");
        // A retry with the same bytes and the same manifest records again.
        let mut again = l.clone();
        apply_inspect(&mut again, &inspect(true), "0.7.0", "2026-10-02").expect("retry");

        let mut fewer = inspect(true);
        fewer.capabilities.pop();
        fewer.routes.clear();
        let err = apply_inspect(&mut l.clone(), &fewer, "0.7.0", "2026-10-02").unwrap_err();
        assert!(err.contains("capabilities, routes"), "{err}");

        let mut bumped = inspect(true);
        bumped.version = "0.2.1".to_owned();
        let err = apply_inspect(&mut l, &bumped, "0.7.0", "2026-10-02").unwrap_err();
        assert!(err.contains("version"), "{err}");
    }

    #[test]
    fn an_artifact_that_does_not_load_is_flagged() {
        let mut l = sandboxed();
        let t = apply_inspect(&mut l, &inspect(false), "0.7.0", "2026-10-01").expect("apply");
        assert_eq!(t, Transition::Flagged);
        assert!(l.note.contains("load"), "{}", l.note);
    }

    #[test]
    fn inspect_is_refused_for_a_native_listing() {
        let mut l = listing("autumn-admin-plugin");
        let mut r = inspect(true);
        r.name = "autumn-admin-plugin".to_owned();
        let err = apply_inspect(&mut l, &r, "0.7.0", "2026-10-01").unwrap_err();
        assert!(err.contains("sandboxed"), "{err}");
    }

    #[test]
    fn write_listing_writes_capabilities_and_digest() {
        let mut src = index::BUNDLED.to_owned();
        src.push_str(
            "\n[[plugin]]\nname = \"autumn-plugin-hello\"\ndescription = \"x\"\n\
             origin = \"community\"\nrepository = \"https://example.com/x\"\n\
             version = \"0.1.0\"\nautumn_web = \"0.7\"\ntier = \"stable\"\n\
             trust = \"sandboxed\"\ncapabilities = [\"http-request\"]\n\
             artifact_sha256 = \"0000000000000000000000000000000000000000000000000000000000000000\"\n\
             status = \"listed\"\n\n[plugin.conformance]\nresult = \"pass\"\n\
             autumn_web = \"0.7.0\"\nchecked = \"2026-09-27\"\n",
        );
        let mut l = index::parse(&src)
            .unwrap()
            .get("autumn-plugin-hello")
            .unwrap()
            .clone();
        // A first recording: no consented artifact to compare with.
        l.artifact_sha256.clear();
        let mut r = inspect(true);
        r.grants.hosts = vec!["api.example.com".to_owned()];
        r.quotas.insert("kv_reads".to_owned(), 500);
        r.limits.insert("fuel".to_owned(), 1_000);
        apply_inspect(&mut l, &r, "0.7.0", "2026-10-01").expect("apply");
        let out = write_listing(&src, &l).expect("write");
        let parsed = index::parse(&out).expect("parse");
        assert_eq!(parsed.get("autumn-plugin-hello"), Some(&l));
    }

    // ── apply_exempt ────────────────────────────────────────────────────

    #[test]
    fn an_exempt_listing_is_refreshed_for_the_release() {
        let mut l = listing("autumn-storage-s3");
        apply_exempt(&mut l, "0.8.0", "2026-10-01").expect("exempt");
        assert_eq!(l.conformance.autumn_web, "0.8.0");
        // Lockstep: the range moves to the new series, or the gate fails.
        assert_eq!(l.autumn_web, "0.8");
        let one = index::PluginIndex {
            schema: index::SCHEMA,
            plugins: vec![l.clone()],
        };
        assert!(index::check(&one, "0.8.0").is_empty());
        assert_eq!(l.conformance.result, CheckOutcome::Exempt);
        assert_eq!(l.version, "0.8.0");
    }

    /// A failed exempt check is recorded: flag, then delist on a later
    /// release. The exemption (its `reason`) stays, so a later pass recovers.
    #[test]
    fn a_failed_exempt_check_flags_then_recovers() {
        let mut l = listing("autumn-storage-s3");
        let reason = l.conformance.reason.clone();
        assert!(!reason.is_empty());
        let t = apply_exempt_failed(&mut l, "0.8.0", "2026-10-01").expect("flag");
        assert_eq!(t, Transition::Flagged);
        assert_eq!(l.status, Status::Incompatible);
        assert_eq!(l.conformance.result, CheckOutcome::Fail);
        assert_eq!(l.conformance.reason, reason);
        let one = |l: &Listing| index::PluginIndex {
            schema: index::SCHEMA,
            plugins: vec![l.clone()],
        };
        assert!(
            index::validate(&one(&l)).is_empty(),
            "{:?}",
            index::validate(&one(&l))
        );
        // Recovery: the next passing compile relists it as exempt.
        apply_exempt(&mut l, "0.8.0", "2026-10-02").expect("recover");
        assert_eq!(l.status, Status::Listed);
        assert_eq!(l.conformance.result, CheckOutcome::Exempt);
        assert!(l.note.is_empty());
        // Two failures on different releases delist it.
        apply_exempt_failed(&mut l, "0.8.0", "2026-10-03").expect("flag");
        let t = apply_exempt_failed(&mut l, "0.9.0", "2026-11-01").expect("delist");
        assert_eq!(t, Transition::Delisted);
    }

    #[test]
    fn a_plugin_listing_cannot_be_recorded_as_exempt_failed() {
        let mut l = listing("autumn-admin-plugin");
        assert!(apply_exempt_failed(&mut l, "0.8.0", "2026-10-01").is_err());
    }

    #[test]
    fn a_plugin_listing_cannot_be_refreshed_as_exempt() {
        let mut l = listing("autumn-admin-plugin");
        let err = apply_exempt(&mut l, "0.8.0", "2026-10-01").unwrap_err();
        assert!(err.contains("report"), "{err}");
    }

    // ── write_listing ───────────────────────────────────────────────────

    /// `record` edits only the fields it owns: comments and order stay.
    #[test]
    fn write_listing_keeps_comments_and_updates_fields() {
        let mut l = listing("autumn-admin-plugin");
        apply_report(
            &mut l,
            &report("autumn-admin-plugin", false, None),
            "0.7.0",
            "2026-10-01",
        )
        .expect("flag");
        let out = write_listing(index::BUNDLED, &l).expect("write");
        assert!(out.starts_with("# The Autumn plugin index"), "comment lost");
        let parsed = index::parse(&out).expect("still parses");
        assert_eq!(parsed.get("autumn-admin-plugin"), Some(&l));
        assert_eq!(
            parsed.get("autumn-search"),
            index::parse(index::BUNDLED)
                .expect("bundled")
                .get("autumn-search"),
            "other listings must not change"
        );
    }

    /// Clearing a note removes the key rather than writing `note = ""`.
    #[test]
    fn write_listing_removes_empty_optional_keys() {
        let mut l = listing("autumn-admin-plugin");
        apply_report(
            &mut l,
            &report("autumn-admin-plugin", false, None),
            "0.7.0",
            "2026-10-01",
        )
        .expect("flag");
        let flagged = write_listing(index::BUNDLED, &l).expect("write");
        apply_report(
            &mut l,
            &report(
                "autumn-admin-plugin",
                true,
                Some(lockstep("autumn-admin-plugin", "0.7.0")),
            ),
            "0.7.0",
            "2026-10-02",
        )
        .expect("relist");
        let out = write_listing(&flagged, &l).expect("write");
        assert!(!out.contains("note ="), "{out}");
    }

    #[test]
    fn write_listing_refuses_an_unknown_name() {
        let mut l = listing("autumn-admin-plugin");
        l.name = "autumn-plugin-ghost".to_owned();
        assert!(write_listing(index::BUNDLED, &l).is_err());
    }

    // ── render_findings ─────────────────────────────────────────────────

    #[test]
    fn findings_render_one_per_line_with_a_count() {
        let findings = vec![index::Finding {
            plugin: "autumn-plugin-x".to_owned(),
            message: "last verified against autumn-web 0.7.0; re-verify against 0.8.0".to_owned(),
        }];
        let out = render_findings(&findings, "index.toml", "0.8.0");
        assert!(out.contains("1 finding"), "{out}");
        assert!(out.contains("autumn-plugin-x: last verified"), "{out}");
        let hostile = vec![index::Finding {
            plugin: "autumn-plugin-x\u{1b}]0;PWN\u{7}".to_owned(),
            message: "`kv\u{1b}[2J` is not a sandbox capability".to_owned(),
        }];
        let out = render_findings(&hostile, "index.toml", "0.8.0");
        assert!(!out.contains(['\u{1b}', '\u{7}']), "{out:?}");
        let clean = render_findings(&[], "index.toml", "0.8.0");
        assert!(clean.contains("passes"), "{clean}");
    }

    // ── run_record end to end ───────────────────────────────────────────

    #[test]
    fn run_record_writes_reports_into_the_index_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let index_path = dir.path().join("index.toml");
        std::fs::write(&index_path, index::BUNDLED).expect("write index");
        let report_path = dir.path().join("admin.json");
        let r = report("autumn-admin-plugin", false, None);
        std::fs::write(&report_path, serde_json::to_string(&r).expect("json")).expect("write");

        let code = run_record(&RecordOptions {
            index: &index_path,
            inspects: &[],
            reports: &[report_path],
            exempt: &["autumn-storage-s3".to_owned()],
            exempt_failed: &[],
            against: "0.7.0",
            date: "2026-10-01",
        });
        assert_eq!(code, 0);
        let written =
            index::parse(&std::fs::read_to_string(&index_path).expect("read")).expect("parse");
        let admin = written.get("autumn-admin-plugin").expect("admin");
        assert_eq!(admin.status, Status::Incompatible);
        let s3 = written.get("autumn-storage-s3").expect("s3");
        assert_eq!(s3.conformance.checked, "2026-10-01");
    }

    fn write_report(dir: &Path, file: &str, r: &ConformanceReport) -> PathBuf {
        let path = dir.join(file);
        std::fs::write(&path, serde_json::to_string(r).expect("json")).expect("write");
        path
    }

    /// Two results for one listing (here a fail, then a pass) are refused.
    #[test]
    fn run_record_refuses_two_results_for_one_listing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let index_path = dir.path().join("index.toml");
        std::fs::write(&index_path, index::BUNDLED).expect("write index");
        let release = env!("CARGO_PKG_VERSION");
        let fail = write_report(
            dir.path(),
            "fail.json",
            &report("autumn-admin-plugin", false, None),
        );
        let mut ok = report(
            "autumn-admin-plugin",
            true,
            Some(lockstep("autumn-admin-plugin", release)),
        );
        ok.autumn_web = Some(release.to_owned());
        let pass = write_report(dir.path(), "pass.json", &ok);
        let code = run_record(&RecordOptions {
            index: &index_path,
            inspects: &[],
            reports: &[fail, pass],
            exempt: &[],
            exempt_failed: &[],
            against: release,
            date: "2026-10-01",
        });
        // With two, the argument order would decide the status.
        assert_eq!(code, 1);
        assert_eq!(
            std::fs::read_to_string(&index_path).unwrap(),
            index::BUNDLED
        );
    }

    /// A pass must carry every check `plugin-check` always emits, and
    /// `route-prefix` when the listing declares a prefix: a cut report would
    /// otherwise hide the check that failed.
    #[test]
    fn a_pass_missing_an_emitted_check_is_refused() {
        let contract = || Some(lockstep("autumn-admin-plugin", "0.8.0"));
        for cut in [
            "sensitive-surfaces",
            "duplicate-registration",
            "route-collision",
        ] {
            let mut r = report("autumn-admin-plugin", true, contract());
            r.checks.retain(|c| c.name != cut);
            let err = apply_report(
                &mut listing("autumn-admin-plugin"),
                &r,
                "0.8.0",
                "2026-10-01",
            )
            .unwrap_err();
            assert!(err.contains(cut), "{err}");
        }
        let mut r = report("autumn-admin-plugin", true, contract());
        r.checks.retain(|c| c.name != "route-prefix");
        let mut prefixed = listing("autumn-admin-plugin");
        prefixed.prefix = "/admin".to_owned();
        assert!(apply_report(&mut prefixed, &r, "0.8.0", "2026-10-01").is_err());
        let mut bare = listing("autumn-admin-plugin");
        bare.prefix.clear();
        assert!(apply_report(&mut bare, &r, "0.8.0", "2026-10-01").is_ok());
    }

    /// A report is recorded for the release it tested, and a pass must say
    /// which that was.
    #[test]
    fn a_report_must_name_the_release_it_tested() {
        let mut pass = report("autumn-admin-plugin", true, None);
        assert!(
            check_tested_release(&pass, "0.7.1")
                .unwrap_err()
                .contains("does not say")
        );
        pass.autumn_web = Some("0.7.0".to_owned());
        let err = check_tested_release(&pass, "0.7.1").unwrap_err();
        assert!(err.contains("tested autumn-web 0.7.0, not 0.7.1"), "{err}");
        assert!(check_tested_release(&pass, "0.7.0").is_ok());
        // A failed install names no release, and is still a failure.
        let fail = report("autumn-admin-plugin", false, None);
        assert!(check_tested_release(&fail, "0.7.1").is_ok());
    }

    /// `run_record` refuses a stale pass and writes nothing.
    #[test]
    fn run_record_refuses_a_report_from_another_release() {
        let dir = tempfile::tempdir().expect("tempdir");
        let index_path = dir.path().join("index.toml");
        std::fs::write(&index_path, index::BUNDLED).expect("write index");
        let mut r = report(
            "autumn-admin-plugin",
            true,
            Some(lockstep("autumn-admin-plugin", "0.7.0")),
        );
        r.autumn_web = Some("0.6.9".to_owned());
        let stale = write_report(dir.path(), "stale.json", &r);
        let code = run_record(&RecordOptions {
            index: &index_path,
            inspects: &[],
            reports: &[stale],
            exempt: &[],
            exempt_failed: &[],
            against: "0.7.0",
            date: "2026-10-01",
        });
        assert_eq!(code, 1);
        assert_eq!(
            std::fs::read_to_string(&index_path).unwrap(),
            index::BUNDLED
        );
    }

    /// A result that breaks an admission rule writes nothing.
    #[test]
    fn run_record_refuses_a_result_that_breaks_a_rule() {
        let dir = tempfile::tempdir().expect("tempdir");
        let index_path = dir.path().join("index.toml");
        std::fs::write(&index_path, index::BUNDLED).expect("write index");
        let mut contract = lockstep("autumn-admin-plugin", "0.7.0");
        contract.autumn_web = Some(">=0.1".to_owned());
        let mut r = report("autumn-admin-plugin", true, Some(contract));
        r.autumn_web = Some("0.7.0".to_owned());
        let open_range = write_report(dir.path(), "open.json", &r);
        let code = run_record(&RecordOptions {
            index: &index_path,
            inspects: &[],
            reports: &[open_range],
            exempt: &[],
            exempt_failed: &[],
            against: "0.7.0",
            date: "2026-10-01",
        });
        assert_eq!(code, 1);
        assert_eq!(
            std::fs::read_to_string(&index_path).unwrap(),
            index::BUNDLED
        );
    }

    #[test]
    fn check_json_names_every_finding() {
        let loaded = index::load(None).expect("bundled");
        let value = check_json(&loaded, "99.0.0");
        assert_eq!(value["passed"], false);
        assert_eq!(value["autumn_web"], "99.0.0");
        let findings = value["findings"].as_array().expect("findings");
        assert!(!findings.is_empty());
        assert!(
            findings
                .iter()
                .all(|f| f["plugin"].is_string() && f["message"].is_string())
        );
        assert_eq!(
            check_json(&loaded, env!("CARGO_PKG_VERSION"))["passed"],
            true
        );
    }

    #[test]
    fn run_record_refuses_a_date_that_is_not_a_date() {
        let dir = tempfile::tempdir().expect("tempdir");
        let index_path = dir.path().join("index.toml");
        std::fs::write(&index_path, index::BUNDLED).expect("write index");
        let code = run_record(&RecordOptions {
            index: &index_path,
            inspects: &[],
            reports: &[],
            exempt: &["autumn-storage-s3".to_owned()],
            exempt_failed: &[],
            against: "0.7.0",
            date: "tomorrow",
        });
        assert_eq!(code, 1);
        assert_eq!(
            std::fs::read_to_string(&index_path).expect("read"),
            index::BUNDLED,
            "a refused record writes nothing"
        );
    }

    #[test]
    fn run_check_passes_the_bundled_index_on_this_release() {
        let code = run_check(&CheckOptions {
            index: None,
            against: env!("CARGO_PKG_VERSION"),
            json: false,
        });
        assert_eq!(code, 0);
    }

    #[test]
    fn run_check_fails_the_bundled_index_on_a_later_release() {
        let code = run_check(&CheckOptions {
            index: None,
            against: "99.0.0",
            json: true,
        });
        assert_eq!(code, 1);
    }
}