greengate-runtime 4.4.0

The amont hook logic: registry, dispatchers, checks and the trust model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
//! The record that turns "a declaration exists" into "the check ran".
//!
//! Moving a gate entry to commit time (`docs/checks.md`, "Moving a gate entry
//! earlier") makes the push gate skip a script because a `pre-commit`
//! declaration covers it. A declaration is a promise on paper: a commit made
//! with `--no-verify`, from a libgit2 client that runs no hooks, or on a
//! machine without amont was never judged by it — and until this module
//! existed, push time had no way to tell those commits from checked ones.
//!
//! Three hooks share one record:
//!
//! 1. **pre-commit** ([`record`]) writes a one-shot marker into `$GIT_DIR`
//!    naming the gate scripts that actually ran, bound to the tree the commit
//!    is about to write (`git write-tree` — during pre-commit the index IS
//!    the commit's content; `staged_only` parks only the working tree).
//! 2. **post-commit** ([`bind_to_head`]) consumes the marker and, when the
//!    marker's tree matches `HEAD^{tree}`, stamps the commit in a notes ref.
//!    `--no-verify` skips pre-commit but NOT post-commit, so an unchecked
//!    commit arrives here with no marker and gets no stamp — which is the
//!    entire point. The tree comparison makes an aborted commit's leftover
//!    marker harmless, and a retried commit of the SAME tree correctly
//!    stamped: the check really did run on exactly that content.
//! 3. **pre-push** ([`stamps_for`]) reads the stamps back and suppresses a
//!    gate script only for pushes whose relevant commits all carry it.
//! 4. **pre-push, on the way out** ([`stamp_push`]) writes the push-time
//!    gates that PASSED onto each pushed tip — and `amont run pre-push`,
//!    which drives the same dispatcher, writes the same stamp for `HEAD`.
//!    The next push of that tree finds the stamp and skips the gate. That is
//!    what lets the suite run BEFORE git opens its connection: a rehearsal
//!    stamps, the push verifies. And a push that passed the gate but died on
//!    the wire — a remote that dropped the idle session while the suite ran
//!    — retries in seconds instead of minutes. Push-time tokens are full
//!    ids (`pre-push-run-tests-js`), commit-time ones are script names
//!    (`test`); the two share a note and never collide.
//!
//! Every failure mode points the same direction: no marker, a mismatched
//! tree, a missing note, a rewritten hash — all mean "no stamp", and no stamp
//! means the push gate RUNS. Nothing here can let an unchecked commit
//! through; it can only cost a redundant gate run.
//!
//! # The second half of the note: what a run COST, and how it ENDED
//!
//! The token line above answers one question — may this gate be skipped for
//! this content — and it is deliberately a set, with no history in it. A
//! stamp says a gate passed; it cannot say a gate has been passing in four
//! seconds since the day its test runner stopped finding any tests.
//!
//! So the note carries optional extra lines, one per RUN:
//!
//! ```text
//! greengate-gate-v1 pre-push-cargo-test
//! run 1726900000 pre-push-cargo-test pass 412391
//! run 1726903600 pre-push-audit-js fail 903
//! ```
//!
//! Additive on purpose, and in the only direction that is safe: every reader
//! that existed before these lines did reads `body.lines().next()` and is
//! unaffected, and an amont old enough to rewrite the note without them loses
//! history — never a verdict. The `run` lines are EVIDENCE, read by
//! [`crate::gate_evidence`]; nothing in this module's skip decisions consults
//! them, so a corrupted or forged one cannot make a check be skipped.
//!
//! One more kind of line, and the one exception to that rule (ADR-0013):
//!
//! ```text
//! deferred cargo-test
//! ```
//!
//! A commit-time gate the busy policy deferred to CI. Pre-push reads it
//! ([`deferred_for`]) so the gate's push twin defers too instead of running
//! the suite with the remote's connection held open. It can only ever move a
//! gate to CI — it is never a token, never stamps, never attests — so a
//! forged line makes CI run more, never less. Kept apart from the `run`
//! history, whose [`MAX_RUNS`] trim must not forget it.
//!
//! The note's key is the tree, which makes the record a per-FINGERPRINT one
//! for free: two runs of one gate against one tree are two lines in one note,
//! and if they disagree the gate is flaky on content that did not change.
//!
//! Why a notes ref and not config: notes are keyed by commit, garbage-collect
//! with unreachable commits (an `greengate.checked.<hash>` config key would
//! outlive every rebase forever), stay local (notes refs are not pushed by
//! default), and stay out of `git log` (only `refs/notes/commits` displays by
//! default). `amont uninstall` deletes the ref; see `uninstall_repo_hooks`.

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

/// One complete set of the names a gate stamp lives under: its header, its
/// four notes refs, the domain of its canonical key, and the attest name set
/// whose input domain keys its inputs ref (decisions ADR-0068, plan
/// "greengate signs its notes under green names"). A note is read WHOLE
/// under one set: the ref it sits in names the set, and its header must be
/// that set's, so the two never mix inside one note.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct GateNames {
    /// First line of every note body (and of the marker file).
    pub format: &'static str,
    /// The tree- and commit-keyed stamps.
    pub notes_ref: &'static str,
    /// The fingerprint-keyed stamps.
    pub inputs_ref: &'static str,
    /// The cluster passes (ADR-0016).
    pub cluster_ref: &'static str,
    /// The completions that did not pass (ADR-0018).
    pub done_ref: &'static str,
    /// Domain of the canonical key in the inputs ref.
    pub canon_domain: &'static str,
    /// The attest names whose input domain keys a declared gate's
    /// fingerprint in the inputs ref.
    pub attest: git_attest::format::Names,
}

/// The names stamps were written under until greengate 4.4 (amont 1.x to
/// 4.3). Still read during the 30-day window; removed at the census.
pub(crate) const LEGACY: GateNames = GateNames {
    format: "amont-gate-v1",
    notes_ref: "amont-gate",
    inputs_ref: "amont-gate-inputs",
    cluster_ref: "amont-gate-cluster",
    done_ref: "amont-gate-done",
    canon_domain: "amont-gate-canon",
    attest: git_attest::format::LEGACY,
};

/// The names stamps are written under since greengate 4.4. Read first.
pub(crate) const GREEN: GateNames = GateNames {
    format: "greengate-gate-v1",
    notes_ref: "greengate-gate",
    inputs_ref: "greengate-gate-inputs",
    cluster_ref: "greengate-gate-cluster",
    done_ref: "greengate-gate-done",
    canon_domain: "greengate-gate-canon",
    attest: git_attest::format::GREEN,
};

/// The ONE owner of what is written: [`FORMAT`] and the short `*_REF`
/// constants below derive from it. The `*_FULL_REF` constants are literals,
/// held equal to `refs/notes/{short}` by a test. GREEN since greengate 4.4.
pub(crate) const WRITE: GateNames = GREEN;

/// The order a stamp is read in: the green set first, the legacy one only
/// for a key the green ref holds no note for.
pub(crate) const READ: [GateNames; 2] = [GREEN, LEGACY];

/// First token of the marker file and of every note body. Versioned like
/// `staged_only::FORMAT`: a future amont that changes the shape bumps this,
/// and an old record is ignored rather than misread.
pub const FORMAT: &str = WRITE.format;

/// The notes ref, spelled the way `git notes --ref` wants it.
pub const NOTES_REF: &str = WRITE.notes_ref;

/// The same ref, fully qualified — what `git update-ref -d` needs. A literal,
/// not derived from [`WRITE`]; a test holds it equal to `refs/notes/{NOTES_REF}`.
pub const NOTES_FULL_REF: &str = "refs/notes/greengate-gate";

/// The second ref: stamps keyed by a gate's declared-input fingerprint
/// (`.github/attest-inputs`, see [`crate::attest_inputs`]) instead of by the
/// whole tree. A gate whose inputs a repository declares is reused on any tree
/// where those inputs are byte-identical — the closing plan commit changes the
/// tree and none of them. Every key there is an oid that is not an object, as
/// in attest's own inputs ref, so `git notes prune` on it would drop
/// everything: never run it, and never merge the ref with `cat_sort_uniq`.
pub const INPUTS_REF: &str = WRITE.inputs_ref;

/// Where CLUSTER passes are recorded (ADR-0016): the same note format, keyed
/// by the judged tree, holding tokens of `gate_identity::cluster_token`.
/// Never `greengate-gate` (ADR-0015): a local token here would let the laptop
/// sign a pass it never ran.
pub const CLUSTER_REF: &str = WRITE.cluster_ref;
pub const CLUSTER_FULL_REF: &str = "refs/notes/greengate-gate-cluster";

/// Where a gate that COMPLETED without passing is recorded (ADR-0018): a
/// warn-severity failure, or a gate that could not run. The same note format,
/// keyed by the tree, holding `gate_identity` tokens. Never `greengate-gate`: a
/// completion is not a pass, and nothing reads this ref to attest or to skip a
/// gate in an inline push. Only the refusing push (`greengate.pushGates refuse`)
/// and land's own push read it, so that what a rehearsal or land's pre-stage
/// already ran is not refused as "not run".
pub const DONE_REF: &str = WRITE.done_ref;
pub const DONE_FULL_REF: &str = "refs/notes/greengate-gate-done";

/// The reserved first word of a provenance line: where a token came from
/// (platform, observed imageID, Job UID). Never a token, never a run, and
/// every reader of tokens drops it.
pub const PROVENANCE: &str = "provenance";
pub const INPUTS_FULL_REF: &str = "refs/notes/greengate-gate-inputs";

/// The marker's filename inside `$GIT_DIR`.
const MARKER: &str = crate::names::GATE_MARKER;

/// The switch for push-time stamps — both writing them and honouring them.
/// On by default: a stamp is amont's own record of a gate it ran on exactly
/// this content, the same trust the commit-time stamps have always carried.
const PUSH_STAMPS: &str = "greengate.pushStamps";

/// Does this repository reuse push-time stamps?
pub fn push_stamps_enabled(settings: &crate::config::Settings) -> bool {
    crate::config::boolean_or(settings, PUSH_STAMPS, true)
}

/// The switch for commit-time reuse — a pre-commit gate that already ran
/// clean against exactly this staged tree is not run again. On by default,
/// for the same reason `pushStamps` is: the record is amont's own, bound to
/// the content, and identical content is what a test suite reads.
const COMMIT_STAMPS: &str = "greengate.commitStamps";

/// Does this repository reuse a gate's verdict across commit attempts of
/// one tree?
pub fn commit_stamps_enabled(settings: &crate::config::Settings) -> bool {
    crate::config::boolean_or(settings, COMMIT_STAMPS, true)
}

/// The first word of an evidence line. A line that does not start with it is
/// not one, and is dropped rather than guessed at.
const RUN: &str = "run";

/// How many runs one note keeps, newest last. A note is read and rewritten on
/// the push path, so it has to stay small; 64 runs of one tree is already far
/// more retries than any content sees, and the statistics this feeds are
/// computed ACROSS notes, not within one.
const MAX_RUNS: usize = 64;

/// How a single run of one gate ended.
///
/// The check vocabulary, kept whole rather than flattened to pass/fail:
/// `Unavailable` is the outcome the fleet audit of 2026-09-19 kept finding —
/// a gate that could not run, reported as a warning, counted by nobody — and
/// collapsing it into "fail" would hide it all over again.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunOutcome {
    Passed,
    Failed,
    Warned,
    Fixed,
    Unavailable,
    Inert,
    // Tree gates (ADR-0024): why a commit's tree was NOT proven. None is a
    // verdict about the content; together they are the hit rate's misses.
    /// No completion marker in the current cache namespace.
    Cold,
    /// Another run held the gate's cache lock.
    Busy,
    /// The tool the gate would run is not the one CI resolves.
    Skew,
    /// The tree was not exactly the commit's (unstaged, untracked, ignored
    /// outside the allow-list, or an operation in progress).
    Withheld,
    /// Still running when the commit was ready, or past its deadline.
    Cancelled,
    /// Not started: its last run would not fit in this commit's cover plus
    /// the slack.
    Slow,
    /// Not run: the busy policy deferred it to CI (ADR-0013).
    Deferred,
}

impl RunOutcome {
    pub fn as_str(self) -> &'static str {
        match self {
            RunOutcome::Passed => "pass",
            RunOutcome::Failed => "fail",
            RunOutcome::Warned => "warn",
            RunOutcome::Fixed => "fixed",
            RunOutcome::Unavailable => "unavailable",
            RunOutcome::Inert => "inert",
            RunOutcome::Cold => "cold",
            RunOutcome::Busy => "busy",
            RunOutcome::Skew => "skew",
            RunOutcome::Withheld => "withheld",
            RunOutcome::Cancelled => "cancelled",
            RunOutcome::Slow => "slow",
            RunOutcome::Deferred => "deferred",
        }
    }

    /// The parse side. `None` for anything unknown — a future amont may write
    /// an outcome this one has never heard of, and inventing a meaning for it
    /// would be worse than dropping the line.
    pub fn parse(s: &str) -> Option<RunOutcome> {
        Some(match s {
            "pass" => RunOutcome::Passed,
            "fail" => RunOutcome::Failed,
            "warn" => RunOutcome::Warned,
            "fixed" => RunOutcome::Fixed,
            "unavailable" => RunOutcome::Unavailable,
            "inert" => RunOutcome::Inert,
            "cold" => RunOutcome::Cold,
            "busy" => RunOutcome::Busy,
            "skew" => RunOutcome::Skew,
            "withheld" => RunOutcome::Withheld,
            "cancelled" => RunOutcome::Cancelled,
            "slow" => RunOutcome::Slow,
            "deferred" => RunOutcome::Deferred,
            _ => return None,
        })
    }

    /// Did this run reach a verdict about the content? Only these two are
    /// evidence about whether a gate works — the rest are a gate declining to
    /// judge, and counting them as passes is how a no-op looks healthy.
    pub fn is_verdict(self) -> bool {
        matches!(self, RunOutcome::Passed | RunOutcome::Failed)
    }
}

/// One run of one gate: when, which, how it ended, how long it took.
///
/// Wall clock, in milliseconds, measured around the check's own `run` — not
/// CPU time and not the hook's total, because the number this exists to catch
/// is "the suite that used to take eleven minutes returned in 0.4 seconds",
/// and that is a wall-clock claim.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Run {
    /// Seconds since the epoch, as the machine that ran it saw them.
    pub at: u64,
    pub gate: String,
    pub outcome: RunOutcome,
    pub ms: u64,
}

impl Run {
    fn render(&self) -> String {
        format!(
            "{RUN} {} {} {} {}",
            self.at,
            self.gate,
            self.outcome.as_str(),
            self.ms
        )
    }

    /// `run <epoch> <gate> <outcome> <ms>`, or nothing. Every field must be
    /// there and parse; a half-understood line is dropped whole.
    fn parse(line: &str) -> Option<Run> {
        let mut t = line.split_whitespace();
        if t.next() != Some(RUN) {
            return None;
        }
        let at = t.next()?.parse().ok()?;
        let gate = t.next()?.to_string();
        let outcome = RunOutcome::parse(t.next()?)?;
        let ms = t.next()?.parse().ok()?;
        Some(Run {
            at,
            gate,
            outcome,
            ms,
        })
    }
}

/// A parsed note body: the skip tokens, and the runs recorded against this
/// key.
///
/// THE reader and THE writer of the format, so that the three callers that
/// rewrite a note cannot each drop a half of it they were not thinking
/// about. `stamp_push` merging tokens used to render the note from its own
/// token list alone, which — once runs existed — would have erased every one
/// of them on the next push.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Note {
    pub tokens: Vec<String>,
    /// Commit-time gates deferred to CI on this content; see the module
    /// documentation. Never trimmed with the runs.
    pub deferred: Vec<String>,
    pub runs: Vec<Run>,
    /// [`PROVENANCE`] lines, verbatim, kept through every rewrite.
    pub provenance: Vec<String>,
}

/// The first word of a deferral line.
const DEFERRED: &str = "deferred";

impl Note {
    /// Parse a note body. A first line that is not ours yields an EMPTY note:
    /// a note somebody else wrote into our ref vouches for nothing, and its
    /// remaining lines are not evidence either.
    pub fn parse(body: &str) -> Note {
        Note::parse_as(body, FORMAT)
    }

    /// [`Note::parse`] for a note read from a ref of the set whose header is
    /// `format`: any other first word, the other set's included, is not
    /// ours there and yields an empty note.
    pub(crate) fn parse_as(body: &str, format: &str) -> Note {
        let mut lines = body.lines();
        let Some(first) = lines.next() else {
            return Note::default();
        };
        let mut tokens = first.split_whitespace();
        if tokens.next() != Some(format) {
            return Note::default();
        }
        let mut deferred = Vec::new();
        let mut runs = Vec::new();
        let mut provenance = Vec::new();
        for line in lines {
            if is_provenance(line) {
                provenance.push(line.trim().to_string());
                continue;
            }
            let mut t = line.split_whitespace();
            match (t.next(), t.next(), t.next()) {
                (Some(DEFERRED), Some(gate), None) => {
                    if !deferred.iter().any(|d| d == gate) {
                        deferred.push(gate.to_string());
                    }
                }
                _ => runs.extend(Run::parse(line)),
            }
        }
        Note {
            tokens: tokens.map(str::to_string).collect(),
            deferred,
            runs,
            provenance,
        }
    }

    /// The bytes to hand `git notes add -m`. Line one is exactly what it has
    /// always been, so every reader that stops there sees no change at all.
    pub fn render(&self) -> String {
        let mut body = format!("{FORMAT} {}", self.tokens.join(" "));
        for gate in &self.deferred {
            body.push('\n');
            body.push_str(&format!("{DEFERRED} {gate}"));
        }
        for run in &self.runs {
            body.push('\n');
            body.push_str(&run.render());
        }
        for line in &self.provenance {
            body.push('\n');
            body.push_str(line);
        }
        body
    }

    fn add_tokens(&mut self, tokens: &[String]) {
        for t in tokens {
            if !self.tokens.iter().any(|have| have == t) {
                self.tokens.push(t.clone());
            }
        }
    }

    /// Append runs, keeping the newest [`MAX_RUNS`].
    fn add_runs(&mut self, runs: &[Run]) {
        self.runs.extend(runs.iter().cloned());
        if self.runs.len() > MAX_RUNS {
            self.runs.drain(..self.runs.len() - MAX_RUNS);
        }
    }
}

/// Is `line` a [`PROVENANCE`] line? Every token reader asks, so a line that
/// says where a pass came from can never be read as the pass itself.
pub fn is_provenance(line: &str) -> bool {
    line.split_whitespace().next() == Some(PROVENANCE)
}

/// The note at `key` in the WRITTEN ref, parsed: the base a writer merges
/// into. Only the written ref, never a note read under another name set, so
/// a rewrite can never carry the other set's tokens under this header. An
/// absent note, an absent ref and a git that would not answer are all an
/// empty note — the same direction everything here fails in.
fn note_at(key: &str) -> Note {
    note_in(NOTES_REF, key)
}

fn note_in(notes_ref: &str, key: &str) -> Note {
    crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
        .map(|body| Note::parse(&body))
        .unwrap_or_default()
}

/// The stamp at `key` as a READER sees it: the note in `which` ref of the
/// first set of [`READ`] that holds one, parsed under that set's header. A
/// green ref's note is the answer even when its header is wrong (it then
/// vouches for nothing): the legacy ref is read only for a key the green
/// ref has no note for.
fn stamp_in(which: fn(&GateNames) -> &'static str, key: &str) -> Note {
    READ.iter()
        .find_map(|set| read_in(set, which(set), key))
        .unwrap_or_default()
}

/// The note at `key` in `notes_ref`, one of `set`'s refs, parsed under
/// `set`'s header; `None` when the ref holds no note there (or git would not
/// answer, which reads the same: no stamp).
///
/// A git failure on the green ref returns `None`, so a legacy note may answer
/// in its place. That is the safe direction: the gate then re-runs, or reads
/// the older stamp.
fn read_in(set: &GateNames, notes_ref: &str, key: &str) -> Option<Note> {
    crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
        .map(|body| Note::parse_as(&body, set.format))
}

/// [`stamp_in`] on the tree- and commit-keyed ref.
fn stamp_at(key: &str) -> Note {
    stamp_in(|s| s.notes_ref, key)
}

/// The tokens of the gates `tree`'s declared inputs vouch for: for each gate
/// the spec at `tree` declares, the note filed under `K(gate, fingerprint)`.
///
/// Only a token written under that gate's own name is honoured from the note
/// at its key: a note somebody else wrote into the ref cannot vouch for a
/// gate it was not filed under. No spec, an invalid or ambiguous one, a gate
/// with no fingerprint on `tree` (a required path missing), a git that would
/// not answer: all contribute nothing, and nothing means the gate runs.
fn input_tokens(tree: &str) -> Vec<String> {
    let Some(spec) = crate::attest_inputs::spec_at(tree) else {
        return canon_tokens(tree);
    };
    let mut out: Vec<String> = Vec::new();
    for (gate, _) in &spec.gates {
        if !manifest_is_an_input(tree, &spec, gate) {
            continue;
        }
        let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
            continue;
        };
        // Each set computes its own key and reads its own ref; the legacy
        // one only when the green ref has no note at the green key.
        let note = READ.iter().find_map(|set| {
            let key = crate::attest_inputs::input_key(&set.attest, gate, &fp)?;
            read_in(set, set.inputs_ref, &key)
        });
        for t in note.unwrap_or_default().tokens {
            if crate::gate_identity::base(&t) == gate.as_str() && !out.contains(&t) {
                out.push(t);
            }
        }
    }
    out
}

/// The tokens `tree`'s canonical fingerprint vouches for: a repository that
/// declares nothing is reused on any tree that differs only in the CONTENT of
/// its plans (attest SPEC, "Canonical tree"). One note per fingerprint holds
/// the tokens of every gate that passed on it, as the tree note does for a
/// tree. A declared (even invalid) spec, an opt-out, or a git that would not
/// answer: no canonical route, nothing contributed, the gate runs.
fn canon_tokens(tree: &str) -> Vec<String> {
    let Some(canon) = crate::attest_inputs::canonical_route(tree) else {
        return Vec::new();
    };
    READ.iter()
        .find_map(|set| {
            let key = crate::attest_inputs::canon_gate_key(set.canon_domain, &canon)?;
            read_in(set, set.inputs_ref, &key)
        })
        .map(|note| note.tokens)
        .unwrap_or_default()
}

/// The key of the canonical note of `tree` in the WRITTEN set, if the
/// canonical route is open.
fn canon_key_of(tree: &str) -> Option<String> {
    let canon = crate::attest_inputs::canonical_route(tree)?;
    crate::attest_inputs::canon_gate_key(WRITE.canon_domain, &canon)
}

/// File `tokens` under the canonical key of `tree`. Best-effort and merged,
/// like [`file_inputs`]. The manifest needs no rule here: `amont.conf` is part
/// of the canonical tree, so a changed declaration is a changed fingerprint.
fn file_canon(tree: &str, tokens: &[String]) {
    let Some(key) = canon_key_of(tree) else {
        return;
    };
    let mut note = note_in(INPUTS_REF, &key);
    note.add_tokens(tokens);
    let _ = write_note_in(INPUTS_REF, &key, &note);
}

/// File `tokens` under the fingerprint keys of the gates `tree` declares, in
/// addition to wherever the caller put them by tree; with no spec at all, under
/// the canonical key. Best-effort, silent, and merged: a miss here is one
/// redundant gate run, which is the safe direction.
fn file_inputs(tree: &str, tokens: &[String]) {
    if tokens.is_empty() {
        return;
    }
    let Some(spec) = crate::attest_inputs::spec_at(tree) else {
        file_canon(tree, tokens);
        return;
    };
    for (gate, _) in &spec.gates {
        let mine: Vec<String> = tokens
            .iter()
            .filter(|t| crate::gate_identity::base(t) == gate.as_str())
            .cloned()
            .collect();
        if mine.is_empty() || !manifest_is_an_input(tree, &spec, gate) {
            continue;
        }
        let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
            continue;
        };
        let Some(key) = crate::attest_inputs::input_key(&WRITE.attest, gate, &fp) else {
            continue;
        };
        let mut note = note_in(INPUTS_REF, &key);
        note.add_tokens(&mine);
        let _ = write_note_in(INPUTS_REF, &key, &note);
    }
}

/// May a gate's stamp travel by fingerprint on `tree`? A gate's scope and its
/// opt-ins live in the manifest, and under a whole-tree key a manifest change
/// was a tree change; under a fingerprint it is one only if the gate declares
/// the manifest. So a tree that tracks its manifest offers the route only to a
/// gate whose declared inputs cover it, and a scope-only edit then misses.
fn manifest_is_an_input(tree: &str, spec: &crate::attest_inputs::Spec, gate: &str) -> bool {
    // The name the tree tracks: an unswept tree still has the 3.x one.
    let tracked = [crate::manifest::MANIFEST, crate::names::old::MANIFEST]
        .into_iter()
        .find(|name| crate::git::succeeds(&["cat-file", "-e", &format!("{tree}:{name}")]));
    tracked.map_or(true, |name| {
        crate::attest_inputs::declares(spec, gate, name)
    })
}

/// Does either set's inputs ref exist here? One spawn per set that lets a
/// repository nothing was ever filed for (an opted-out one, or one whose
/// stamps never passed) skip the fingerprint and canonical routes entirely on
/// the push path.
fn inputs_ref_exists() -> bool {
    READ.iter().any(|set| {
        crate::git::succeeds(&[
            "rev-parse",
            "-q",
            "--verify",
            &format!("refs/notes/{}", set.inputs_ref),
        ])
    })
}

/// The stamp tokens on `tree` (a tree object id). Tree gates are read here
/// and only here (ADR-0024): `tree:<name>` on the pushed tree proves the gate
/// on exactly that content, whichever commit carried it.
pub fn tree_tokens(tree: &str) -> Vec<String> {
    let mut tokens = stamp_at(tree).tokens;
    if inputs_ref_exists() {
        for t in input_tokens(tree) {
            if !tokens.contains(&t) {
                tokens.push(t);
            }
        }
    }
    tokens
}

/// Add `tokens` to the gate note on `tree` — how a rehearsal records tree
/// gates it proved in its snapshot of exactly that tree. Merged, never
/// rendered from the tokens alone, so evidence already on the note survives.
pub fn stamp_tree(tree: &str, tokens: &[String]) -> bool {
    let mut note = note_at(tree);
    note.add_tokens(tokens);
    let ok = write_note(tree, &note);
    file_inputs(tree, tokens);
    ok
}

/// Write `note` at `key`. Best-effort, like every writer here.
fn write_note(key: &str, note: &Note) -> bool {
    write_note_in(NOTES_REF, key, note)
}

fn write_note_in(notes_ref: &str, key: &str, note: &Note) -> bool {
    let body = note.render();
    crate::git::succeeds(&["notes", "--ref", notes_ref, "add", "-f", "-m", &body, key])
}

/// Record what a gate run COST and how it ENDED, against the content it ran
/// on.
///
/// Evidence only: nothing in this module reads these back to decide whether a
/// check may be skipped, which is why recording a FAILED run — the case the
/// stamp path deliberately has no opinion about — is safe here.
///
/// Best-effort and silent. A note git refused costs a row in a report nobody
/// is blocked on; warning about it on every push would train people to ignore
/// the warnings that do gate something.
pub fn record_runs(key: &str, runs: &[Run]) {
    // A gate name with whitespace in it would forge a second field on read.
    // Refused rather than escaped: every id this repository can produce is
    // already free of it, so the escaping would be a code path no real input
    // ever reaches — untested by construction.
    let runs: Vec<Run> = runs
        .iter()
        .filter(|r| !r.gate.is_empty() && !r.gate.contains(char::is_whitespace))
        .cloned()
        .collect();
    if runs.is_empty() {
        return;
    }
    let mut note = note_at(key);
    note.add_runs(&runs);
    let _ = write_note(key, &note);
}

/// pre-commit: record on `tree` (the staged tree, which is the commit's)
/// that the busy policy deferred `gates`, by their commit-time script names.
/// Best-effort and silent: a lost line runs the push twin, the safe way.
pub fn record_deferred(tree: &str, gates: &[String]) {
    let gates: Vec<&String> = gates
        .iter()
        .filter(|g| !g.is_empty() && !g.contains(char::is_whitespace))
        .collect();
    if gates.is_empty() {
        return;
    }
    let mut note = note_at(tree);
    for g in gates {
        if !note.deferred.contains(g) {
            note.deferred.push(g.clone());
        }
    }
    let _ = write_note(tree, &note); // best-effort: a lost line runs the push twin, the safe way
}

/// The commit-time gates the busy policy deferred on `tree`, by script name.
/// What `amont stamps` reports as `deferred`; never a token.
pub fn deferred_on(tree: &str) -> Vec<String> {
    stamp_at(tree).deferred
}

/// Which of `commits` carry a deferral of `gate` on their tree's note (or
/// their own). Read only to defer a push twin, never to skip one: a commit
/// in this set still has no stamp.
pub fn deferred_for(commits: &[String], gate: &str) -> HashSet<String> {
    let mut out = HashSet::new();
    if commits.is_empty() {
        return out;
    }
    let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
    args.extend(commits.iter().map(String::as_str));
    let Some(list) = crate::git::stdout(&args) else {
        return out;
    };
    for line in list.lines() {
        let mut it = line.split_whitespace();
        let (Some(commit), Some(tree)) = (it.next(), it.next()) else {
            continue;
        };
        if [commit, tree]
            .iter()
            .any(|key| stamp_at(key).deferred.iter().any(|d| d == gate))
        {
            out.insert(commit.to_string());
        }
    }
    out
}

/// `$GIT_DIR/amont-gate` — the worktree-PRIVATE gitdir, deliberately: the
/// commit this marker waits for happens in this worktree. The stamps the
/// marker becomes live in the common dir (a notes ref) and are shared.
fn marker_path() -> Option<PathBuf> {
    let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
    Some(std::path::Path::new(&dir).join(MARKER))
}

/// pre-commit: record that `scripts` ran clean against the tree the commit
/// will carry.
///
/// Called on EVERY pre-commit verdict, with an empty list when nothing
/// qualifying ran (or the commit is about to be blocked) — an aborted or
/// unchecked attempt must not inherit a previous attempt's marker.
///
/// Best-effort throughout: a failure to record costs one redundant gate run
/// at push time, which is the safe direction, and a pre-commit that failed a
/// COMMIT over bookkeeping would be the tail wagging the dog.
pub fn record(scripts: &[&str]) {
    let Some(path) = marker_path() else { return };
    if scripts.is_empty() {
        let _ = std::fs::remove_file(&path);
        return;
    }
    // The index, as the object id `git commit` is about to seal. Inherits
    // `GIT_INDEX_FILE`, so `git commit -a`'s temporary index answers here
    // too. Pure read of the index: writes objects, touches no ref.
    let Some(tree) = crate::git::stdout(&["write-tree"]) else {
        // Not "nothing ran": git could not name the tree, so nothing may be
        // vouched for. Dropping the marker is the fail-safe half (the gate
        // re-runs at push); saying so is the half that was missing.
        crate::hooks::common::warn(
            "git would not name the staged tree — this commit records no gate stamp",
        );
        let _ = std::fs::remove_file(&path);
        return;
    };
    let mut body = format!("{FORMAT}\n{tree}\n");
    for s in scripts {
        body.push_str(s);
        body.push('\n');
    }
    let _ = std::fs::write(&path, body);
}

/// pre-commit, before a gate runs: the scripts a previous run already
/// vouched for against the tree this commit is about to seal.
///
/// Two records answer, both bound to the TREE (`git write-tree` of the index
/// under the staged-only hold — the commit's content, not the working
/// tree):
///
/// 1. the one-shot marker [`record`] left behind. post-commit consumes it,
///    so a marker that is still there belongs to an attempt that never
///    reached post-commit — a `commit-msg` refusal, an editor closed on an
///    empty message, a Ctrl-C at the prompt. The gates ran, the tree is the
///    same, the verdict stands: measured on this machine, a subject three
///    characters too long replayed a ten-minute suite for nothing.
/// 2. the tree note [`bind_to_head`] writes — a reword, a `reset --soft` and
///    re-commit, or a rebase that kept the tree.
///
/// Every failure mode reads as "nothing is vouched for", which runs the
/// gate: no `write-tree`, a marker for another tree, a wrong format, a git
/// that would not answer. Reuse can only ever skip a run the record proves
/// happened on this exact content; it can never let unjudged content
/// through — the direction every function in this module fails in.
///
/// Repo-controlled inputs to the gate (its command line, its scope) live in
/// the manifest, which is part of the tree: a changed declaration is a
/// changed tree, and nothing is reused by tree. A gate reused by fingerprint
/// gets the same guarantee only if it declares the manifest as an input
/// ([`manifest_is_an_input`]); otherwise it is not offered the route at all.
pub fn vouched_for_staged_tree() -> HashSet<String> {
    let mut out = HashSet::new();
    let Some(tree) = crate::git::stdout(&["write-tree"]) else {
        return out;
    };
    if let Some(path) = marker_path() {
        if let Ok(body) = std::fs::read_to_string(&path) {
            let mut lines = body.lines();
            if lines.next() == Some(FORMAT) && lines.next() == Some(tree.as_str()) {
                out.extend(
                    lines
                        .filter(|l| !l.trim().is_empty() && !is_provenance(l))
                        .map(str::to_string),
                );
            }
        }
    }
    // The tree note: `notes show` fails loudly on an absent note, and a
    // failure here is simply "no note" — the marker's answer stands alone.
    // Tokens are `<name>@<identity>` (`gate_identity`): commit-time ones are
    // named by script, push-time ones by full id (`pre-push-…`), which no
    // pre-commit declaration is named after — harmless in the set, and a
    // reader skips only on the complete token. The note's `run` lines are evidence and are not
    // tokens: `Note` keeps the two apart so nothing here can be skipped by a
    // line that only records how long something took.
    out.extend(stamp_at(&tree).tokens);
    // A gate the repository declares inputs for is also vouched for by any
    // earlier tree whose declared inputs are byte-identical to this staged
    // tree's: a plan-only commit changes the tree and none of them. The tree
    // here is the INDEX's (`write-tree`), so partial staging is judged on what
    // is about to be committed, not on the working copy.
    if inputs_ref_exists() {
        out.extend(input_tokens(&tree));
    }
    out
}

/// post-commit: consume the marker; stamp HEAD when the tree still matches.
///
/// One-shot by construction — the marker is deleted before anything is
/// judged, so no path through here can leave it to vouch for a later commit.
///
/// Returns the scripts it actually stamped (empty on every no-stamp path,
/// including a note git refused). The caller subtracts this from what the
/// manifest declares to learn what the commit dodged — [`crate::bypass`]
/// keeps that count. Two records, two questions: the stamp gates a check,
/// the ledger only counts.
pub fn bind_to_head() -> Vec<String> {
    let Some(path) = marker_path() else {
        return Vec::new();
    };
    let Ok(body) = std::fs::read_to_string(&path) else {
        return Vec::new(); // no marker: nothing ran at pre-commit, nothing to stamp
    };
    let _ = std::fs::remove_file(&path);
    let mut lines = body.lines();
    if lines.next() != Some(FORMAT) {
        return Vec::new();
    }
    let Some(tree) = lines.next() else {
        return Vec::new();
    };
    let scripts: Vec<&str> = lines
        .filter(|l| !l.trim().is_empty() && !is_provenance(l))
        .collect();
    if scripts.is_empty() {
        return Vec::new();
    }
    let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
        crate::hooks::common::warn(
            "git would not name this commit's tree — no gate stamp was written",
        );
        return Vec::new();
    };
    // A different tree means this commit is not the one pre-commit judged —
    // the marker is a dead letter from an aborted attempt.
    if head_tree != tree {
        return Vec::new();
    }
    let scripts: Vec<String> = scripts.iter().map(|s| s.to_string()).collect();
    // The stamp goes on the TREE as well as the commit, and the tree is the
    // one that survives the way work actually reaches `main`.
    //
    // A squash-merge is performed by the forge: it produces a commit nobody
    // here ever saw, carrying no note, so a later `git push` of a tag on
    // that commit re-ran every gate the branch had already proved. Measured
    // on this repository: a branch push took 13 seconds and the tag push
    // that followed took the full suite and died on a reset connection.
    //
    // The tree is identical across that merge whenever the base has not
    // moved — five of five merges in one afternoon here — and identical
    // trees are identical CONTENT, which is the only thing a test suite
    // reads. That is the same argument `attest` makes for signing the tree
    // rather than the commit, and this module's marker has been tree-bound
    // since it was written; this only carries the binding through to the
    // note.
    //
    // Both, not either: the commit note is what a `git log --notes` reader
    // sees, and dropping it would make the stamps invisible in the place
    // people look for them.
    // MERGED into whatever is there, never rendered from the scripts alone:
    // a pre-push run against this same tree may already have recorded
    // evidence lines on it, and an `add -f` built from this list would erase
    // them.
    let mut tree_note = note_at(&head_tree);
    tree_note.add_tokens(&scripts);
    let _ = write_note(&head_tree, &tree_note);
    file_inputs(&head_tree, &scripts);
    let mut head_note = note_at("HEAD");
    head_note.add_tokens(&scripts);
    if !write_note("HEAD", &head_note) {
        // A note git refused is not a stamp — and the push will re-run these
        // checks, which is right but looks arbitrary unless it is said.
        crate::hooks::common::warn(
            "git refused to write the gate stamp — these checks will run again at push",
        );
        return Vec::new();
    }
    // The ledger counts NAMES: what the commit dodged is judged against what
    // the manifest declares, and the identity is the stamp's business alone.
    scripts
        .iter()
        .map(|s| crate::gate_identity::base(s).to_string())
        .collect()
}

/// pre-push, after every block gate passed: record that `gates` passed
/// against `tree`, the content of `commit` — MERGING with whatever the note
/// already says, because a commit-time stamp (`test`) may already sit there
/// and `notes add -f` would otherwise erase it.
///
/// Best-effort, like every writer here: a stamp that could not be written
/// costs one redundant gate run on the next push, which is the safe
/// direction. Returns whether the commit's note was written.
pub fn stamp_push(commit: &str, tree: &str, gates: &[String]) -> bool {
    if gates.is_empty() {
        return false;
    }
    let mut written = false;
    for key in [tree, commit] {
        let mut note = note_at(key);
        note.add_tokens(gates);
        let ok = write_note(key, &note);
        if key == commit {
            written = ok;
        }
    }
    file_inputs(tree, gates);
    if !written {
        crate::hooks::common::warn(
            "git refused to write the push stamp — these gates will run again on the next push",
        );
    }
    written
}

/// How a gate completed without passing (ADR-0018). The kind is part of the
/// record, so each answers only for as long as it should.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Completion {
    /// The gate reported a warning itself.
    Warned,
    /// The gate failed while its severity was `warn`: answers only while it
    /// still is, since a gate set back to `block` must run again.
    FailedUnderWarn,
    /// The gate could not run (a tool missing): answers for an hour, then
    /// the gate is tried again.
    Unavailable,
}

/// How long an `Unavailable` completion answers for.
const UNAVAILABLE_FOR_SECS: u64 = 60 * 60;

/// The record word for `token` completed as `how`, at `now`.
fn completion_word(how: Completion, token: &str, now: u64) -> String {
    match how {
        Completion::Warned => format!("warned:{token}"),
        Completion::FailedUnderWarn => format!("failed-under-warn:{token}"),
        Completion::Unavailable => format!("unavailable:{now}:{token}"),
    }
}

/// Does record word `word` answer for `token` now, under `severity`?
fn completion_answers(word: &str, token: &str, severity: crate::check::Severity, now: u64) -> bool {
    if word.strip_prefix("warned:") == Some(token) {
        return true;
    }
    if word.strip_prefix("failed-under-warn:") == Some(token) {
        return severity == crate::check::Severity::Warn;
    }
    word.strip_prefix("unavailable:")
        .and_then(|rest| rest.split_once(':'))
        .is_some_and(|(at, tok)| {
            tok == token
                && at
                    .parse::<u64>()
                    .is_ok_and(|at| now.saturating_sub(at) <= UNAVAILABLE_FOR_SECS)
        })
}

fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Record on `tree` that the gates behind `tokens` completed there without
/// passing, as `how` (ADR-0018). Merged into the note; an `Unavailable`
/// record replaces the one before it for the same gate, so a tree's note does
/// not grow by a word per run. The error names the tree, for the caller to
/// say: a record that was not written costs a refused push.
pub fn record_done(tree: &str, tokens: &[String], how: Completion) -> Result<(), String> {
    if tokens.is_empty() {
        return Ok(());
    }
    let now = now_secs();
    let mut note = note_in(DONE_REF, tree);
    if how == Completion::Unavailable {
        note.tokens.retain(|word| {
            !word
                .strip_prefix("unavailable:")
                .and_then(|rest| rest.split_once(':'))
                .is_some_and(|(_, token)| tokens.iter().any(|t| t == token))
        });
    }
    let words: Vec<String> = tokens
        .iter()
        .map(|t| completion_word(how, t, now))
        .collect();
    note.add_tokens(&words);
    if write_note_in(DONE_REF, tree, &note) {
        Ok(())
    } else {
        Err(format!(
            "git refused to record the completed gates on {tree}"
        ))
    }
}

/// Did the gate behind `token` complete without passing on the tree of every
/// one of `commits`, by a record that still answers under `severity`? An
/// unreadable tree or note is "no", the direction that refuses rather than
/// skips.
pub fn done_on_every(commits: &[String], token: &str, severity: crate::check::Severity) -> bool {
    let now = now_secs();
    !commits.is_empty()
        && commits.iter().all(|c| {
            crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]).is_some_and(|tree| {
                stamp_in(|s| s.done_ref, &tree)
                    .tokens
                    .iter()
                    .any(|word| completion_answers(word, token, severity, now))
            })
        })
}

/// pre-push: which of `commits` carry a stamp, and for which scripts.
///
/// One `notes list` narrows the reads to commits that have a note at all;
/// absent ref, unparseable note, wrong format version — all read as "no
/// stamp", which re-runs the gate.
pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
    let mut out = HashMap::new();
    if commits.is_empty() {
        return out;
    }
    // Both sets' lists, unioned: a commit noted only under the green ref is
    // a stamped commit too ([`stamp_at`] then picks which note answers).
    let lists: Option<Vec<String>> = READ
        .iter()
        .map(|set| crate::git::stdout(&["notes", "--ref", set.notes_ref, "list"]))
        .collect();
    let Some(lists) = lists else {
        // NOT the absent-ref case, whatever an older comment here claimed:
        // `notes list` exits 0 with empty output when the ref does not exist,
        // so that arrives as `Some("")` and falls through as "nothing is
        // stamped" — correctly. Reaching HERE means git could not answer at
        // all. Same verdict (the gates re-run: never skip work on a question
        // we could not ask), different sentence, because a transient git
        // failure that reads as "nothing is stamped" is indistinguishable
        // from the real thing — which is exactly how one flaky spawn cost a
        // day of not-diagnosing.
        crate::hooks::common::warn(
            "git would not list the gate stamps — every gated check will run again",
        );
        return out;
    };
    let noted: HashSet<&str> = lists
        .iter()
        .flat_map(|list| list.lines())
        .filter_map(|l| l.split_whitespace().nth(1))
        .collect();
    // Commit -> tree, in ONE spawn rather than one per commit: this is the
    // push path, and a `rev-parse` each would be a process per pushed
    // commit to answer a question `git log` answers in a batch.
    let mut trees: HashMap<String, String> = HashMap::new();
    {
        let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
        args.extend(commits.iter().map(String::as_str));
        if let Some(out) = crate::git::stdout(&args) {
            for line in out.lines() {
                let mut it = line.split_whitespace();
                if let (Some(c), Some(t)) = (it.next(), it.next()) {
                    trees.insert(c.to_string(), t.to_string());
                }
            }
        }
        // No mapping is not an error: every commit simply falls back to the
        // commit-keyed lookup below, which is what happened before trees
        // were stamped at all.
    }

    // Declared-input stamps are keyed by fingerprint, not by tree, so a commit
    // whose tree carries no note can still be vouched for. Asked only when the
    // ref exists: a repository nothing was filed for pays one spawn. Once
    // stamps are filed (declared or canonical), each pushed commit pays the
    // few git spawns of its route.
    let by_inputs = inputs_ref_exists();

    for commit in commits {
        // The commit's own note AND its TREE's, merged. Both are written only
        // for that tree (`bind_to_head` checks `HEAD^{tree}`, `stamp_push` is
        // handed the commit's own tree), so every token on either vouches for
        // exactly this content.
        //
        // Not "the commit's note, else the tree's". A squash-merge produces a
        // commit this machine never saw — no note — while the content, and
        // therefore the tree, is the one the gates ran on, and falling through
        // to the tree is what lets a tag push on a merged commit skip work the
        // branch already proved. But the same preference hid the tree's push
        // tokens behind a commit note after an AMEND that kept the tree:
        // post-commit wrote a commit note holding only the commit-time
        // scripts, `stamps_for` then stopped there, and the push gate ran
        // again for content it had already judged.
        //
        // The direction of failure is unchanged: no note on either, an
        // unparseable one, or a git that would not answer all mean "no
        // stamp", and no stamp runs the gate.
        let mut tokens: Vec<String> = Vec::new();
        let mut keys: Vec<&str> = Vec::new();
        if noted.contains(commit.as_str()) {
            keys.push(commit);
        }
        if let Some(tree) = trees.get(commit).filter(|t| noted.contains(t.as_str())) {
            keys.push(tree);
        }
        for key in keys {
            for t in stamp_at(key).tokens {
                if !tokens.contains(&t) {
                    tokens.push(t);
                }
            }
        }
        if by_inputs {
            if let Some(tree) = trees.get(commit) {
                for t in input_tokens(tree) {
                    if !tokens.contains(&t) {
                        tokens.push(t);
                    }
                }
            }
        }
        if tokens.is_empty() {
            continue;
        }
        out.insert(commit.clone(), tokens);
    }
    out
}

/// uninstall: forget everything this module ever wrote here.
///
/// The stamps are OUR bookkeeping — unlike `hook.skip` and `greengate.severity`,
/// which are the user's statements and are never touched.
pub fn forget() -> bool {
    let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
    // Every ref of every name set: a green note is ours too.
    let mut deleted = false;
    for set in READ {
        for r in full_refs(&set) {
            deleted |= crate::git::succeeds(&["update-ref", "-d", &r]);
        }
    }
    marker || deleted
}

/// The four fully qualified refs of one name set.
fn full_refs(set: &GateNames) -> [String; 4] {
    [set.notes_ref, set.inputs_ref, set.cluster_ref, set.done_ref]
        .map(|short| format!("refs/notes/{short}"))
}

/// The cluster tokens on `tree` (ADR-0016). Read only for a trusted
/// `platform=any` gate, so a repository with none never pays the spawn.
pub(crate) fn cluster_tokens(tree: &str) -> Vec<String> {
    stamp_in(|s| s.cluster_ref, tree).tokens
}

/// Record a cluster pass: `token` on the note at `tree`, with its provenance
/// line. Merged, like every writer here; best-effort.
pub(crate) fn stamp_cluster(tree: &str, token: &str, provenance: &str) -> bool {
    let mut note = note_in(CLUSTER_REF, tree);
    note.add_tokens(&[token.to_string()]);
    let line = format!("{PROVENANCE} {token} {provenance}");
    note.provenance
        .retain(|l| l.split_whitespace().nth(1) != Some(token));
    note.provenance.push(line);
    write_note_in(CLUSTER_REF, tree, &note)
}

/// pre-push: the tree and the cluster tokens of each of `commits`. Asked only
/// when a trusted `platform=any` gate is in play; a commit whose tree carries
/// no cluster note is absent from the map.
pub(crate) fn cluster_stamps_for(commits: &[String]) -> HashMap<String, (String, Vec<String>)> {
    let mut out = HashMap::new();
    for commit in commits {
        let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")]) else {
            continue;
        };
        let tokens = cluster_tokens(&tree);
        if !tokens.is_empty() {
            out.insert(commit.clone(), (tree, tokens));
        }
    }
    out
}

/// The same, for a repository this process is not standing in.
pub fn forget_in(repo: &std::path::Path) -> bool {
    let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
        .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
    let mut deleted = false;
    for set in READ {
        for r in full_refs(&set) {
            deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &r]);
        }
    }
    marker || deleted
}

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

    /// A completion answers only as long as it should (ADR-0018): a failure
    /// under `warn` stops answering once the gate blocks again, and a gate
    /// that could not run is tried again after an hour.
    #[test]
    fn a_completion_answers_only_while_it_should() {
        use crate::check::Severity::{Block, Warn};
        let now = 1_700_000_000;
        let word = |how| completion_word(how, "gate-tok", now);
        assert!(completion_answers(
            &word(Completion::Warned),
            "gate-tok",
            Block,
            now
        ));
        assert!(completion_answers(
            &word(Completion::FailedUnderWarn),
            "gate-tok",
            Warn,
            now
        ));
        assert!(!completion_answers(
            &word(Completion::FailedUnderWarn),
            "gate-tok",
            Block,
            now
        ));
        let unavailable = word(Completion::Unavailable);
        assert!(completion_answers(
            &unavailable,
            "gate-tok",
            Block,
            now + 3600
        ));
        assert!(!completion_answers(
            &unavailable,
            "gate-tok",
            Block,
            now + 3601
        ));
        assert!(!completion_answers(
            &word(Completion::Warned),
            "other-tok",
            Warn,
            now
        ));
    }

    /// A real repository, because every function here is a conversation with
    /// git — hand-rolled fixtures would test the conversation we imagined.
    fn repo(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        git(&dir, &["init", "-q", "--template=", "."]);
        git(&dir, &["config", "user.email", "t@t.test"]);
        git(&dir, &["config", "user.name", "t"]);
        dir
    }

    /// A fixture git call that FAILS where it fails.
    ///
    /// This used to discard the exit status, and that is how a rare flake
    /// stayed unreadable for a day: if the setup `git commit` did not
    /// happen, the test carried on to an unborn HEAD, and the panic landed
    /// three lines later on a missing gate stamp — a product-shaped
    /// failure for a fixture-shaped cause. Same rule the checks obey:
    /// git failing is not git answering.
    fn git(dir: &Path, args: &[&str]) -> String {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .output()
            .expect("git");
        assert!(
            out.status.success(),
            "fixture: git {args:?} in {} exited {:?}: {}",
            dir.display(),
            out.status.code(),
            String::from_utf8_lossy(&out.stderr).trim()
        );
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    /// The module talks to the repo at the process cwd; these tests each set
    /// it. Serialised via the crate-wide lock, because cwd is process-global
    /// and `attest`'s tests move it too.
    fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
        let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
        let prev = std::env::current_dir().unwrap();
        std::env::set_current_dir(dir).unwrap();
        let r = f();
        std::env::set_current_dir(prev).unwrap();
        r
    }

    #[test]
    fn the_commit_note_does_not_hide_the_tree_notes_push_tokens() {
        let dir = repo("union");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            record(&["test"]);
            git(&dir, &["commit", "-qm", "chore: a"]);
            bind_to_head();
            let head = git(&dir, &["rev-parse", "HEAD"]);
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            // A push-time stamp lands on the TREE only (the shape a rehearsal
            // leaves), while the commit note keeps just the commit-time script.
            assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
            assert_eq!(note_at(&head).tokens, vec!["test".to_string()]);
            let stamps = stamps_for(std::slice::from_ref(&head));
            assert_eq!(
                stamps.get(&head).map(Vec::as_slice),
                Some(&["test".to_string(), "pre-push-cargo-test".to_string()][..]),
                "both notes speak for the same tree"
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// An `unavailable` record replaces the one before it for the same gate,
    /// and leaves every other gate's record alone: a tree's note does not grow
    /// by a word per run (ADR-0018).
    #[test]
    fn an_unavailable_record_replaces_its_predecessor_only() {
        let dir = repo("done-unavailable");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        git(&dir, &["commit", "-qm", "chore: a"]);
        in_repo(&dir, || {
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            let one = |t: &str| vec![t.to_string()];
            record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("first");
            record_done(&tree, &one("lint@b"), Completion::Unavailable).expect("other gate");
            record_done(&tree, &one("lint@b"), Completion::Warned).expect("a warning");
            record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("again");
            let words = note_in(DONE_REF, &tree).tokens;
            let unavailable_for = |token: &str| {
                words
                    .iter()
                    .filter(|w| w.starts_with("unavailable:") && w.ends_with(&format!(":{token}")))
                    .count()
            };
            assert_eq!(unavailable_for("suite@a"), 1, "{words:?}");
            assert_eq!(unavailable_for("lint@b"), 1, "{words:?}");
            assert!(words.contains(&"warned:lint@b".to_string()), "{words:?}");
        });
        let _ = std::fs::remove_dir_all(&dir); // a temp fixture; `repo` clears it on the next run
    }

    #[test]
    fn a_commit_with_only_a_tree_note_still_reads_the_tree_tokens() {
        let dir = repo("tree-only");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        git(&dir, &["commit", "-qm", "chore: a"]);
        in_repo(&dir, || {
            let head = git(&dir, &["rev-parse", "HEAD"]);
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
            let stamps = stamps_for(std::slice::from_ref(&head));
            assert_eq!(
                stamps.get(&head).map(Vec::as_slice),
                Some(&["pre-push-cargo-test".to_string()][..])
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_commit_with_only_a_commit_note_still_reads_its_tokens() {
        let dir = repo("commit-only");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        git(&dir, &["commit", "-qm", "chore: a"]);
        in_repo(&dir, || {
            let head = git(&dir, &["rev-parse", "HEAD"]);
            let mut note = Note::default();
            note.add_tokens(&["typecheck".to_string()]);
            assert!(write_note(&head, &note));
            let stamps = stamps_for(std::slice::from_ref(&head));
            assert_eq!(
                stamps.get(&head).map(Vec::as_slice),
                Some(&["typecheck".to_string()][..])
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_token_on_both_notes_is_read_once() {
        let dir = repo("dedup");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            record(&["test"]);
            git(&dir, &["commit", "-qm", "chore: a"]);
            bind_to_head(); // writes `test` on the commit AND the tree
            let head = git(&dir, &["rev-parse", "HEAD"]);
            let stamps = stamps_for(std::slice::from_ref(&head));
            assert_eq!(
                stamps.get(&head).map(Vec::as_slice),
                Some(&["test".to_string()][..])
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
        let dir = repo("roundtrip");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            record(&["typecheck", "test"]);
            git(&dir, &["commit", "-qm", "chore: a"]);
            let stamped = bind_to_head();
            assert_eq!(
                stamped,
                vec!["typecheck".to_string(), "test".to_string()],
                "bind_to_head reports the scripts it stamped"
            );
            let head = git(&dir, &["rev-parse", "HEAD"]);
            let stamps = stamps_for(std::slice::from_ref(&head));
            assert_eq!(
                stamps.get(&head).map(Vec::as_slice),
                Some(&["typecheck".to_string(), "test".to_string()][..])
            );
            // One-shot: the marker is gone.
            // One-shot: the marker is gone. The fixture's own path, not
            // `marker_path()` — that helper spawns git, and a transient
            // spawn failure on a loaded runner reads as `None` here while
            // production code correctly treats it as "no marker". Seen once,
            // on Windows, as an unwrap panic in a sibling test.
            assert!(!dir.join(".git").join(MARKER).exists());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_marker_for_a_different_tree_stamps_nothing() {
        let dir = repo("stale");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            record(&["typecheck"]);
            // The commit that actually lands carries DIFFERENT content — the
            // aborted-attempt-then-different-retry shape.
            std::fs::write(dir.join("a.ts"), "y").unwrap();
            git(&dir, &["add", "a.ts"]);
            git(&dir, &["commit", "-qm", "chore: different"]);
            assert!(
                bind_to_head().is_empty(),
                "bind_to_head reports nothing when the tree moved"
            );
            let head = git(&dir, &["rev-parse", "HEAD"]);
            assert!(
                stamps_for(&[head]).is_empty(),
                "a stale marker must not vouch"
            );
            assert!(
                !dir.join(".git").join(MARKER).exists(),
                "consumed either way"
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn an_empty_record_clears_a_previous_marker() {
        let dir = repo("clears");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            record(&["typecheck"]);
            assert!(dir.join(".git").join(MARKER).exists());
            record(&[]);
            assert!(!dir.join(".git").join(MARKER).exists());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The version guard's REJECT branch, fed a hand-written marker: an old
    /// (or future) format is ignored rather than misread — the doc's claim,
    /// now pinned. Every other test's markers come from record() itself and
    /// so always carry the current FORMAT.
    #[test]
    fn a_marker_in_an_unknown_format_stamps_nothing() {
        let dir = repo("wrongformat");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            let tree = git(&dir, &["write-tree"]);
            let marker = dir.join(".git").join(MARKER);
            std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
            git(&dir, &["commit", "-qm", "chore: a"]);
            bind_to_head();
            let head = git(&dir, &["rev-parse", "HEAD"]);
            assert!(
                stamps_for(std::slice::from_ref(&head)).is_empty(),
                "an unknown format was trusted"
            );
            assert!(!marker.exists(), "consumed either way");
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A note somebody else wrote into OUR ref is not a stamp. Absent this,
    /// `git notes --ref=amont-gate add` would be a one-line way to vouch for
    /// an unchecked commit — the parsing trust boundary of the whole chain.
    #[test]
    fn a_foreign_note_is_not_a_stamp() {
        let dir = repo("foreignnote");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            git(&dir, &["commit", "-qm", "chore: a"]);
            git(
                &dir,
                &[
                    "notes",
                    "--ref",
                    NOTES_REF,
                    "add",
                    "-m",
                    "typecheck test",
                    "HEAD",
                ],
            );
            let head = git(&dir, &["rev-parse", "HEAD"]);
            assert!(
                stamps_for(std::slice::from_ref(&head)).is_empty(),
                "a note without the format token was trusted"
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// An absent notes ref is `Some("")`, not `None` — the distinction the
    /// warning on that branch depends on. If git ever starts failing here
    /// instead, this test fails and the warning stops being a lie.
    #[test]
    fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
        let dir = repo("no-stamps");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        git(&dir, &["commit", "-qm", "chore: a"]);
        in_repo(&dir, || {
            assert_eq!(
                crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
                Some(""),
                "an absent notes ref must be an ANSWER, not a failure — the \
                 no-stamps path and the git-is-broken path are told apart by it"
            );
            let head = git(&dir, &["rev-parse", "HEAD"]);
            assert!(stamps_for(&[head]).is_empty());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The compatibility promise, in both directions.
    ///
    /// A note written before evidence lines existed is ONE line, and it must
    /// parse to exactly the tokens it always did — every skip decision in
    /// this module reads that line, and a reader that needed the new shape
    /// would stop honouring every stamp on every machine the day it shipped.
    #[test]
    fn a_note_from_before_the_run_lines_parses_unchanged() {
        let note = Note::parse("greengate-gate-v1 typecheck test");
        assert_eq!(note.tokens, vec!["typecheck", "test"]);
        assert!(note.runs.is_empty());
        // And round-trips to the same bytes, so an old amont reading a note
        // this one rewrote sees what it wrote.
        assert_eq!(note.render(), "greengate-gate-v1 typecheck test");
    }

    /// The new shape: line one unchanged, evidence after it.
    #[test]
    fn run_lines_are_read_without_disturbing_the_tokens() {
        let body = "greengate-gate-v1 pre-push-cargo-test\n\
                    run 1726900000 pre-push-cargo-test pass 412391\n\
                    run 1726903600 pre-push-audit-js fail 903\n";
        let note = Note::parse(body);
        assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
        assert_eq!(note.runs.len(), 2);
        assert_eq!(
            note.runs[0],
            Run {
                at: 1_726_900_000,
                gate: "pre-push-cargo-test".into(),
                outcome: RunOutcome::Passed,
                ms: 412_391,
            }
        );
        assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
        assert_eq!(note.render(), body.trim_end());
    }

    /// A line this version does not understand is dropped, not guessed at —
    /// so a future amont may add a field (or an outcome) without an older one
    /// inventing a meaning for it.
    #[test]
    fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
        let note = Note::parse(
            "greengate-gate-v1 test\n\
             run 1726900000 pre-push-cargo-test pass 400\n\
             run tomorrow pre-push-cargo-test pass 400\n\
             run 1726900001 pre-push-cargo-test sideways 400\n\
             banana\n\
             run 1726900002 pre-push-cargo-test fail 500\n",
        );
        assert_eq!(note.tokens, vec!["test"]);
        assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
        assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
    }

    /// A deferral line (ADR-0013) round-trips, is never a token, and is not
    /// trimmed with the run history: more than [`MAX_RUNS`] later runs on the
    /// same tree must not make the push twin forget the commit deferred it.
    #[test]
    fn a_deferral_is_never_a_token_and_outlives_the_run_trim() {
        let mut note = Note::parse("greengate-gate-v1 lint\ndeferred cargo-test\n");
        assert_eq!(note.tokens, vec!["lint"]);
        assert_eq!(note.deferred, vec!["cargo-test"]);
        let runs: Vec<Run> = (0..MAX_RUNS as u64 + 10)
            .map(|i| Run {
                at: 1_726_900_000 + i,
                gate: "pre-push-audit-js".into(),
                outcome: RunOutcome::Passed,
                ms: 1,
            })
            .collect();
        note.add_runs(&runs);
        let again = Note::parse(&note.render());
        assert_eq!(again.runs.len(), MAX_RUNS);
        assert_eq!(again.deferred, vec!["cargo-test"]);
        assert_eq!(again.tokens, vec!["lint"]);
    }

    /// A note somebody else wrote into our ref is not evidence either. The
    /// token line is the trust boundary for BOTH halves of the note.
    #[test]
    fn a_foreign_note_yields_no_runs() {
        let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
        assert!(note.tokens.is_empty() && note.runs.is_empty());
    }

    /// Recording evidence must never cost a stamp. `stamp_push` and
    /// `bind_to_head` rewrite the same note, and the first version of this
    /// rendered the note from its own token list — which would have erased
    /// every run line on the next push.
    #[test]
    fn a_stamp_and_its_evidence_survive_each_other() {
        let dir = repo("evidence");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            git(&dir, &["commit", "-qm", "chore: a"]);
            let head = git(&dir, &["rev-parse", "HEAD"]);
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            record_runs(
                &tree,
                &[Run {
                    at: 1_726_900_000,
                    gate: "pre-push-cargo-test".into(),
                    outcome: RunOutcome::Failed,
                    ms: 412_391,
                }],
            );
            // …and now a later push of the same content passes and stamps it.
            assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
            let note = note_at(&tree);
            assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
            assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
            // The stamp still reads back as a stamp.
            let stamps = stamps_for(std::slice::from_ref(&head));
            assert_eq!(
                stamps.get(&head).map(Vec::as_slice),
                Some(&["pre-push-cargo-test".to_string()][..])
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The whole point of the evidence half: it is not a stamp. A recorded
    /// run — even a passing one — must not let the gate be skipped, because
    /// skipping is decided by the token line and nothing else.
    #[test]
    fn a_recorded_run_is_not_a_stamp() {
        let dir = repo("not-a-stamp");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            git(&dir, &["commit", "-qm", "chore: a"]);
            let head = git(&dir, &["rev-parse", "HEAD"]);
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            record_runs(
                &tree,
                &[Run {
                    at: 1_726_900_000,
                    gate: "pre-push-cargo-test".into(),
                    outcome: RunOutcome::Passed,
                    ms: 412_391,
                }],
            );
            assert!(
                stamps_for(std::slice::from_ref(&head)).is_empty(),
                "a run line vouched for a gate — evidence must never gate"
            );
            assert!(
                !vouched_for_staged_tree().contains("pre-push-cargo-test"),
                "a run line vouched at commit time"
            );
            // It IS readable as history, though.
            let history = crate::gate_evidence::history_in(&dir);
            assert_eq!(history.runs.len(), 1);
            assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn forget_removes_the_stamps() {
        let dir = repo("forget");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            record(&["typecheck"]);
            git(&dir, &["commit", "-qm", "chore: a"]);
            bind_to_head();
            let head = git(&dir, &["rev-parse", "HEAD"]);
            assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
            forget();
            assert!(stamps_for(&[head]).is_empty());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A squash-merge produces a commit this machine never saw, and the
    /// stamp has to survive it.
    ///
    /// This is the case that motivated tree-stamping. A branch is verified
    /// locally and stamped; the forge squashes it onto `main` as a NEW
    /// commit with no note; pushing a tag on that commit re-ran every gate
    /// the branch had already proved. Measured on this repository: 13
    /// seconds for the branch push, then the full suite for the tag push,
    /// which died on a reset connection.
    ///
    /// The tree is what the gates actually read, and it is identical across
    /// that merge whenever the base has not moved — five of five merges in
    /// one afternoon here.
    #[test]
    fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
        let dir = repo("squashed");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            record(&["test"]);
            git(&dir, &["commit", "-qm", "feat: on a branch"]);
            assert_eq!(bind_to_head(), vec!["test".to_string()]);
            let branch_tip = git(&dir, &["rev-parse", "HEAD"]);

            // Stand in for the forge's squash: a DIFFERENT commit object
            // with the SAME tree. `--amend` with a new message is the
            // cheapest way to get exactly that shape.
            git(
                &dir,
                &[
                    "commit",
                    "-q",
                    "--amend",
                    "-m",
                    "feat: squashed by the forge",
                ],
            );
            let merged = git(&dir, &["rev-parse", "HEAD"]);
            assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
            assert_eq!(
                git(&dir, &["rev-parse", "HEAD^{tree}"]),
                git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
                "…carrying the same tree, which is the whole premise"
            );

            let stamps = stamps_for(std::slice::from_ref(&merged));
            assert_eq!(
                stamps.get(&merged).map(Vec::as_slice),
                Some(&["test".to_string()][..]),
                "the stamp must follow the content, not the commit hash"
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// And it must not follow anything else. A commit whose tree was never
    /// stamped gets nothing, however many other stamps exist — otherwise
    /// this widening would vouch for content nobody checked.
    #[test]
    fn a_different_tree_gets_no_stamp_from_the_fallback() {
        let dir = repo("othertree");
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        in_repo(&dir, || {
            record(&["test"]);
            git(&dir, &["commit", "-qm", "chore: stamped"]);
            assert_eq!(bind_to_head(), vec!["test".to_string()]);

            // Different CONTENT, so a different tree, and no marker: this
            // commit was never judged.
            std::fs::write(dir.join("b.ts"), "y").unwrap();
            git(&dir, &["add", "b.ts"]);
            git(&dir, &["commit", "-qm", "chore: unjudged"]);
            let unstamped = git(&dir, &["rev-parse", "HEAD"]);

            assert!(
                stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
                "a tree nobody stamped must not inherit one"
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    // ---- declared-input reuse (`.github/attest-inputs`) -------------------

    /// A repository declaring that gate `test` reads only `a.ts`, with one
    /// commit stamped `test@abc`. The plans directory is where a later,
    /// plan-only commit will change the tree without touching any input.
    fn declared(name: &str, spec: &str) -> PathBuf {
        let dir = repo(name);
        std::fs::create_dir_all(dir.join(".github")).unwrap();
        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
        std::fs::write(dir.join(".github/attest-inputs"), spec).unwrap();
        git(&dir, &["add", "-A"]);
        in_repo(&dir, || {
            record(&["test@abc"]);
            git(&dir, &["commit", "-qm", "feat: judged"]);
            assert_eq!(bind_to_head(), vec!["test".to_string()]);
        });
        dir
    }

    /// Change only the plan and commit it WITHOUT a marker: nothing was
    /// judged for this tree, so only the fingerprint route can speak.
    fn plan_only_commit(dir: &Path) -> String {
        std::fs::write(dir.join("docs/plans/p.md"), "plan v2, closing").unwrap();
        git(dir, &["add", "docs/plans/p.md"]);
        git(dir, &["commit", "-qm", "docs(plan): done"]);
        git(dir, &["rev-parse", "HEAD"])
    }

    #[test]
    fn a_plan_only_commit_reuses_the_stamp_of_a_declared_gate() {
        let dir = declared("plan-only", "test a.ts\n");
        in_repo(&dir, || {
            let head = plan_only_commit(&dir);
            let stamps = stamps_for(std::slice::from_ref(&head));
            assert_eq!(
                stamps.get(&head).map(Vec::as_slice),
                Some(&["test@abc".to_string()][..]),
                "the closing commit changed the tree and none of the declared inputs"
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn the_staged_tree_of_a_plan_only_commit_is_vouched_for() {
        let dir = declared("staged", "test a.ts\n");
        in_repo(&dir, || {
            std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
            git(&dir, &["add", "docs/plans/p.md"]);
            assert!(vouched_for_staged_tree().contains("test@abc"));
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn partial_staging_is_judged_on_the_index_not_the_working_copy() {
        let dir = declared("partial", "test a.ts\n");
        in_repo(&dir, || {
            // The plan is staged; an unstaged edit to a declared input sits in
            // the working copy. The commit would carry only the plan.
            std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
            git(&dir, &["add", "docs/plans/p.md"]);
            std::fs::write(dir.join("a.ts"), "unstaged edit").unwrap();
            assert!(vouched_for_staged_tree().contains("test@abc"));

            // The other way round: the input IS staged, so it misses even
            // though the working copy was put back.
            std::fs::write(dir.join("a.ts"), "staged edit").unwrap();
            git(&dir, &["add", "a.ts"]);
            std::fs::write(dir.join("a.ts"), "x").unwrap();
            assert!(!vouched_for_staged_tree().contains("test@abc"));
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_changed_declared_input_misses() {
        let dir = declared("input-changed", "test a.ts\n");
        in_repo(&dir, || {
            std::fs::write(dir.join("a.ts"), "changed").unwrap();
            git(&dir, &["add", "a.ts"]);
            git(&dir, &["commit", "-qm", "feat: unjudged"]);
            let head = git(&dir, &["rev-parse", "HEAD"]);
            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_changed_declaration_misses() {
        let dir = declared("declaration-changed", "test a.ts\n");
        in_repo(&dir, || {
            // The spec's own blob is in every fingerprint: widening what the
            // gate reads is a different declaration, so nothing is reused.
            std::fs::write(dir.join("b.ts"), "y").unwrap();
            std::fs::write(dir.join(".github/attest-inputs"), "test a.ts b.ts\n").unwrap();
            git(&dir, &["add", "-A"]);
            git(&dir, &["commit", "-qm", "chore: widen the declaration"]);
            let head = git(&dir, &["rev-parse", "HEAD"]);
            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_declared_config_file_is_an_input_like_any_other() {
        // A gate's scope lives in a tracked file (`amont.conf`). Declared, a
        // scope-only edit changes the fingerprint and the stamp misses.
        let dir = declared("config", "test a.ts amont.conf\n");
        in_repo(&dir, || {
            // `declared` ran before amont.conf existed: it is a required path,
            // so that first commit had no fingerprint and filed nothing.
            assert!(!inputs_ref_exists());

            std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
            git(&dir, &["add", "amont.conf"]);
            record(&["test@abc"]);
            git(&dir, &["commit", "-qm", "chore: config"]);
            assert_eq!(bind_to_head(), vec!["test".to_string()]);

            std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
            git(&dir, &["add", "docs/plans/p.md"]);
            git(&dir, &["commit", "-qm", "docs(plan): done"]);
            let plan = git(&dir, &["rev-parse", "HEAD"]);
            assert!(stamps_for(std::slice::from_ref(&plan)).contains_key(&plan));

            std::fs::write(dir.join("amont.conf"), "scope = lib\n").unwrap();
            git(&dir, &["add", "amont.conf"]);
            git(&dir, &["commit", "-qm", "chore: scope-only change"]);
            let scope = git(&dir, &["rev-parse", "HEAD"]);
            assert!(
                stamps_for(std::slice::from_ref(&scope)).is_empty(),
                "a scope-only change must miss"
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_declared_stamp_is_read_back_as_its_complete_token() {
        // The identity comparison lives in the readers (`pair_verdict`, the
        // push gate): they skip only on the complete token they compute. This
        // pins what the new route owes them: tokens come back verbatim, never
        // widened to the gate's name, and a second identity under the same key
        // is kept apart from the first.
        let dir = declared("identity", "test a.ts\n");
        in_repo(&dir, || {
            let head = plan_only_commit(&dir);
            let tokens = stamps_for(std::slice::from_ref(&head))
                .remove(&head)
                .unwrap_or_default();
            assert_eq!(tokens, vec!["test@abc".to_string()]);

            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            assert!(stamp_tree(&tree, &["test@def".to_string()]));
            let tokens = tree_tokens(&tree);
            assert!(tokens.contains(&"test@abc".to_string()));
            assert!(tokens.contains(&"test@def".to_string()));
            assert!(!tokens.contains(&"test@zzz".to_string()));
            assert!(!tokens.contains(&"test".to_string()));
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_gate_that_does_not_declare_the_manifest_is_not_offered_the_route() {
        // `amont.conf` is tracked but the gate's declaration omits it: a
        // scope-only edit would be invisible to the fingerprint, so the route
        // is refused outright. Nothing is filed and nothing is reused.
        let dir = repo("manifest-undeclared");
        std::fs::create_dir_all(dir.join(".github")).unwrap();
        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
        git(&dir, &["add", "-A"]);
        in_repo(&dir, || {
            record(&["test@abc"]);
            git(&dir, &["commit", "-qm", "feat: judged"]);
            bind_to_head();
            assert!(!inputs_ref_exists(), "the route must not open");
            let head = plan_only_commit(&dir);
            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_gate_declaring_the_manifest_opens_the_route() {
        // The counterpart: with `amont.conf` among its declared inputs the
        // gate is filed by fingerprint again.
        let dir = declared("manifest-declared", "test a.ts amont.conf\n");
        in_repo(&dir, || {
            std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
            git(&dir, &["add", "amont.conf"]);
            record(&["test@abc"]);
            git(&dir, &["commit", "-qm", "chore: config"]);
            bind_to_head();
            assert!(inputs_ref_exists());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn an_undeclared_gate_keeps_whole_tree_behaviour() {
        let dir = declared("undeclared", "test a.ts\n");
        in_repo(&dir, || {
            // `lint` passed on the first tree but the spec declares only
            // `test`: the plan-only commit is a new tree for `lint`.
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
            let head = plan_only_commit(&dir);
            let tokens = stamps_for(std::slice::from_ref(&head))
                .remove(&head)
                .unwrap_or_default();
            assert!(tokens.contains(&"test@abc".to_string()));
            assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn an_invalid_or_ambiguous_spec_falls_back_to_whole_tree_behaviour() {
        // A glob invalidates the whole spec.
        let dir = declared("invalid", "test src/*\n");
        in_repo(&dir, || {
            assert!(!inputs_ref_exists(), "no valid spec, nothing is filed");
            let head = plan_only_commit(&dir);
            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
        });
        let _ = std::fs::remove_dir_all(&dir);

        // Both locations present: ambiguous, the route is off.
        let dir = repo("ambiguous");
        std::fs::create_dir_all(dir.join(".github")).unwrap();
        std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
        std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
        git(&dir, &["add", "-A"]);
        in_repo(&dir, || {
            record(&["test@abc"]);
            git(&dir, &["commit", "-qm", "feat: judged"]);
            bind_to_head();
            assert!(!inputs_ref_exists());
            let head = plan_only_commit(&dir);
            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_gate_that_did_not_pass_leaves_no_declared_input_stamp() {
        let dir = repo("failed");
        std::fs::create_dir_all(dir.join(".github")).unwrap();
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
        git(&dir, &["add", "-A"]);
        in_repo(&dir, || {
            // pre-commit blocked or ran nothing: an empty record, no marker.
            record(&[]);
            git(&dir, &["commit", "-qm", "feat: unjudged"]);
            assert!(bind_to_head().is_empty());
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            let head = git(&dir, &["rev-parse", "HEAD"]);
            assert!(!stamp_push(&head, &tree, &[]));
            assert!(!inputs_ref_exists());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn stamp_tree_and_tree_tokens_use_the_inputs_ref() {
        let dir = declared("rehearsal", "test a.ts\n");
        in_repo(&dir, || {
            // A rehearsal proves a gate in a snapshot of this tree …
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            assert!(stamp_tree(&tree, &["test@rehearsed".to_string()]));
            // … and a later tree with identical declared inputs reads it back.
            plan_only_commit(&dir);
            let later = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            assert_ne!(later, tree);
            assert!(tree_tokens(&later).contains(&"test@rehearsed".to_string()));
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn the_inputs_ref_is_keyed_the_way_attest_keys_its_own() {
        let dir = declared("key", "test a.ts\n");
        in_repo(&dir, || {
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
            let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
            let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
            let listed = git(&dir, &["notes", "--ref", INPUTS_REF, "list"]);
            assert!(
                listed
                    .lines()
                    .any(|l| l.split_whitespace().nth(1) == Some(key.as_str())),
                "{listed}"
            );
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_foreign_token_in_the_inputs_ref_vouches_for_nothing() {
        let dir = declared("foreign", "test a.ts\n");
        in_repo(&dir, || {
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
            let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
            let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
            // Somebody files a token for ANOTHER gate under `test`'s key.
            let mut note = note_in(INPUTS_REF, &key);
            note.add_tokens(&["publish@evil".to_string()]);
            assert!(write_note_in(INPUTS_REF, &key, &note));
            assert!(!tree_tokens(&tree).contains(&"publish@evil".to_string()));
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn forget_removes_the_inputs_ref_too() {
        let dir = declared("forget-inputs", "test a.ts\n");
        in_repo(&dir, || {
            assert!(inputs_ref_exists());
            assert!(forget());
            assert!(!inputs_ref_exists());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A repository that declares nothing: `a.ts`, a plan, and optionally an
    /// `amont.conf`, judged once (`test@abc`).
    fn canonical(name: &str, conf: Option<&str>) -> PathBuf {
        let dir = repo(name);
        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
        if let Some(conf) = conf {
            std::fs::write(dir.join("amont.conf"), conf).unwrap();
        }
        git(&dir, &["add", "-A"]);
        in_repo(&dir, || {
            record(&["test@abc"]);
            git(&dir, &["commit", "-qm", "feat: judged"]);
            assert_eq!(bind_to_head(), vec!["test".to_string()]);
        });
        dir
    }

    fn vouched(dir: &Path, commit: &str) -> Vec<String> {
        in_repo(dir, || {
            stamps_for(std::slice::from_ref(&commit.to_string()))
                .remove(commit)
                .unwrap_or_default()
        })
    }

    #[test]
    fn with_no_spec_a_plans_only_commit_is_vouched_for_canonically() {
        let dir = canonical("canon-plan-edit", None);
        in_repo(&dir, || {
            assert!(inputs_ref_exists(), "the canonical stamp is filed");
            let head = plan_only_commit(&dir);
            assert_eq!(
                stamps_for(std::slice::from_ref(&head))
                    .remove(&head)
                    .unwrap_or_default(),
                vec!["test@abc".to_string()]
            );
            // The staged tree, as pre-commit judges it, is vouched for too.
            std::fs::write(dir.join("docs/plans/p.md"), "plan v3").unwrap();
            git(&dir, &["add", "docs/plans/p.md"]);
            assert!(vouched_for_staged_tree().contains("test@abc"));
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_plan_added_deleted_or_renamed_is_not_vouched_for() {
        let dir = canonical("canon-plan-exists", None);
        std::fs::write(dir.join("docs/plans/q.md"), "second plan").unwrap();
        git(&dir, &["add", "docs/plans/q.md"]);
        git(&dir, &["commit", "-qm", "docs(plan): add"]);
        let added = git(&dir, &["rev-parse", "HEAD"]);
        assert!(vouched(&dir, &added).is_empty(), "a plan added");
        git(&dir, &["mv", "docs/plans/p.md", "docs/plans/r.md"]);
        git(&dir, &["commit", "-qm", "docs(plan): rename"]);
        let renamed = git(&dir, &["rev-parse", "HEAD"]);
        assert!(vouched(&dir, &renamed).is_empty(), "a plan renamed");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn with_no_spec_any_other_change_is_not_vouched_for() {
        let dir = canonical("canon-code-edit", Some("gate test = make test\n"));
        std::fs::write(dir.join("a.ts"), "changed").unwrap();
        git(&dir, &["commit", "-qam", "feat: code"]);
        let code = git(&dir, &["rev-parse", "HEAD"]);
        assert!(vouched(&dir, &code).is_empty(), "a source edit");
        // amont.conf is part of the canonical tree: a scope-only edit misses.
        std::fs::write(dir.join("amont.conf"), "gate test = make other\n").unwrap();
        git(&dir, &["commit", "-qam", "chore: config"]);
        let conf = git(&dir, &["rev-parse", "HEAD"]);
        assert!(vouched(&dir, &conf).is_empty(), "a manifest edit");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn plan_exempt_off_closes_the_canonical_route() {
        for (name, conf) in [
            ("off", "set planExempt off\n"),
            ("spelled", "SET  PLANEXEMPT\tOff\r\n"),
            ("after", "set planExempt on\nset planExempt off\n"),
        ] {
            let dir = canonical(&format!("canon-off-{name}"), Some(conf));
            in_repo(&dir, || {
                assert!(!inputs_ref_exists(), "{name}: nothing is filed");
                let head = plan_only_commit(&dir);
                assert!(
                    stamps_for(std::slice::from_ref(&head)).is_empty(),
                    "{name}: a plans-only commit is a new tree"
                );
            });
            let _ = std::fs::remove_dir_all(&dir);
        }
        // `on`, a trailing comment and a comment line do not opt out.
        for (name, conf) in [
            ("on", "set planExempt on\n"),
            ("comment", "set planExempt off # no\n"),
            ("commented", "# set planExempt off\n"),
        ] {
            let dir = canonical(&format!("canon-on-{name}"), Some(conf));
            let head = plan_only_commit(&dir);
            assert!(!vouched(&dir, &head).is_empty(), "{name}: still canonical");
            let _ = std::fs::remove_dir_all(&dir);
        }
    }

    #[test]
    fn a_spec_that_cannot_be_used_means_no_canonical_stamps() {
        // A directory where the spec should be: listed, unreadable as a blob.
        let dir = repo("canon-unreadable-spec");
        std::fs::create_dir_all(dir.join(".github/attest-inputs")).unwrap();
        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
        std::fs::write(dir.join(".github/attest-inputs/x"), "x").unwrap();
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
        git(&dir, &["add", "-A"]);
        in_repo(&dir, || {
            record(&["test@abc"]);
            git(&dir, &["commit", "-qm", "feat: judged"]);
            bind_to_head();
            assert!(!inputs_ref_exists(), "an unreadable spec opens nothing");
            let head = plan_only_commit(&dir);
            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn two_specs_mean_no_canonical_stamps() {
        let dir = repo("canon-ambiguous");
        std::fs::create_dir_all(dir.join(".github")).unwrap();
        std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
        std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
        git(&dir, &["add", "-A"]);
        in_repo(&dir, || {
            record(&["test@abc"]);
            git(&dir, &["commit", "-qm", "feat: judged"]);
            bind_to_head();
            assert!(!inputs_ref_exists());
            let head = plan_only_commit(&dir);
            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_valid_spec_keeps_precedence_over_the_canonical_route() {
        // `lint` is not declared: it must NOT ride the canonical route.
        let dir = declared("canon-precedence", "test a.ts\n");
        in_repo(&dir, || {
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
            let head = plan_only_commit(&dir);
            let tokens = stamps_for(std::slice::from_ref(&head))
                .remove(&head)
                .unwrap_or_default();
            assert!(tokens.contains(&"test@abc".to_string()));
            assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    // Both name sets (decisions ADR-0068, plan "greengate signs its notes
    // under green names", Phase 2): read green first, legacy only for a key
    // the green ref has no note for, a note's header matching its ref.

    /// A repository with one unjudged commit: no stamp under either set.
    fn unstamped(name: &str) -> (PathBuf, String, String) {
        let dir = repo(name);
        std::fs::write(dir.join("a.ts"), "x").unwrap();
        git(&dir, &["add", "a.ts"]);
        git(&dir, &["commit", "-qm", "feat: a"]);
        let head = git(&dir, &["rev-parse", "HEAD"]);
        let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
        (dir, head, tree)
    }

    /// Plant `body` at `key` in `notes_ref`, as another greengate would.
    fn plant(dir: &Path, notes_ref: &str, key: &str, body: &str) {
        git(
            dir,
            &["notes", "--ref", notes_ref, "add", "-f", "-m", body, key],
        );
    }

    fn stamps_of(commit: &str) -> Vec<String> {
        stamps_for(&[commit.to_string()])
            .remove(commit)
            .unwrap_or_default()
    }

    #[test]
    fn a_pass_is_found_under_either_gate_ref() {
        for (i, set) in READ.iter().enumerate() {
            let (dir, head, tree) = unstamped(&format!("either-{i}"));
            plant(
                &dir,
                set.notes_ref,
                &head,
                &format!("{} test@c", set.format),
            );
            plant(
                &dir,
                set.notes_ref,
                &tree,
                &format!("{} test@t", set.format),
            );
            plant(
                &dir,
                set.cluster_ref,
                &tree,
                &format!("{} suite@k", set.format),
            );
            plant(
                &dir,
                set.done_ref,
                &tree,
                &format!("{} warned:lint@w", set.format),
            );
            in_repo(&dir, || {
                let mut got = stamps_of(&head);
                got.sort();
                assert_eq!(got, ["test@c", "test@t"], "{}", set.notes_ref);
                assert_eq!(tree_tokens(&tree), ["test@t"], "{}", set.notes_ref);
                assert_eq!(cluster_tokens(&tree), ["suite@k"], "{}", set.cluster_ref);
                assert!(
                    done_on_every(
                        std::slice::from_ref(&head),
                        "lint@w",
                        crate::check::Severity::Block
                    ),
                    "{}",
                    set.done_ref
                );
            });
            let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
        }
    }

    #[test]
    fn with_notes_under_both_refs_the_green_note_is_read() {
        let (dir, head, tree) = unstamped("both-refs");
        for key in [&head, &tree] {
            plant(
                &dir,
                LEGACY.notes_ref,
                key,
                &format!("{} test@old", LEGACY.format),
            );
            plant(
                &dir,
                GREEN.notes_ref,
                key,
                &format!("{} test@new", GREEN.format),
            );
        }
        plant(
            &dir,
            LEGACY.cluster_ref,
            &tree,
            &format!("{} suite@old", LEGACY.format),
        );
        plant(
            &dir,
            GREEN.cluster_ref,
            &tree,
            &format!("{} suite@new", GREEN.format),
        );
        in_repo(&dir, || {
            assert_eq!(stamps_of(&head), ["test@new"]);
            assert_eq!(tree_tokens(&tree), ["test@new"]);
            assert_eq!(cluster_tokens(&tree), ["suite@new"]);
        });
        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
    }

    #[test]
    fn a_note_whose_header_is_the_other_sets_reads_as_unstamped() {
        for (i, (sits_in, header_of)) in [(LEGACY, GREEN), (GREEN, LEGACY)].iter().enumerate() {
            let (dir, head, tree) = unstamped(&format!("mixed-{i}"));
            for key in [&head, &tree] {
                plant(
                    &dir,
                    sits_in.notes_ref,
                    key,
                    &format!("{} test@x", header_of.format),
                );
            }
            plant(
                &dir,
                sits_in.cluster_ref,
                &tree,
                &format!("{} suite@x", header_of.format),
            );
            in_repo(&dir, || {
                assert!(stamps_of(&head).is_empty(), "{}", sits_in.notes_ref);
                assert!(tree_tokens(&tree).is_empty(), "{}", sits_in.notes_ref);
                assert!(cluster_tokens(&tree).is_empty(), "{}", sits_in.cluster_ref);
            });
            let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
        }
    }

    /// A green inputs note is filed under the GREEN key (its own input
    /// domain) and answers before the legacy one; the legacy key in the
    /// green ref is not read.
    #[test]
    fn the_green_inputs_ref_is_read_first_under_its_own_key() {
        let dir = declared("green-inputs", "test a.ts\n");
        in_repo(&dir, || {
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
            let fp = crate::attest_inputs::fingerprint(&tree, &spec, "test").expect("fp");
            let green = crate::attest_inputs::input_key(&GREEN.attest, "test", &fp).expect("key");
            let legacy = crate::attest_inputs::input_key(&LEGACY.attest, "test", &fp).expect("key");
            assert_ne!(green, legacy, "each set keys with its own domain");
            let head = plan_only_commit(&dir);
            // The legacy key in the green ref is no green stamp.
            plant(
                &dir,
                GREEN.inputs_ref,
                &legacy,
                &format!("{} test@wrongkey", GREEN.format),
            );
            assert_eq!(stamps_of(&head), ["test@abc"]);
            plant(
                &dir,
                GREEN.inputs_ref,
                &green,
                &format!("{} test@green", GREEN.format),
            );
            assert_eq!(stamps_of(&head), ["test@green"]);
        });
        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
    }

    #[test]
    fn a_green_canonical_note_is_read_under_the_green_domain() {
        let dir = canonical("green-canon", None);
        in_repo(&dir, || {
            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
            let canon = crate::attest_inputs::canonical_route(&tree).expect("canon");
            let key =
                crate::attest_inputs::canon_gate_key(GREEN.canon_domain, &canon).expect("key");
            plant(
                &dir,
                GREEN.inputs_ref,
                &key,
                &format!("{} test@green", GREEN.format),
            );
            let head = plan_only_commit(&dir);
            assert_eq!(stamps_of(&head), ["test@green"]);
        });
        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
    }

    /// `gate_evidence::history_in` reads the runs of both name sets: a run
    /// recorded before the writers switched is still evidence, and a new one
    /// lands in the green ref.
    #[test]
    fn history_reads_runs_under_both_name_sets() {
        let (dir, _head, tree) = unstamped("history-both");
        let other = git(&dir, &["rev-parse", "HEAD"]);
        plant(
            &dir,
            LEGACY.notes_ref,
            &other,
            &format!("{}\nrun 100 old-gate pass 7", LEGACY.format),
        );
        plant(
            &dir,
            GREEN.notes_ref,
            &tree,
            &format!("{}\nrun 200 new-gate pass 9", GREEN.format),
        );
        // A body under the wrong set's header is no evidence.
        plant(
            &dir,
            GREEN.notes_ref,
            &other,
            &format!("{}\nrun 300 mixed-gate pass 1", LEGACY.format),
        );
        let history = crate::gate_evidence::history_in(&dir);
        let mut got: Vec<(String, String)> = history
            .runs
            .iter()
            .map(|(k, r)| (k.clone(), r.gate.clone()))
            .collect();
        got.sort();
        let mut want = vec![
            (other, "old-gate".to_string()),
            (tree, "new-gate".to_string()),
        ];
        want.sort();
        assert_eq!(got, want);
        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
    }

    #[test]
    fn forget_removes_the_refs_of_both_name_sets() {
        let (dir, _head, tree) = unstamped("forget-both");
        plant(
            &dir,
            GREEN.notes_ref,
            &tree,
            &format!("{} test@g", GREEN.format),
        );
        plant(
            &dir,
            LEGACY.notes_ref,
            &tree,
            &format!("{} test@l", LEGACY.format),
        );
        for set in READ {
            plant(&dir, set.done_ref, &tree, "done");
        }
        in_repo(&dir, || {
            assert_eq!(tree_tokens(&tree).len(), 1);
            assert!(forget());
            assert!(tree_tokens(&tree).is_empty(), "{:?}", tree_tokens(&tree));
        });
        for set in READ {
            for r in full_refs(&set) {
                let out = std::process::Command::new("git")
                    .args(["-C"])
                    .arg(&dir)
                    .args(["rev-parse", "--verify", "-q", &r])
                    .output()
                    .unwrap();
                assert!(!out.status.success(), "{r} survived forget");
            }
        }
        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
    }

    #[test]
    fn writes_go_under_the_green_names_and_each_full_ref_names_its_ref() {
        assert_eq!(WRITE, GREEN);
        assert_eq!(FORMAT, "greengate-gate-v1");
        for (full, short) in [
            (NOTES_FULL_REF, NOTES_REF),
            (INPUTS_FULL_REF, INPUTS_REF),
            (CLUSTER_FULL_REF, CLUSTER_REF),
            (DONE_FULL_REF, DONE_REF),
        ] {
            assert_eq!(full, format!("refs/notes/{short}"));
            assert!(full.starts_with("refs/notes/greengate-gate"), "{full}");
        }
        // A writer's merge base is the written ref alone: a legacy note on
        // the key is never copied under the green header.
        let (dir, head, tree) = unstamped("write-green");
        plant(
            &dir,
            LEGACY.notes_ref,
            &tree,
            &format!("{} test@old", LEGACY.format),
        );
        in_repo(&dir, || {
            assert!(stamp_push(&head, &tree, &["suite@p".to_string()]));
            let written = git(&dir, &["notes", "--ref", GREEN.notes_ref, "show", &tree]);
            assert_eq!(written, format!("{} suite@p", GREEN.format));
            // Nothing was written to the legacy ref.
            let old = git(&dir, &["notes", "--ref", LEGACY.notes_ref, "show", &tree]);
            assert_eq!(old, format!("{} test@old", LEGACY.format));
        });
        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
    }
}