treeship-core 0.31.10

Portable trust receipts for agent workflows - core library
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
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
//! `.treeship` package builder and reader.
//!
//! A `.treeship` package is a directory (or tar archive) containing:
//!
//! - `receipt.json`   -- the canonical Session Receipt
//! - `merkle.json`    -- standalone Merkle tree data
//! - `render.json`    -- Explorer render hints
//! - `artifacts/`     -- referenced artifact payloads
//! - `proofs/`        -- inclusion proofs and zk proofs
//! - `preview.html`   -- static preview (optional)

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

use crate::statements::ApprovalStatement;
use crate::verify::{signed_parent, SignedParent};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::receipt::{ArtifactEntry, SessionReceipt, RECEIPT_TYPE};
use crate::statements::{
    approval_revocation_record_digest, approval_use_record_digest,
    journal_checkpoint_record_digest, ApprovalRevocation, ApprovalUse, JournalCheckpoint,
    ReplayCheck, ReplayCheckLevel,
};

/// Errors from package operations.
#[derive(Debug)]
pub enum PackageError {
    Io(std::io::Error),
    Json(serde_json::Error),
    InvalidPackage(String),
}

impl std::fmt::Display for PackageError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(e) => write!(f, "package io: {e}"),
            Self::Json(e) => write!(f, "package json: {e}"),
            Self::InvalidPackage(msg) => write!(f, "invalid package: {msg}"),
        }
    }
}

impl std::error::Error for PackageError {}
impl From<std::io::Error> for PackageError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}
impl From<serde_json::Error> for PackageError {
    fn from(e: serde_json::Error) -> Self {
        Self::Json(e)
    }
}

/// Manifest file inside the package root.
const RECEIPT_FILE: &str = "receipt.json";
const MERKLE_FILE: &str = "merkle.json";
const RENDER_FILE: &str = "render.json";
const ARTIFACTS_DIR: &str = "artifacts";
/// `anchors/<artifact_id>.json`: the witness proofs for a sealed artifact, a
/// JSON array of `RecordAnchor` that each carry a `proof` (TS-2026-003).
/// Absent in packages whose artifacts were never anchored.
pub const ANCHORS_DIR: &str = "anchors";
const PROOFS_DIR: &str = "proofs";
const PREVIEW_FILE: &str = "preview.html";

// Approval Authority package layout (v0.9.9 PR 4).
// approvals/index.json -- top-level index of every approval evidence
//                          file in this package
// approvals/grants/<grant_id>.json    -- copy of the signed
//                          ApprovalStatement envelope (already in
//                          artifacts/ via the chain; mirrored here for
//                          single-directory access during verify)
// approvals/uses/<use_id>.json        -- ApprovalUse record from the
//                          local journal at session-close time
// approvals/checkpoints/<id>.json     -- JournalCheckpoint records that
//                          cover the included uses (PR 6 Hub
//                          checkpoint signing extends this)
const APPROVALS_DIR: &str = "approvals";
const APPROVALS_GRANTS: &str = "approvals/grants";
const APPROVALS_USES: &str = "approvals/uses";
const APPROVALS_CHECKPOINTS: &str = "approvals/checkpoints";
const APPROVALS_INDEX_FILE: &str = "approvals/index.json";

/// Optional approval evidence to embed in the package alongside the
/// receipt + artifacts. None means "no approvals consumed during this
/// session, or none worth exporting." Empty vectors mean "we looked and
/// found nothing"; the resulting package omits the `approvals/` dir
/// entirely so absence is unambiguous.
///
/// Ownership of the evidence stays with the caller: `session::close`
/// gathers the grant envelopes from the chain, the uses from the local
/// journal, and any covering checkpoints, then hands them off here.
#[derive(Debug, Clone, Default)]
pub struct ApprovalsBundle {
    /// Bytes of the signed ApprovalStatement envelopes that authorized
    /// any consumed uses. Each entry is `(grant_id, raw_envelope_json)`.
    /// Stored verbatim so the package's verifier can re-check the
    /// signature without re-serializing.
    pub grants: Vec<(String, Vec<u8>)>,
    /// ApprovalUse records pulled from the local journal at close time.
    /// `action_artifact_id` should be backfilled before passing to
    /// build_package (see `commands/session.rs`).
    pub uses: Vec<ApprovalUse>,
    /// JournalCheckpoints that cover the included uses. Optional; may
    /// be empty even when uses are present (PR 6 fills these in).
    pub checkpoints: Vec<JournalCheckpoint>,
    /// Explicit revocations we wanted to surface (e.g. a use whose
    /// grant was revoked after consumption -- the package should still
    /// show the consumed evidence and the revocation alongside).
    /// Empty in PR 4; reserved.
    pub revocations: Vec<ApprovalRevocation>,

    /// Bytes of each action artifact's signed envelope that consumed an
    /// approval. Each entry is `(action_artifact_id, raw_envelope_json)`.
    /// v0.9.10 PR A: shipped to close the action↔use binding gap. The
    /// verifier extracts `meta.approval_use_id` from each envelope and
    /// cross-checks it against the package's use records. Empty in
    /// pre-v0.9.10 packages; readers must treat absence as "binding
    /// not asserted by package" rather than "binding present and OK."
    pub action_envelopes: Vec<(String, Vec<u8>)>,

    /// Every sealed artifact's signed envelope, `(artifact_id, raw_envelope_json)`,
    /// so the package verifies its own signatures instead of asking the
    /// reader to trust the sealed set (audit 2026-09, AUD-31). Written to
    /// `artifacts/<id>.json`, the same directory the consuming actions above
    /// already use. Empty in pre-0.31.2 packages.
    pub sealed_envelopes: Vec<(String, Vec<u8>)>,
    /// The public half of every key that signed a sealed envelope,
    /// `(key_id, "ed25519:<base64url>")`, written to `keys.json`. A verifier
    /// checks each signature against the key the package names, then
    /// separately reports whether that key is one it has pinned.
    pub signer_keys: Vec<(String, String)>,
    /// Witness proofs for sealed artifacts, `(artifact_id, anchors)`, written
    /// to `anchors/<id>.json` (TS-2026-003). Only anchors that carry a proof
    /// belong here: a local claim without one proves nothing to a reader.
    /// The proofs are unsigned by the package on purpose; each one verifies
    /// on its own against the reader's trusted logs and binds to its
    /// artifact, so the package vouching for it would add nothing.
    pub sealed_anchors: Vec<(String, Vec<crate::storage::RecordAnchor>)>,
}

/// `keys.json` at the package root.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PackageKeys {
    pub schema: String,
    /// key_id -> `ed25519:<base64url public key>`
    pub keys: std::collections::BTreeMap<String, String>,
}

pub const KEYS_FILE: &str = "keys.json";
/// The session's close record (`treeship/receipt/v1`, `session.v1`), signed
/// over the digest of `receipt.json`, sealed beside the package since 0.31.4
/// so the sealed set itself is under a signature (audit follow-up AUD-34).
pub const RECORD_FILE: &str = "record.json";

/// Label the CLI gives this ship's own keys when it adds them as
/// `session_host` roots for a local verify, so `signer_trust` can say
/// "this ship's own key" instead of "pinned".
pub const OWN_KEY_LABEL: &str = "this ship's own key";
pub const PACKAGE_KEYS_SCHEMA: &str = "treeship/package-keys/v1";

/// `approvals/index.json` -- top-level inventory of evidence in the
/// package. Lets a consumer pre-flight what's there before opening
/// every file; doubles as a stable shape for downstream tooling.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalsIndex {
    /// Stable schema marker so future versions can fan out cleanly.
    #[serde(rename = "type")]
    pub type_: String,
    pub schema_version: u32,
    /// Stable kebab-case ids of grants present. Order matches
    /// `grants/` filename order.
    pub grants: Vec<String>,
    /// Use ids present.
    pub uses: Vec<String>,
    pub checkpoints: Vec<String>,
    pub revocations: Vec<String>,
}

impl ApprovalsIndex {
    pub fn type_string() -> &'static str {
        "treeship/approvals-index/v1"
    }
}

/// Result of building a package.
pub struct PackageOutput {
    /// Path to the package directory.
    pub path: PathBuf,
    /// SHA-256 digest of the canonical receipt.json.
    pub receipt_digest: String,
    /// Merkle root hex (if present).
    pub merkle_root: Option<String>,
    /// Number of files in the package.
    pub file_count: usize,
}

/// Build a `.treeship` package directory from a composed receipt.
///
/// Writes all package files into `output_dir/<session_id>.treeship/`.
/// Returns metadata about the written package.
///
/// Backwards-compatible wrapper: callers that don't have approval
/// evidence to export pass through here unchanged. Callers that do
/// (`session::close` with consumed approvals) call
/// `build_package_with_approvals` directly.
pub fn build_package(
    receipt: &SessionReceipt,
    output_dir: &Path,
) -> Result<PackageOutput, PackageError> {
    build_package_with_approvals(receipt, output_dir, None)
}

/// Like `build_package` but also embeds approval evidence (PR 4 of v0.9.9).
/// `bundle = None` is identical to `build_package`; the `approvals/`
/// directory is omitted entirely so absence stays unambiguous.
pub fn build_package_with_approvals(
    receipt: &SessionReceipt,
    output_dir: &Path,
    bundle: Option<&ApprovalsBundle>,
) -> Result<PackageOutput, PackageError> {
    let session_id = &receipt.session.id;
    let pkg_dir = output_dir.join(format!("{session_id}.treeship"));

    // A package is written below the sessions directory the caller named;
    // nothing from there down may be a link, and every file is created
    // fresh (never through a link or into a hard link).
    crate::fs_safe::create_dir_all_below(output_dir, &pkg_dir)?;
    crate::fs_safe::create_dir_all_below(output_dir, &pkg_dir.join(ARTIFACTS_DIR))?;
    crate::fs_safe::create_dir_all_below(output_dir, &pkg_dir.join(PROOFS_DIR))?;

    let mut file_count = 0usize;

    // 1. receipt.json -- canonical serialization
    let receipt_bytes = serde_json::to_vec_pretty(receipt)?;
    crate::fs_safe::write_atomic(&pkg_dir.join(RECEIPT_FILE), &receipt_bytes, 0o644)?;
    file_count += 1;

    let receipt_hash = Sha256::digest(&receipt_bytes);
    let receipt_digest = format!("sha256:{}", hex::encode(receipt_hash));

    // 2. merkle.json -- standalone copy of the Merkle section
    let merkle_bytes = serde_json::to_vec_pretty(&receipt.merkle)?;
    crate::fs_safe::write_atomic(&pkg_dir.join(MERKLE_FILE), &merkle_bytes, 0o644)?;
    file_count += 1;

    // 3. render.json
    let render_bytes = serde_json::to_vec_pretty(&receipt.render)?;
    crate::fs_safe::write_atomic(&pkg_dir.join(RENDER_FILE), &render_bytes, 0o644)?;
    file_count += 1;

    // 4. Write inclusion proofs as individual files
    for proof_entry in &receipt.merkle.inclusion_proofs {
        let proof_bytes = serde_json::to_vec_pretty(proof_entry)?;
        let filename = format!("{}.proof.json", proof_entry.artifact_id);
        crate::fs_safe::write_atomic(
            &pkg_dir.join(PROOFS_DIR).join(filename),
            &proof_bytes,
            0o644,
        )?;
        file_count += 1;
    }

    // 5. preview.html stub
    if receipt.render.generate_preview {
        let preview = render_preview_html_with_approvals(receipt, bundle);
        crate::fs_safe::write_atomic(&pkg_dir.join(PREVIEW_FILE), preview.as_bytes(), 0o644)?;
        file_count += 1;
    }

    // 6. Approval evidence (v0.9.9 PR 4). Only writes when the caller
    // supplied a bundle AND that bundle has at least one entry; an empty
    // bundle behaves the same as None so a session with no consumed
    // approvals doesn't leave behind an empty `approvals/` directory.
    if let Some(b) = bundle {
        // The sealed set's own envelopes and keys, independent of whether
        // any approval evidence exists.
        if !b.sealed_envelopes.is_empty() {
            crate::fs_safe::create_dir_all_below(output_dir, &pkg_dir.join(ARTIFACTS_DIR))?;
            for (artifact_id, envelope_bytes) in &b.sealed_envelopes {
                let safe = sanitize_filename(artifact_id);
                let path = pkg_dir.join(ARTIFACTS_DIR).join(format!("{safe}.json"));
                if !path.exists() {
                    crate::fs_safe::write_atomic(&path, envelope_bytes, 0o644)?;
                    file_count += 1;
                }
            }
        }
        let proofs: Vec<_> = b
            .sealed_anchors
            .iter()
            .map(|(id, anchors)| {
                let with_proof: Vec<_> = anchors
                    .iter()
                    .filter(|a| a.proof.is_some())
                    .cloned()
                    .collect();
                (id, with_proof)
            })
            .filter(|(_, a)| !a.is_empty())
            .collect();
        if !proofs.is_empty() {
            crate::fs_safe::create_dir_all_below(output_dir, &pkg_dir.join(ANCHORS_DIR))?;
            for (artifact_id, anchors) in proofs {
                let safe = sanitize_filename(artifact_id);
                std::fs::write(
                    pkg_dir.join(ANCHORS_DIR).join(format!("{safe}.json")),
                    serde_json::to_vec_pretty(&anchors)?,
                )?;
                file_count += 1;
            }
        }
        if !b.signer_keys.is_empty() {
            let keys = PackageKeys {
                schema: PACKAGE_KEYS_SCHEMA.into(),
                keys: b.signer_keys.iter().cloned().collect(),
            };
            crate::fs_safe::write_atomic(
                &pkg_dir.join(KEYS_FILE),
                &serde_json::to_vec_pretty(&keys)?,
                0o644,
            )?;
            file_count += 1;
        }
        if !b.grants.is_empty()
            || !b.uses.is_empty()
            || !b.checkpoints.is_empty()
            || !b.revocations.is_empty()
            || !b.action_envelopes.is_empty()
        {
            crate::fs_safe::create_dir_all_below(output_dir, &pkg_dir.join(APPROVALS_GRANTS))?;
            crate::fs_safe::create_dir_all_below(output_dir, &pkg_dir.join(APPROVALS_USES))?;
            crate::fs_safe::create_dir_all_below(output_dir, &pkg_dir.join(APPROVALS_CHECKPOINTS))?;
            // v0.9.10 PR A: write action envelopes that consumed an
            // approval. The artifacts/ directory was created earlier
            // for the package layout but never populated; closing the
            // action↔use binding gap requires the verifier to be able
            // to read each consuming action's `meta.approval_use_id`.
            crate::fs_safe::create_dir_all_below(output_dir, &pkg_dir.join(ARTIFACTS_DIR))?;
            for (artifact_id, envelope_bytes) in &b.action_envelopes {
                let safe = sanitize_filename(artifact_id);
                std::fs::write(
                    pkg_dir.join(ARTIFACTS_DIR).join(format!("{safe}.json")),
                    envelope_bytes,
                )?;
                file_count += 1;
            }

            let mut grant_ids = Vec::with_capacity(b.grants.len());
            for (grant_id, envelope_bytes) in &b.grants {
                let safe = sanitize_filename(grant_id);
                std::fs::write(
                    pkg_dir.join(APPROVALS_GRANTS).join(format!("{safe}.json")),
                    envelope_bytes,
                )?;
                grant_ids.push(grant_id.clone());
                file_count += 1;
            }

            let mut use_ids = Vec::with_capacity(b.uses.len());
            for u in &b.uses {
                let safe = sanitize_filename(&u.use_id);
                let bytes = serde_json::to_vec_pretty(u)?;
                std::fs::write(
                    pkg_dir.join(APPROVALS_USES).join(format!("{safe}.json")),
                    &bytes,
                )?;
                use_ids.push(u.use_id.clone());
                file_count += 1;
            }

            let mut checkpoint_ids = Vec::with_capacity(b.checkpoints.len());
            for cp in &b.checkpoints {
                let safe = sanitize_filename(&cp.checkpoint_id);
                let bytes = serde_json::to_vec_pretty(cp)?;
                std::fs::write(
                    pkg_dir
                        .join(APPROVALS_CHECKPOINTS)
                        .join(format!("{safe}.json")),
                    &bytes,
                )?;
                checkpoint_ids.push(cp.checkpoint_id.clone());
                file_count += 1;
            }

            let mut revocation_ids = Vec::with_capacity(b.revocations.len());
            for rev in &b.revocations {
                let safe = sanitize_filename(&rev.revocation_id);
                let bytes = serde_json::to_vec_pretty(rev)?;
                std::fs::write(
                    pkg_dir
                        .join(APPROVALS_DIR)
                        .join(format!("revocations-{safe}.json")),
                    &bytes,
                )?;
                revocation_ids.push(rev.revocation_id.clone());
                file_count += 1;
            }

            let index = ApprovalsIndex {
                type_: ApprovalsIndex::type_string().into(),
                schema_version: 1,
                grants: grant_ids,
                uses: use_ids,
                checkpoints: checkpoint_ids,
                revocations: revocation_ids,
            };
            let index_bytes = serde_json::to_vec_pretty(&index)?;
            crate::fs_safe::write_atomic(&pkg_dir.join(APPROVALS_INDEX_FILE), &index_bytes, 0o644)?;
            file_count += 1;
        }
    }

    Ok(PackageOutput {
        path: pkg_dir,
        receipt_digest,
        merkle_root: receipt.merkle.root.clone(),
        file_count,
    })
}

/// Sanitize an id (artifact_id, use_id, checkpoint_id) into a filesystem-safe
/// filename. Underscores everything that isn't alphanumeric, dash, or dot.
/// Not a security boundary; the digest chain is the integrity check.
fn sanitize_filename(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '.' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// Read approval evidence embedded in a package, if any. Returns
/// `Ok(ApprovalsBundle::default())` when the package has no `approvals/`
/// directory (the typical case for sessions that didn't consume any
/// scoped approvals). Errors only on malformed JSON inside files that
/// the index claims exist.
///
/// Quiet on missing-directory by design: PR 4 packages and pre-PR-4
/// packages should both round-trip through verify without spurious
/// failures.
pub fn read_approvals_bundle(pkg_dir: &Path) -> Result<ApprovalsBundle, PackageError> {
    let approvals_dir = pkg_dir.join(APPROVALS_DIR);
    if !approvals_dir.is_dir() {
        return Ok(ApprovalsBundle::default());
    }

    let mut bundle = ApprovalsBundle::default();

    // Grants are raw envelopes by file; we don't parse here, the
    // verify layer can re-check the signature.
    let grants_dir = pkg_dir.join(APPROVALS_GRANTS);
    if grants_dir.is_dir() {
        for entry in std::fs::read_dir(&grants_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) != Some("json") {
                continue;
            }
            let id = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_string();
            let bytes = std::fs::read(&path)?;
            bundle.grants.push((id, bytes));
        }
    }

    let uses_dir = pkg_dir.join(APPROVALS_USES);
    if uses_dir.is_dir() {
        for entry in std::fs::read_dir(&uses_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) != Some("json") {
                continue;
            }
            let bytes = std::fs::read(&path)?;
            let u: ApprovalUse = serde_json::from_slice(&bytes)?;
            bundle.uses.push(u);
        }
    }

    let cps_dir = pkg_dir.join(APPROVALS_CHECKPOINTS);
    if cps_dir.is_dir() {
        for entry in std::fs::read_dir(&cps_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) != Some("json") {
                continue;
            }
            let bytes = std::fs::read(&path)?;
            let cp: JournalCheckpoint = serde_json::from_slice(&bytes)?;
            bundle.checkpoints.push(cp);
        }
    }

    // v0.9.10 PR A: read action envelopes shipped to support the
    // action↔use binding check. Pre-v0.9.10 packages have an empty
    // artifacts/ dir (the dir was created but never populated); the
    // bundle's `action_envelopes` stays empty in that case, and the
    // verifier reports the binding row honestly as "not asserted by
    // package" rather than silently passing.
    let arts_dir = pkg_dir.join(ARTIFACTS_DIR);
    if arts_dir.is_dir() {
        for entry in std::fs::read_dir(&arts_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) != Some("json") {
                continue;
            }
            let id = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_string();
            let bytes = std::fs::read(&path)?;
            bundle.action_envelopes.push((id, bytes));
        }
    }

    Ok(bundle)
}

/// Read and parse a `.treeship` package from disk.
pub fn read_package(pkg_dir: &Path) -> Result<SessionReceipt, PackageError> {
    let receipt_path = pkg_dir.join(RECEIPT_FILE);
    if !receipt_path.exists() {
        return Err(PackageError::InvalidPackage(format!(
            "missing {RECEIPT_FILE} in {}",
            pkg_dir.display()
        )));
    }
    let bytes = std::fs::read(&receipt_path)?;
    let receipt: SessionReceipt = serde_json::from_slice(&bytes)?;

    if receipt.type_ != RECEIPT_TYPE {
        return Err(PackageError::InvalidPackage(format!(
            "unexpected type: {} (expected {RECEIPT_TYPE})",
            receipt.type_
        )));
    }

    Ok(receipt)
}

/// The one word a package verify comes to. `Verified` and `SignaturesPass`
/// each need rows that PASSED, never merely the absence of a failure: an
/// empty package, or one whose record or trust rows never ran, used to read
/// `verified` because nothing had failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PackageVerdict {
    /// Every signature verifies, the close record binds receipt.json, and
    /// every signing key (record included) is pinned here or this ship's own.
    Verified,
    /// As `Verified`, but at least one signing key is not pinned here.
    SignaturesPass,
    /// `--structural`: structure and approvals only; signatures unchecked.
    StructuralPass,
    /// A row failed, or a row `verified` depends on did not pass. The string
    /// says which.
    Failed(String),
}

impl PackageVerdict {
    /// The stable word printed and emitted as JSON `verdict`.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Verified => "verified",
            Self::SignaturesPass => "signatures-pass",
            Self::StructuralPass => "structural-pass",
            Self::Failed(_) => "failed",
        }
    }
}

/// Reduce a package verify's rows to its verdict. `StructuralPass` needs a
/// passing `merkle_root` row (a sealed set to be the structure of). Outside
/// `--structural`,
/// `Verified` and `SignaturesPass` require all of: at least one `signature:`
/// row PASS, `receipt_binding` PASS, and a `signer_trust` row (PASS for
/// `Verified`, WARN for `SignaturesPass`). Anything else is `Failed`.
pub fn package_verdict(checks: &[VerifyCheck], structural_only: bool) -> PackageVerdict {
    let failed: Vec<&str> = checks
        .iter()
        .filter(|c| c.status == VerifyStatus::Fail)
        .map(|c| c.name.as_str())
        .collect();
    if !failed.is_empty() {
        return PackageVerdict::Failed(format!("failed: {}", failed.join(", ")));
    }
    let status = |name: &str| {
        checks
            .iter()
            .find(|c| c.name == name)
            .map(|c| c.status.clone())
    };
    if structural_only {
        // Structure needs a sealed set to be the structure of: an empty
        // package proves nothing (the receipt-only verifier fails it too).
        if status("merkle_root") != Some(VerifyStatus::Pass) {
            return PackageVerdict::Failed("not verified: the package seals no artifacts".into());
        }
        return PackageVerdict::StructuralPass;
    }
    let mut missing = Vec::new();
    if !checks
        .iter()
        .any(|c| c.name.starts_with("signature:") && c.status == VerifyStatus::Pass)
    {
        missing.push("no artifact signature verified");
    }
    if status("receipt_binding") != Some(VerifyStatus::Pass) {
        missing.push("the close record does not bind receipt.json");
    }
    let trust = status("signer_trust");
    if trust.is_none() {
        missing.push("no signing key was judged");
    }
    if !missing.is_empty() {
        return PackageVerdict::Failed(format!("not verified: {}", missing.join("; ")));
    }
    // An approval signed by an approver nobody pinned cannot make the
    // actions it authorizes `verified`.
    let approver_ok = status("approval_signer").is_none_or(|s| s == VerifyStatus::Pass);
    match trust {
        Some(VerifyStatus::Pass) if approver_ok => PackageVerdict::Verified,
        _ => PackageVerdict::SignaturesPass,
    }
}

/// Whether the package's close record (`record.json`, the signature that
/// seals the receipt) verifies under one of `keys` -- a signature that
/// holds, not a key-id match. The CLI uses it to tell the producer's own
/// machine from a foreign verifier, for checks only the producer can run,
/// such as its Approval Use Journal (W1-13). Only the close signer counts:
/// an approver whose key signed one sealed approval did not produce the
/// session, holds no journal for it, and must not be failed for lacking
/// one.
pub fn package_close_signed_by(pkg_dir: &Path, keys: &[ed25519_dalek::VerifyingKey]) -> bool {
    let Some(env) = std::fs::read(pkg_dir.join(RECORD_FILE))
        .ok()
        .and_then(|raw| crate::attestation::Envelope::from_json(&raw).ok())
    else {
        return false;
    };
    if env.payload_type != crate::statements::payload_type("receipt") {
        return false;
    }
    env.signatures.iter().any(|sig| {
        keys.iter()
            .any(|vk| crate::attestation::verify_with_key(&env, &sig.keyid, *vk).is_ok())
    })
}

/// Verify a `.treeship` package locally.
///
/// Returns a list of check results. All must pass for the package to be valid.
///
/// Auto-loads the operator's trust roots from
/// `TrustRootStore::default_path()`. Use
/// [`verify_package_with_trust`] when the trust store is already in
/// hand (CLI paths that take a `Ctx`, or tests).
///
/// Audit lane J fix-up: `open_default_or_empty` propagates `Malformed`
/// and `PermissionsTooOpen` errors -- those are operator
/// misconfiguration that must NOT be silently downgraded to an empty
/// trust store (an empty store fails verification of any hub-org
/// checkpoint, which is the right end-state, but the operator needs a
/// clear "your trust file is broken" diagnostic instead of a misleading
/// "untrusted issuer" message). Surface the error as a `trust-root`
/// fail row and stop before doing real work that depends on trust.
pub fn verify_package(pkg_dir: &Path) -> Result<Vec<VerifyCheck>, PackageError> {
    let trust = match crate::trust::TrustRootStore::open_default_or_empty() {
        Ok(t) => t,
        Err(e) => {
            // Build a minimal check list so the caller's printer still
            // renders a coherent failure rather than silently routing
            // through a fake empty store.
            return Ok(vec![VerifyCheck::fail(
                "trust-root",
                &format!("trust store unreadable: {e}"),
            )]);
        }
    };
    verify_package_with_trust(pkg_dir, &trust)
}

/// Like `verify_package` but takes an explicit `TrustRootStore` so the
/// caller can verify with a constructed-in-memory trust set (tests) or
/// a non-default location (CLI `--trust-roots`).
pub fn verify_package_with_trust(
    pkg_dir: &Path,
    trust: &crate::trust::TrustRootStore,
) -> Result<Vec<VerifyCheck>, PackageError> {
    verify_package_with_options(pkg_dir, trust, false)
}

/// Structural checks only: the receipt, the Merkle tree, the approvals
/// evidence. A package that carries no artifact envelopes (every package
/// built before 0.31.2) cannot be signature-verified from its own bytes,
/// and the default verifier fails it for that reason. This entry point
/// downgrades that failure to a warning for callers who know they are
/// looking at structure, not evidence.
pub fn verify_package_structural(pkg_dir: &Path) -> Result<Vec<VerifyCheck>, PackageError> {
    let trust = crate::trust::TrustRootStore::open_default_or_empty()
        .unwrap_or_else(|_| crate::trust::TrustRootStore::empty());
    verify_package_with_options(pkg_dir, &trust, true)
}

pub fn verify_package_with_options(
    pkg_dir: &Path,
    trust: &crate::trust::TrustRootStore,
    structural_only: bool,
) -> Result<Vec<VerifyCheck>, PackageError> {
    let mut checks = Vec::new();

    // 1. receipt.json exists and parses
    let receipt = match read_package(pkg_dir) {
        Ok(r) => {
            checks.push(VerifyCheck::pass(
                "receipt.json",
                "Parses as valid Session Receipt",
            ));
            r
        }
        Err(e) => {
            checks.push(VerifyCheck::fail(
                "receipt.json",
                &format!("Failed to parse: {e}"),
            ));
            return Ok(checks);
        }
    };

    // 2. Type field
    if receipt.type_ == RECEIPT_TYPE {
        checks.push(VerifyCheck::pass("type", "Correct receipt type"));
    } else {
        checks.push(VerifyCheck::fail(
            "type",
            &format!("Expected {RECEIPT_TYPE}, got {}", receipt.type_),
        ));
    }

    // 3. Determinism: re-serialize and check digest matches.
    //
    // IMPORTANT SCOPE NOTE (do not read this row as integrity): this only
    // confirms the receipt struct round-trips to the same bytes. It is NOT a
    // signature check. The Merkle root below covers ONLY the artifact IDs;
    // the receipt's timeline, side_effects, tool_usage, and narrative are
    // composed from the (unsigned) event log and are NOT cryptographically
    // bound by anything in this package. An attacker who edits those fields
    // and re-serializes will pass determinism and pass the Merkle check.
    // The authenticated anchor over the whole receipt is the actor-signed
    // `session.v1` record (which binds receipt_digest) in the agent's chain;
    // embedding + requiring it here is tracked as a follow-up. Until then,
    // `package verify` authenticates the ARTIFACTS, not the narrative, and
    // says so via the explicit scope check below.
    let receipt_path = pkg_dir.join(RECEIPT_FILE);
    let on_disk = std::fs::read(&receipt_path)?;
    let re_serialized = serde_json::to_vec_pretty(&receipt)?;
    if on_disk == re_serialized {
        checks.push(VerifyCheck::pass(
            "determinism",
            "receipt.json round-trips identically (structural, NOT a signature)",
        ));
    } else {
        // Not a hard failure -- pretty-print whitespace may differ
        checks.push(VerifyCheck::warn(
            "determinism",
            "receipt.json does not byte-match after re-serialization",
        ));
    }

    // 3b. Scope of what this package authenticates for the receipt body
    // (timeline / side_effects / tool_usage / narrative). It is composed from
    // the event log, not signed per entry. Since 0.31.4 the close record in
    // record.json signs the digest of the whole receipt.json, so editing any
    // of it fails `receipt_binding`; the row below reports that, or the
    // absence of it. It used to warn unconditionally, next to a PASS that
    // said the opposite (film findings 2026-09-22, gate report).
    // Pushed after the record binding check runs, see 3c.

    // 3c. Coverage: does the sealed set say what the harness could observe?
    // A `coverage.v1` receipt minted at close carries the declared capture
    // level, the connection modes and the counted events; without it a
    // reader has no denominator for the timeline. Reported, never a fail:
    // packages sealed before 0.31.6 carry none.
    checks.push(coverage_check(pkg_dir, &receipt));

    // 3d. Network scope: when the session declared one, say whether every
    // recorded destination fell inside it. No scope declared, no row: the
    // connections stand in side_effects as recorded, unjudged.
    if let Some(tu) = receipt.tool_usage.as_ref() {
        if !tu.network_declared.is_empty() {
            let total = receipt.side_effects.network_connections.len();
            if tu.network_off_scope.is_empty() {
                checks.push(VerifyCheck::pass(
                    "network_scope",
                    &format!(
                        "{total} recorded connection(s), all within the declared scope [{}]",
                        tu.network_declared.join(", ")
                    ),
                ));
            } else {
                checks.push(VerifyCheck::warn(
                    "network_scope",
                    &format!(
                        "{} destination(s) outside the declared scope [{}]: {}",
                        tu.network_off_scope.len(),
                        tu.network_declared.join(", "),
                        tu.network_off_scope.join(", ")
                    ),
                ));
            }
        }
    }

    // 3e. Retries: actions that name an earlier attempt. Reported only when
    // the sealed set carries any. Checks the chain is consistent (same
    // action and actor, attempts count up, same idempotency key when both
    // sides carry one, the retried attempt is in this package) and that two
    // attempts do not both claim a distinct effect, which is the shape of a
    // duplicated ticket rather than a recovered one.
    if let Some(row) = retries_check(pkg_dir, &receipt) {
        checks.push(row);
    }

    // 3f. Judgements: model answers the producer acted on. Reported only
    // when the sealed set carries any; flags one acted on below its own
    // declared bar, or with no bar at all. The row does not re-run a judge.
    if let Some(row) = judgements_check(pkg_dir, &receipt) {
        checks.push(row);
    }

    // 4. Merkle root re-computation
    if !receipt.artifacts.is_empty() {
        // Recompute under the receipt's declared merkle version so
        // legacy (v0.10.2 and earlier, version=1, no domain separation)
        // receipts continue to verify. New receipts always emit v2.
        // Construct through the validating `with_version` so an unknown
        // version surfaces as a hard fail rather than silently falling
        // back to v1.
        let version = receipt.merkle.merkle_version;
        let mut tree = match crate::merkle::MerkleTree::with_version(version) {
            Ok(t) => t,
            Err(e) => {
                checks.push(VerifyCheck::fail(
                    "merkle_root",
                    &format!("receipt declared unknown merkle_version: {e}"),
                ));
                // Skip the remaining merkle/inclusion work; emit the
                // leaf_count + timeline tail and return.
                return Ok(finish_package_checks(checks, &receipt));
            }
        };
        for art in &receipt.artifacts {
            tree.append(&art.artifact_id);
        }
        let root_bytes = tree.root();
        let recomputed_root = root_bytes.map(|r| format!("mroot_{}", hex::encode(r)));
        let root_hex = root_bytes.map(hex::encode).unwrap_or_default();

        if recomputed_root == receipt.merkle.root {
            checks.push(VerifyCheck::pass(
                "merkle_root",
                "Merkle root matches recomputed value",
            ));
        } else {
            checks.push(VerifyCheck::fail(
                "merkle_root",
                &format!(
                    "Mismatch: on-disk {:?} vs recomputed {:?}",
                    receipt.merkle.root, recomputed_root
                ),
            ));
        }

        // 5. Verify each inclusion proof. Per-proof merkle_version must
        // match the receipt section's declared version — drift is a
        // hard fail (smuggled v1 proof inside a v2 receipt would
        // otherwise dispatch through the weaker hashing path).
        for proof_entry in &receipt.merkle.inclusion_proofs {
            if proof_entry.proof.merkle_version != version {
                checks.push(VerifyCheck::fail(
                    &format!("inclusion:{}", proof_entry.artifact_id),
                    &format!(
                        "proof merkle_version {} != receipt section v{}",
                        proof_entry.proof.merkle_version, version,
                    ),
                ));
                continue;
            }
            let verified = crate::merkle::MerkleTree::verify_proof(
                version,
                &root_hex,
                &proof_entry.artifact_id,
                &proof_entry.proof,
            );
            if verified {
                checks.push(VerifyCheck::pass(
                    &format!("inclusion:{}", proof_entry.artifact_id),
                    "Inclusion proof valid",
                ));
            } else {
                checks.push(VerifyCheck::fail(
                    &format!("inclusion:{}", proof_entry.artifact_id),
                    "Inclusion proof failed verification",
                ));
            }
        }
    } else {
        checks.push(VerifyCheck::warn("merkle_root", "No artifacts to verify"));
    }

    // Signatures and chain linkage, from the package's own envelopes
    // (audit 2026-09, AUD-31 / AUD-32; QA TS-002b).
    let sealed = verify_sealed_envelopes(pkg_dir, &receipt, structural_only, &mut checks);
    verify_stapled_anchors(pkg_dir, &receipt, trust, &mut checks);
    let (body_bound, vouched) =
        verify_receipt_binding(pkg_dir, &receipt, structural_only, &sealed, &mut checks);
    let authenticated = push_signer_trust(
        pkg_dir,
        &sealed.signers,
        vouched.as_ref(),
        trust,
        &mut checks,
    );
    // Approvers include the signers of grants carried in approvals/ (an
    // approval minted before the session is not sealed).
    let mut approvers = sealed.approval_signers.clone();
    approvers.extend(
        bundle_grants(pkg_dir, &read_approvals_bundle(pkg_dir).unwrap_or_default())
            .0
            .into_iter()
            .map(|g| g.keyid),
    );
    push_chain_completeness(&receipt, &sealed, &authenticated, &mut checks);
    push_approval_signer(pkg_dir, &approvers, trust, &mut checks);
    push_key_id_collisions(pkg_dir, trust, &mut checks);
    push_approval_evidence(pkg_dir, &receipt, structural_only, &mut checks);
    if body_bound {
        checks.push(VerifyCheck::pass(
            "receipt_body_binding",
            "timeline/side-effects/narrative are bound: the close record (record.json) signs the digest of the whole receipt.json, so editing any of them fails receipt_binding. They remain the producer's own account of the session, composed from its event log and signed by its key; the artifacts are the evidence",
        ));
    } else {
        checks.push(VerifyCheck::warn(
            "receipt_body_binding",
            "timeline/side-effects/narrative are NOT signed in this package — only the artifacts and Merkle root are cryptographically bound. For an authenticated record of the session, verify the actor-signed session.v1 record (or the published report).",
        ));
    }
    verify_session_window(pkg_dir, &receipt, &mut checks);

    // 6. Leaf count matches artifacts
    if receipt.merkle.leaf_count == receipt.artifacts.len() {
        checks.push(VerifyCheck::pass(
            "leaf_count",
            "Leaf count matches artifact count",
        ));
    } else {
        checks.push(VerifyCheck::fail(
            "leaf_count",
            &format!(
                "leaf_count {} != artifact count {}",
                receipt.merkle.leaf_count,
                receipt.artifacts.len()
            ),
        ));
    }

    // 7. Timeline ordering (determinism rule: timestamp, sequence_no, event_id)
    let ordered = receipt.timeline.windows(2).all(|w| {
        (&w[0].timestamp, w[0].sequence_no, &w[0].event_id)
            <= (&w[1].timestamp, w[1].sequence_no, &w[1].event_id)
    });
    if ordered {
        checks.push(VerifyCheck::pass(
            "timeline_order",
            "Timeline is correctly ordered",
        ));
    } else {
        checks.push(VerifyCheck::fail(
            "timeline_order",
            "Timeline entries are not in deterministic order",
        ));
    }

    // event_log completeness: when session::close skipped malformed
    // event log lines, the count is recorded on receipt.proofs.event_log_skipped.
    // Surface as WARN (not FAIL) because the receipt is still
    // cryptographically valid -- we just want a downstream verifier to
    // know that some evidence was dropped before the receipt was sealed.
    // A future --strict flag can promote this to FAIL.
    // Codex adversarial review finding #8.
    if receipt.proofs.event_log_skipped > 0 {
        checks.push(VerifyCheck::warn(
            "event_log_completeness",
            &format!(
                "{} event(s) skipped during close (malformed lines in events.jsonl). \
                 Receipt is cryptographically valid but does not represent the full event stream. \
                 Inspect close-time stderr or the events.jsonl directly to investigate.",
                receipt.proofs.event_log_skipped,
            ),
        ));
    }

    if receipt.proofs.reconcile_untracked_truncated > 0 {
        checks.push(VerifyCheck::warn(
            "reconcile_completeness",
            &format!(
                "untracked git reconcile exceeded cap {} (saw at least {}). \
                 Per-file synthetic events were skipped and the receipt is bounded, not complete for untracked files.",
                receipt.proofs.reconcile_untracked_cap,
                receipt.proofs.reconcile_untracked_truncated,
            ),
        ));
    }

    // AUD-07: the git-diff backstop was disabled between session start and
    // close (git worked at start — a HEAD was captured — but not at close).
    // A file changed via a non-AgentWroteFile channel could be missing from
    // the "Files changed" ledger with no other signal, so this must not read
    // as a clean, complete audit trail.
    if receipt.proofs.reconcile_degraded {
        checks.push(VerifyCheck::warn(
            "reconcile_degraded",
            "the git reconcile backstop was UNAVAILABLE at session close although git worked at start \
             (.git removed, corrupt index, or git not on PATH). Files changed outside a captured \
             AgentWroteFile event may be MISSING from this receipt's file ledger — treat the \
             \"Files changed\" list as incomplete.",
        ));
    }

    // 8. Approval evidence -- v0.9.9 PR 4. Three independent replay
    // checks, each emitted as its own VerifyCheck row so the printer
    // (and downstream tooling) can render them separately.
    //
    //   replay-package-local      duplicate uses INSIDE this package
    //   replay-included-checkpoint  embedded JournalCheckpoints verify standalone
    //
    // The local-journal level requires access to the workspace journal,
    // which the package alone doesn't carry; that check runs in the CLI
    // verify_package wrapper that has Ctx access. The hub-org level is
    // reserved for PR 6 -- not claimed without a real Hub checkpoint.
    let bundle = read_approvals_bundle(pkg_dir).unwrap_or_default();
    add_approval_evidence_checks(&mut checks, &bundle, trust);
    // Under --structural too: the per-artifact signature rows are still
    // checked in that mode, and a carried grant whose signature fails, or
    // an approval used past its signed limit, is a failure of the bytes
    // themselves, not of trust. Without this a package read as structure
    // passed on a forged grant.
    push_approval_use_limit(pkg_dir, &receipt, &bundle, structural_only, &mut checks);

    Ok(checks)
}

/// `approval-use-limit`: an approval is used no more often than its SIGNED
/// scope allows. `replay-package-local` reads max_uses from the use record,
/// which is unsigned: raise it and recompute the record digest, and a
/// second use of a single-use approval passed. Here the limit comes from
/// the sealed approval whose signature row passed (`scope.maxActions`), and
/// both the sealed consuming actions and the use records for its nonce are
/// counted against it; each consuming action also needs its own use record.
/// A grant envelope carried in `approvals/grants` (an approval minted before
/// the session started is there, not in the sealed set), checked like a
/// sealed artifact: its signature verifies under the key the package names
/// and its id re-derives from the signed bytes.
struct BundleGrant {
    id: String,
    keyid: String,
    nonce_digest: Option<String>,
    max: Option<u32>,
}

/// The package's grant envelopes: (verified, failed-with-reason).
fn bundle_grants(pkg_dir: &Path, bundle: &ApprovalsBundle) -> (Vec<BundleGrant>, Vec<String>) {
    let keys = package_verifying_keys(pkg_dir);
    let mut ok = Vec::new();
    let mut bad = Vec::new();
    for (grant_id, raw) in &bundle.grants {
        let env = match crate::attestation::Envelope::from_json(raw) {
            Ok(e) => e,
            Err(e) => {
                bad.push(format!("{grant_id}: envelope does not parse ({e})"));
                continue;
            }
        };
        let Some(sig) = env.signatures.first() else {
            bad.push(format!("{grant_id}: no signature"));
            continue;
        };
        let Some(vk) = keys.get(&sig.keyid) else {
            bad.push(format!(
                "{grant_id}: signed by {}, a key the package does not carry",
                sig.keyid
            ));
            continue;
        };
        match crate::attestation::verify_with_key(&env, &sig.keyid, *vk) {
            Ok(res) if res.artifact_id == *grant_id => {}
            Ok(res) => {
                bad.push(format!(
                    "{grant_id}: the signed bytes re-derive to {}",
                    res.artifact_id
                ));
                continue;
            }
            Err(e) => {
                bad.push(format!("{grant_id}: invalid signature ({e})"));
                continue;
            }
        }
        let v = env
            .payload_bytes()
            .ok()
            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok());
        let max = match signed_max_actions(v.as_ref()) {
            Ok(m) => m,
            Err(detail) => {
                bad.push(format!("{grant_id}: {detail}"));
                continue;
            }
        };
        ok.push(BundleGrant {
            id: grant_id.clone(),
            keyid: sig.keyid.clone(),
            nonce_digest: v
                .as_ref()
                .and_then(|v| v.get("nonce"))
                .and_then(|n| n.as_str())
                .map(crate::statements::nonce_digest),
            max,
        });
    }
    (ok, bad)
}

/// `scope.maxActions` from a signed approval payload: absent means
/// unbounded; a value the use counter cannot hold is an error, never a
/// truncated (smaller) limit.
fn signed_max_actions(payload: Option<&serde_json::Value>) -> Result<Option<u32>, String> {
    let Some(m) = payload
        .and_then(|v| v.get("scope"))
        .and_then(|s| s.get("maxActions"))
    else {
        return Ok(None);
    };
    let Some(n) = m.as_u64() else {
        return Err(format!("scope.maxActions is {m}, not a whole number"));
    };
    u32::try_from(n)
        .map(Some)
        .map_err(|_| format!("scope.maxActions {n} is beyond the supported range"))
}

fn push_approval_use_limit(
    pkg_dir: &Path,
    receipt: &SessionReceipt,
    bundle: &ApprovalsBundle,
    structural_only: bool,
    checks: &mut Vec<VerifyCheck>,
) {
    use std::collections::{BTreeMap, BTreeSet};
    let verified = |id: &str| {
        checks
            .iter()
            .any(|c| c.name == format!("signature:{id}") && c.status == VerifyStatus::Pass)
    };
    // nonce digest -> (grant id, signed max), and -> consuming action ids
    let mut grants: BTreeMap<String, (String, Option<u32>)> = BTreeMap::new();
    let mut consumers: BTreeMap<String, Vec<String>> = BTreeMap::new();
    // Two different approvals with one nonce: which limit applies would be
    // the verifier's guess (the last one read won).
    let mut shared: Vec<String> = Vec::new();
    // Sealed approvals whose signed scope cannot be counted against.
    let mut bad_scopes: Vec<String> = Vec::new();
    for a in &receipt.artifacts {
        let Some(env) = std::fs::read(
            pkg_dir
                .join(ARTIFACTS_DIR)
                .join(format!("{}.json", sanitize_filename(&a.artifact_id))),
        )
        .ok()
        .and_then(|raw| crate::attestation::Envelope::from_json(&raw).ok()) else {
            continue;
        };
        let Some(v) = env
            .payload_bytes()
            .ok()
            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
        else {
            continue;
        };
        if env.payload_type == crate::statements::payload_type("approval") {
            if !verified(&a.artifact_id) {
                continue;
            }
            if let Some(n) = v.get("nonce").and_then(|n| n.as_str()) {
                let max = match signed_max_actions(Some(&v)) {
                    Ok(m) => m,
                    Err(detail) => {
                        bad_scopes.push(format!("approval {}: {detail}", a.artifact_id));
                        continue;
                    }
                };
                let nd = crate::statements::nonce_digest(n);
                if let Some((other, _)) = grants.get(&nd) {
                    if other != &a.artifact_id {
                        shared.push(format!("{other} and {}", a.artifact_id));
                    }
                }
                grants.insert(nd, (a.artifact_id.clone(), max));
            }
        } else if let Some(n) = v.get("approvalNonce").and_then(|n| n.as_str()) {
            consumers
                .entry(crate::statements::nonce_digest(n))
                .or_default()
                .push(a.artifact_id.clone());
        }
    }
    // Grants carried in approvals/ (minted before the session) count exactly
    // like sealed approvals, by their signed scope; a grant that fails its
    // signature is a failure, not a warning.
    let (carried, bad_grants) = bundle_grants(pkg_dir, bundle);
    for g in carried {
        let Some(nd) = g.nonce_digest else { continue };
        if let Some((other, _)) = grants.get(&nd) {
            if other != &g.id {
                shared.push(format!("{other} and {}", g.id));
            }
            continue;
        }
        grants.insert(nd, (g.id, g.max));
    }
    if consumers.is_empty()
        && bundle.uses.is_empty()
        && bad_grants.is_empty()
        && shared.is_empty()
        && bad_scopes.is_empty()
    {
        return;
    }
    let mut problems = Vec::new();
    for pair in &shared {
        problems.push(format!("approvals {pair} share one nonce"));
    }
    for b in &bad_grants {
        problems.push(format!("carried grant {b}"));
    }
    problems.extend(bad_scopes);
    let mut unsigned = Vec::new();
    // Approvals whose signed scope sets no maxActions: nothing to count
    // against, and the pass text must not claim a limit was checked.
    let mut unbounded: Vec<String> = Vec::new();
    let nonces: BTreeSet<&String> = consumers
        .keys()
        .chain(bundle.uses.iter().map(|u| &u.nonce_digest))
        .collect();
    for nd in nonces {
        let acts = consumers.get(nd).map(Vec::len).unwrap_or(0);
        let use_ids: BTreeSet<&str> = bundle
            .uses
            .iter()
            .filter(|u| &u.nonce_digest == nd)
            .map(|u| u.use_id.as_str())
            .collect();
        let uses = bundle.uses.iter().filter(|u| &u.nonce_digest == nd).count();
        // A use record's own max_uses is unsigned; where the approval's
        // signed scope sets a limit, the record must say the same, or it
        // was edited (raised to hide a replay). An unbounded scope has
        // nothing for the record to agree with and is not held to it.
        if let Some((_, Some(signed))) = grants.get(nd) {
            let disagreeing: Vec<String> = bundle
                .uses
                .iter()
                .filter(|u| &u.nonce_digest == nd && u.max_uses != Some(*signed))
                .map(|u| {
                    format!(
                        "use {} records max_uses {} but the signed scope says {signed}",
                        u.use_id,
                        u.max_uses
                            .map(|m| m.to_string())
                            .unwrap_or_else(|| "none".into()),
                    )
                })
                .collect();
            problems.extend(disagreeing);
        }
        match grants.get(nd) {
            Some((grant, Some(max))) => {
                if acts as u32 > *max {
                    problems.push(format!(
                        "approval {grant} is signed for {max} use(s) but {acts} sealed action(s) consume it"
                    ));
                }
                if uses as u32 > *max {
                    problems.push(format!(
                        "approval {grant} is signed for {max} use(s) but the package records {uses} use(s)"
                    ));
                }
            }
            Some((grant, None)) => {
                if acts > 0 || uses > 0 {
                    unbounded.push(grant.clone());
                }
            }
            None if acts > 0 => unsigned.push(consumers[nd].join(", ")),
            None => {}
        }
        // A consuming action without its own use record is missing
        // evidence, not a broken signature or an exceeded limit; the
        // `approval_evidence` row already reports it, as a warning under
        // --structural, so it is not counted as a failure of the bytes here.
        if acts > use_ids.len() && !structural_only {
            problems.push(format!(
                "{acts} sealed action(s) consume one approval but only {} distinct use record(s) cover them",
                use_ids.len()
            ));
        }
    }
    if !problems.is_empty() {
        checks.push(VerifyCheck::fail(
            "approval-use-limit",
            &problems.join("; "),
        ));
    } else if !unsigned.is_empty() {
        checks.push(VerifyCheck::warn(
            "approval-use-limit",
            &format!(
                "action(s) {} consume an approval that is not sealed (signed) in this package, so its use limit cannot be checked here",
                unsigned.join("; ")
            ),
        ));
    } else if !unbounded.is_empty() {
        checks.push(VerifyCheck::pass(
            "approval-use-limit",
            &format!(
                "approval(s) {} are unbounded (no maxActions in the signed scope), so no use limit applies to them; every other approval is used within the limit its signed scope sets, each consuming action with its own use record",
                unbounded.join(", ")
            ),
        ));
    } else {
        checks.push(VerifyCheck::pass(
            "approval-use-limit",
            "every approval is used within the limit its signed scope sets, each consuming action with its own use record",
        ));
    }
}

/// Tail of `verify_package`: emit leaf_count and timeline-order checks.
/// Used by the early-return path when an unknown merkle version aborts
/// Merkle recomputation — those two checks are independent of the tree
/// version and still meaningful to surface.
/// Which trust-root kinds mean "I accept receipts signed by this key".
const SIGNER_KINDS: &[crate::trust::TrustRootKind] = &[
    crate::trust::TrustRootKind::CertIssuer,
    crate::trust::TrustRootKind::AgentCert,
    crate::trust::TrustRootKind::SessionHost,
];

fn read_package_keys(pkg_dir: &Path) -> Option<PackageKeys> {
    let raw = std::fs::read(pkg_dir.join(KEYS_FILE)).ok()?;
    serde_json::from_slice(&raw).ok()
}

/// Decode the keys the package names, by key id. Empty when `keys.json` is
/// missing or unreadable; the callers report that themselves.
fn package_verifying_keys(
    pkg_dir: &Path,
) -> std::collections::BTreeMap<String, ed25519_dalek::VerifyingKey> {
    let mut keys = std::collections::BTreeMap::new();
    if let Some(pk) = read_package_keys(pkg_dir) {
        for (id, encoded) in pk.keys {
            if let Ok(vk) = crate::trust::decode_ed25519_pubkey(&encoded) {
                keys.insert(id, vk);
            }
        }
    }
    keys
}

/// The close record binds the sealed set: `session close` signs the SHA-256
/// of `receipt.json` into a `session.v1` record after the package is built,
/// and the package carries that envelope as `record.json`. Rewriting the
/// artifact list and recomputing the tree leaves every per-artifact row green
/// (the auditor's AUD-34 splice: an artifact from another session, same key,
/// dropped into an `unchained` slot). This row catches it: the receipt's
/// digest no longer matches what the producer signed at close. A package
/// without a record FAILs: nothing signed says whether it predates 0.31.4 or
/// had its record removed (CLI-4); under `--structural` it is a WARN. The
/// record must be a `session.v1` receipt statement, and its signer is
/// returned so `signer_trust` judges it with the artifact signers: a record
/// forged under a key added to keys.json cannot reach `verified`. The
/// producer's own key still says nothing about a producer who re-signs,
/// which is what anchoring is for.
fn verify_receipt_binding(
    pkg_dir: &Path,
    receipt: &SessionReceipt,
    structural_only: bool,
    sealed: &SealedSet,
    checks: &mut Vec<VerifyCheck>,
) -> (bool, Option<Vouched>) {
    use sha2::{Digest, Sha256};
    let fail = |checks: &mut Vec<VerifyCheck>, detail: String| {
        checks.push(VerifyCheck::fail("receipt_binding", &detail));
        (false, None)
    };
    let path = pkg_dir.join(RECORD_FILE);
    let raw = match std::fs::read(&path) {
        Ok(b) => b,
        Err(_) => {
            // Nothing in a package says, under a signature, which release
            // built it, so "built before 0.31.4" cannot be told apart from
            // "record.json deleted" (CLI-4): deleting it, then splicing in
            // another session's artifacts or editing the receipt, passed by
            // default. Without a record nothing signed covers the sealed set,
            // so the row fails whatever else the package carries; reading a
            // package as structure is the reader's explicit choice
            // (--structural, verdict structural-pass).
            let detail = "the package carries no close record, so the sealed set is not under a signature: an artifact could be added to the list, or the receipt edited, and the tree recomputed without any per-artifact row failing. Either it was built before 0.31.4, or record.json was removed; the bytes cannot say which";
            if structural_only {
                checks.push(VerifyCheck::warn("receipt_binding", detail));
                return (false, None);
            }
            return fail(checks, format!("{detail}. For a package you know was built before 0.31.4, --structural reports what can still be checked (verdict structural-pass)"));
        }
    };
    if structural_only {
        checks.push(VerifyCheck::warn(
            "receipt_binding",
            "close record present but not checked under --structural",
        ));
        return (false, None);
    }
    let envelope = match crate::attestation::Envelope::from_json(&raw) {
        Ok(e) => e,
        Err(e) => {
            return fail(
                checks,
                format!("record.json does not parse as a DSSE envelope: {e}"),
            )
        }
    };
    // The close record is a `treeship/receipt/v1` statement of kind
    // `session.v1`; any other signed statement that happens to carry a
    // `receipt_digest` field is not one.
    let record_pt = crate::statements::payload_type("receipt");
    if envelope.payload_type != record_pt {
        return fail(
            checks,
            format!(
                "record.json is a {} envelope, not a close record ({record_pt})",
                envelope.payload_type
            ),
        );
    }
    let Some(sig) = envelope.signatures.first() else {
        return fail(checks, "record.json carries no signature".into());
    };
    let keys = package_verifying_keys(pkg_dir);
    let Some(vk) = keys.get(&sig.keyid) else {
        return fail(
            checks,
            format!(
                "record.json is signed by {}, a key the package does not carry",
                sig.keyid
            ),
        );
    };
    if let Err(e) = crate::attestation::verify_with_key(&envelope, &sig.keyid, *vk) {
        return fail(
            checks,
            format!("record.json signature invalid for key {}: {e}", sig.keyid),
        );
    }
    let statement: serde_json::Value = match envelope
        .payload_bytes()
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
    {
        Some(v) => v,
        None => return fail(checks, "record.json payload is not JSON".into()),
    };
    let s_type = statement.get("type").and_then(|t| t.as_str());
    let s_kind = statement.get("kind").and_then(|k| k.as_str());
    if s_type != Some(crate::statements::TYPE_RECEIPT) || s_kind != Some("session.v1") {
        return fail(
            checks,
            format!(
                "record.json is a {} statement of kind {}, not a session.v1 close record",
                s_type.unwrap_or("(untyped)"),
                s_kind.unwrap_or("(none)")
            ),
        );
    }
    let body = statement.get("payload");
    let (Some(signed_digest), Some(signed_session)) = (
        body.and_then(|p| p.get("receipt_digest"))
            .and_then(|d| d.as_str()),
        body.and_then(|p| p.get("session_id"))
            .and_then(|d| d.as_str()),
    ) else {
        return fail(
            checks,
            "the close record does not name a receipt_digest and a session_id".into(),
        );
    };
    let receipt_bytes = match std::fs::read(pkg_dir.join(RECEIPT_FILE)) {
        Ok(b) => b,
        Err(e) => return fail(checks, format!("receipt.json unreadable: {e}")),
    };
    let actual = format!("sha256:{}", hex::encode(Sha256::digest(&receipt_bytes)));
    if signed_session != receipt.session.id {
        return fail(
            checks,
            format!(
                "the close record names session {} but this receipt is {}",
                signed_session, receipt.session.id
            ),
        );
    }
    if signed_digest != actual {
        return fail(
            checks,
            format!(
                "the producer signed receipt digest {} at close but receipt.json now digests to {}: the sealed set was rewritten after it was signed",
                signed_digest, actual
            ),
        );
    }
    // The record is bound to the session, not to the reader's trust store:
    // any key the reader pinned for some other reason must not be able to
    // re-sign this session's receipt. The record names, as its signed
    // subject, the sealed `session.close` action; that close must name this
    // session; and the record's signer must be the close's signer or the key
    // the signed close names as its record key (an agent with its own key).
    let Some(subject) = statement
        .get("subject")
        .and_then(|s| s.get("artifactId"))
        .and_then(|a| a.as_str())
    else {
        return fail(
            checks,
            "the close record names no subject: it must name the sealed session.close action"
                .into(),
        );
    };
    // Exactly one close for this session, chained, and signed by the key
    // that signed the chain's root session.start (whose place is bound by the
    // producer's next artifact signing it as parent). Otherwise a key the
    // reader pinned could append its own close for this session and name it.
    let session_id_of = |c: &SealedClose| {
        c.statement
            .get("meta")
            .and_then(|m| m.get("session_id"))
            .and_then(|v| v.as_str())
            .map(str::to_string)
    };
    let session_closes: Vec<&SealedClose> = sealed
        .closes
        .iter()
        .filter(|c| session_id_of(c).as_deref() == Some(receipt.session.id.as_str()))
        .collect();
    if session_closes.len() > 1 {
        return fail(
            checks,
            format!(
                "the package seals {} session.close actions for session {}: {}",
                session_closes.len(),
                receipt.session.id,
                session_closes
                    .iter()
                    .map(|c| c.id.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        );
    }
    let Some(close) = sealed.closes.iter().find(|c| c.id == subject) else {
        return fail(
            checks,
            format!("the close record names {subject}, which is not a sealed, verified session.close action in this package"),
        );
    };
    let meta = close.statement.get("meta");
    if meta
        .and_then(|m| m.get("session_id"))
        .and_then(|v| v.as_str())
        != Some(receipt.session.id.as_str())
    {
        return fail(
            checks,
            format!(
                "the session.close {subject} the record names does not close session {}",
                receipt.session.id
            ),
        );
    }
    if !close.chained {
        return fail(
            checks,
            format!("session.close {subject} is sealed unchained; the close must be on the session's chain"),
        );
    }
    let root_id = receipt
        .artifacts
        .iter()
        .find(|a| !a.unchained)
        .map(|a| a.artifact_id.as_str());
    let root = root_id
        .and_then(|r| sealed.starts.iter().find(|s| s.id == r))
        .filter(|s| session_id_of(s).as_deref() == Some(receipt.session.id.as_str()));
    let Some(root) = root else {
        return fail(
            checks,
            format!(
                "the chain's first artifact ({}) is not a verified session.start for session {}",
                root_id.unwrap_or("none"),
                receipt.session.id
            ),
        );
    };
    if root.keyid != close.keyid {
        return fail(
            checks,
            format!(
                "session.close {subject} is signed by {}, but the session.start that roots the chain ({}) is signed by {}: the close is not the producer's",
                close.keyid, root.id, root.keyid
            ),
        );
    }
    let vouched = if sig.keyid == close.keyid {
        None
    } else {
        let named = meta.and_then(|m| m.get("record_key"));
        let named_id = named.and_then(|k| k.get("key_id")).and_then(|v| v.as_str());
        let named_pub = named
            .and_then(|k| k.get("public_key"))
            .and_then(|v| v.as_str())
            .and_then(|p| crate::trust::decode_ed25519_pubkey(p).ok());
        if named_id != Some(sig.keyid.as_str()) || named_pub.as_ref() != Some(vk) {
            return fail(
                checks,
                format!(
                    "record.json is signed by {}, which is neither the signer of session.close {subject} ({}) nor the record key that signed session.close names. A package closed before 0.31.10 by an agent with its own key names none; read it with --structural",
                    sig.keyid, close.keyid
                ),
            );
        }
        Some(Vouched {
            key: sig.keyid.clone(),
            by: close.keyid.clone(),
        })
    };
    let how = match &vouched {
        None => format!("the signer of session.close {subject}"),
        Some(v) => format!(
            "the record key session.close {subject} names, signed by {}",
            v.by
        ),
    };
    checks.push(VerifyCheck::pass(
        "receipt_binding",
        &format!(
            "close record signed by {} (fp {}; {how}) binds receipt.json ({}) and names this session",
            sig.keyid,
            key_fingerprint(vk),
            actual
        ),
    ));
    (true, vouched)
}

/// A key the package authenticates through its own signed structure: named
/// as the record key inside a `session.close` signed by `by`.
struct Vouched {
    key: String,
    by: String,
}

/// Every sealed artifact's signed timestamp should fall inside the session's
/// own window. Clocks skew and a producer controls its own clock, so this is
/// a warning that names the artifacts, not a proof; an artifact minutes after
/// `ended_at` is the shape a spliced one has.
fn verify_session_window(pkg_dir: &Path, receipt: &SessionReceipt, checks: &mut Vec<VerifyCheck>) {
    use crate::statements::invitation::parse_rfc3339_to_unix;
    const SKEW: u64 = 120;
    let Some(started) = parse_rfc3339_to_unix(&receipt.session.started_at) else {
        return;
    };
    let ended = receipt
        .session
        .ended_at
        .as_deref()
        .and_then(parse_rfc3339_to_unix);
    let art_dir = pkg_dir.join(ARTIFACTS_DIR);
    let mut outside: Vec<String> = Vec::new();
    let mut seen = 0usize;
    for entry in &receipt.artifacts {
        let path = art_dir.join(format!("{}.json", sanitize_filename(&entry.artifact_id)));
        let Ok(raw) = std::fs::read(&path) else {
            continue;
        };
        let Ok(env) = crate::attestation::Envelope::from_json(&raw) else {
            continue;
        };
        let Some(ts) = env
            .payload_bytes()
            .ok()
            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
            .and_then(|v| {
                v.get("timestamp")
                    .and_then(|t| t.as_str())
                    .map(str::to_string)
            })
        else {
            continue;
        };
        let Some(t) = parse_rfc3339_to_unix(&ts) else {
            continue;
        };
        seen += 1;
        let before = t + SKEW < started;
        let after = ended.map(|e| t > e + SKEW).unwrap_or(false);
        if before || after {
            outside.push(format!("{} ({})", entry.artifact_id, ts));
        }
    }
    if seen == 0 {
        return;
    }
    if outside.is_empty() {
        checks.push(VerifyCheck::pass(
            "session_window",
            &format!("{seen} sealed artifact(s) were signed inside the session's window"),
        ));
    } else {
        checks.push(VerifyCheck::warn(
            "session_window",
            &format!(
                "{} sealed artifact(s) were signed outside the session's window ({} to {}): {}",
                outside.len(),
                receipt.session.started_at,
                receipt
                    .session
                    .ended_at
                    .clone()
                    .unwrap_or_else(|| "open".into()),
                outside.join(", ")
            ),
        ));
    }
}

/// For every sealed artifact: the envelope is in the package, its id
/// re-derives from the signed bytes, its Ed25519 signature verifies against
/// the key the package names, and each chained entry names the previous
/// sealed entry as its parent. Then, separately, whether the signing keys
/// are pinned trust roots.
///
/// A package with no envelopes at all (pre-0.31.2 layout) gets one `envelopes`
/// FAIL, or a WARN under `structural_only`: structure without signatures is
/// not verification, and a forged sealed set is indistinguishable from an
/// honest legacy one from the package's bytes alone.
/// The `anchoring` row: every stapled Rekor proof is checked offline against
/// the reader's trusted logs and bound to its sealed artifact (TS-2026-003).
///
/// No row at all when the package carries no `anchors/` directory, which is
/// every package built before this existed and every session never pushed:
/// absence changes no existing verdict. When proofs are present:
/// * a proof that fails, or is for another artifact, is a failure -- the
///   package is presenting a witness that does not hold;
/// * a proof from a log this reader has not pinned is a warning naming it;
/// * otherwise a pass that says how many sealed artifacts are witnessed and
///   over what span of Rekor time.
fn verify_stapled_anchors(
    pkg_dir: &Path,
    receipt: &SessionReceipt,
    trust: &crate::trust::TrustRootStore,
    checks: &mut Vec<VerifyCheck>,
) {
    use crate::verify::rekor::{verify_rekor_entry, RekorVerifyError};

    let dir = pkg_dir.join(ANCHORS_DIR);
    if !dir.is_dir() {
        return;
    }
    let logs = crate::trust::transparency_logs(trust);
    let art_dir = pkg_dir.join(ARTIFACTS_DIR);
    let sealed: std::collections::BTreeSet<&str> = receipt
        .artifacts
        .iter()
        .map(|a| a.artifact_id.as_str())
        .collect();

    let mut verified: Vec<i64> = Vec::new();
    let mut witnessed_artifacts = 0usize;
    let mut bad: Vec<String> = Vec::new();
    let mut untrusted_logs: std::collections::BTreeSet<String> = Default::default();
    let mut unsealed: Vec<String> = Vec::new();

    let Ok(entries) = std::fs::read_dir(&dir) else {
        checks.push(VerifyCheck::fail(
            "anchoring",
            "anchors/ exists but cannot be read",
        ));
        return;
    };
    let mut files: Vec<_> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
    files.sort();
    for path in files {
        let Some(id) = path
            .file_stem()
            .and_then(|s| s.to_str())
            .map(str::to_string)
        else {
            continue;
        };
        if !sealed.contains(id.as_str()) {
            unsealed.push(id);
            continue;
        }
        let parsed = std::fs::read(&path)
            .ok()
            .and_then(|b| serde_json::from_slice::<Vec<crate::storage::RecordAnchor>>(&b).ok());
        let Some(anchors) = parsed else {
            bad.push(format!("{id}: anchors file is not a list of anchors"));
            continue;
        };
        let env = std::fs::read(art_dir.join(format!("{}.json", sanitize_filename(&id))))
            .ok()
            .and_then(|b| crate::attestation::Envelope::from_json(&b).ok());
        let Some(env) = env else {
            bad.push(format!(
                "{id}: no signed envelope in the package to bind the proof to"
            ));
            continue;
        };
        let mut any = false;
        for a in anchors.iter().filter(|a| a.mechanism == "rekor") {
            let Some(proof) = &a.proof else { continue };
            match verify_rekor_entry(proof, &env, &logs) {
                Ok(v) => {
                    verified.push(v.integrated_time);
                    any = true;
                }
                Err(RekorVerifyError::UnknownLog(log_id)) => {
                    untrusted_logs.insert(log_id);
                }
                Err(e) => bad.push(format!("{id}: {e}")),
            }
        }
        if any {
            witnessed_artifacts += 1;
        }
    }

    if !bad.is_empty() {
        checks.push(VerifyCheck::fail(
            "anchoring",
            &format!(
                "{} stapled proof(s) do not hold: {}",
                bad.len(),
                bad.join("; ")
            ),
        ));
        return;
    }
    if !untrusted_logs.is_empty() {
        checks.push(VerifyCheck::warn(
            "anchoring",
            &format!(
                "proofs come from a transparency log this machine does not trust (logID {}); pin it with `treeship trust add <label> @<log key>.pem --kind transparency_log` if you mean to",
                untrusted_logs.into_iter().collect::<Vec<_>>().join(", ")
            ),
        ));
        return;
    }
    if verified.is_empty() {
        checks.push(VerifyCheck::warn(
            "anchoring",
            "anchors/ is present but carries no Rekor proof",
        ));
        return;
    }
    let first = verified.iter().min().copied().unwrap_or_default();
    let last = verified.iter().max().copied().unwrap_or_default();
    let mut detail = format!(
        "{witnessed_artifacts} of {} sealed artifact(s) carry a Rekor entry that verifies offline (Rekor time {} to {}); the rest rest on the signer's clock",
        sealed.len(),
        crate::statements::unix_to_rfc3339(first.max(0) as u64),
        crate::statements::unix_to_rfc3339(last.max(0) as u64),
    );
    if !unsealed.is_empty() {
        detail.push_str(&format!(
            "; ignored proofs for artifacts not in the sealed set: {}",
            unsealed.join(", ")
        ));
    }
    checks.push(VerifyCheck::pass("anchoring", &detail));
}

/// The short fingerprint `treeship trust` shows for a key.
fn key_fingerprint(vk: &ed25519_dalek::VerifyingKey) -> String {
    crate::statements::invitation::pubkey_fingerprint_short(&crate::trust::encode_ed25519_pubkey(
        vk,
    ))
}

/// How a trusted key is trusted here: the pinned root it matched, by label,
/// kind and fingerprint, never just the package's key id (a key id is only a
/// label the signer picked).
fn describe_trusted(
    kid: &str,
    vk: &ed25519_dalek::VerifyingKey,
    trust: &crate::trust::TrustRootStore,
) -> String {
    let fp = key_fingerprint(vk);
    let root = trust.roots().iter().find(|r| {
        SIGNER_KINDS.contains(&r.kind)
            && crate::trust::decode_ed25519_pubkey(&r.public_key)
                .map(|k| k.to_bytes() == vk.to_bytes())
                .unwrap_or(false)
    });
    match root {
        Some(r) if r.label == OWN_KEY_LABEL => format!("{kid} (this ship's own, fp {fp})"),
        Some(r) => format!(
            "{kid} (pinned as {:?}, {}, fp {fp})",
            r.label,
            r.kind.as_str()
        ),
        None => format!("{kid} (fp {fp})"),
    }
}

/// `key_id_collision`: a key id in this package names a different public key
/// than the root pinned here under that same id. Key ids are labels; a
/// forger who re-signs a victim's chain under their own key can reuse the
/// victim's id, and the package then reads as the victim's. FAIL, naming
/// both fingerprints.
/// Package key ids that a pinned root names with a different public key.
/// Trust hints never offer to pin one of these: pinning the package's key
/// under that id is exactly the re-point a forger wants.
fn colliding_key_ids(
    pkg_dir: &Path,
    trust: &crate::trust::TrustRootStore,
) -> std::collections::BTreeSet<String> {
    package_verifying_keys(pkg_dir)
        .into_iter()
        .filter(|(kid, vk)| {
            trust.roots().iter().any(|r| {
                &r.key_id == kid
                    && SIGNER_KINDS.contains(&r.kind)
                    && crate::trust::decode_ed25519_pubkey(&r.public_key)
                        .map(|p| p.to_bytes() != vk.to_bytes())
                        .unwrap_or(false)
            })
        })
        .map(|(kid, _)| kid)
        .collect()
}

fn push_key_id_collisions(
    pkg_dir: &Path,
    trust: &crate::trust::TrustRootStore,
    checks: &mut Vec<VerifyCheck>,
) {
    let keys = package_verifying_keys(pkg_dir);
    let mut clashes = Vec::new();
    for (kid, vk) in &keys {
        for r in trust.roots() {
            if &r.key_id != kid || !SIGNER_KINDS.contains(&r.kind) {
                continue;
            }
            let Ok(pinned) = crate::trust::decode_ed25519_pubkey(&r.public_key) else {
                continue;
            };
            if pinned.to_bytes() != vk.to_bytes() {
                clashes.push(format!(
                    "{kid}: the package's key has fp {}, the root pinned here as {kid} ({:?}) has fp {}",
                    key_fingerprint(vk),
                    r.label,
                    key_fingerprint(&pinned)
                ));
            }
        }
    }
    if !clashes.is_empty() {
        checks.push(VerifyCheck::fail(
            "key_id_collision",
            &format!(
                "a key id in this package names a different public key than the root pinned here under that id, so the package would read as someone else's: {}",
                clashes.join("; ")
            ),
        ));
    }
}

/// `approval_evidence`: every sealed action that consumes an approval has
/// its use record in the package's `approvals/` bundle. The close record
/// digests receipt.json only, so deleting `approvals/` used to hide the
/// approval-use and replay rows (and any failure among them) while the
/// package still verified.
fn push_approval_evidence(
    pkg_dir: &Path,
    receipt: &SessionReceipt,
    structural_only: bool,
    checks: &mut Vec<VerifyCheck>,
) {
    // (action id, digest of its signed approvalNonce)
    let consuming: Vec<(&str, String)> = receipt
        .artifacts
        .iter()
        .filter_map(|a| {
            let nonce = std::fs::read(
                pkg_dir
                    .join(ARTIFACTS_DIR)
                    .join(format!("{}.json", sanitize_filename(&a.artifact_id))),
            )
            .ok()
            .and_then(|raw| crate::attestation::Envelope::from_json(&raw).ok())
            .and_then(|env| env.payload_bytes().ok())
            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
            .and_then(|v| {
                v.get("approvalNonce")
                    .and_then(|n| n.as_str())
                    .map(str::to_string)
            })?;
            Some((
                a.artifact_id.as_str(),
                crate::statements::nonce_digest(&nonce),
            ))
        })
        .collect();
    if consuming.is_empty() {
        return;
    }
    let bundle = read_approvals_bundle(pkg_dir).unwrap_or_default();
    // A use record covers an action by the digest of the nonce it consumed
    // (the record is reserved before the action exists, so it may not name
    // the action's id).
    let covered: std::collections::BTreeSet<&str> = bundle
        .uses
        .iter()
        .map(|u| u.nonce_digest.as_str())
        .collect();
    let missing: Vec<&str> = consuming
        .iter()
        .filter(|(_, d)| !covered.contains(d.as_str()))
        .map(|(id, _)| *id)
        .collect();
    if missing.is_empty() {
        checks.push(VerifyCheck::pass(
            "approval_evidence",
            &format!(
                "{} approval-consuming action(s), each with its use record in approvals/",
                consuming.len()
            ),
        ));
    } else {
        let detail = format!(
            "{} sealed action(s) consume an approval but the package carries no use record for them in approvals/ ({}): the approval-use and replay checks cannot run",
            missing.len(),
            missing.join(", ")
        );
        checks.push(if structural_only {
            VerifyCheck::warn("approval_evidence", &detail)
        } else {
            VerifyCheck::fail("approval_evidence", &detail)
        });
    }
}

/// `chain_completeness`: sealed artifacts that are not on the chain. One
/// that a signed reference inside the sealed set accounts for is bound (W1-13,
/// CLI-18): an approval whose nonce a chained action consumes in its signed
/// `approvalNonce`; a participant whose row passed (bound to a sealed
/// invitation and countersigned by its issuer); the invitation such a
/// participant redeems. The referencing signer must be authenticated here
/// (pinned, own, or vouched by the session.close), so an attacker's own
/// signed action cannot vouch for a smuggled approval. Package order stays
/// unproven either way, and the row says so. Unbound ones WARN (`--strict`
/// fails them).
fn push_chain_completeness(
    receipt: &SessionReceipt,
    sealed: &SealedSet,
    authenticated: &std::collections::BTreeSet<String>,
    checks: &mut Vec<VerifyCheck>,
) {
    let unchained: Vec<&str> = receipt
        .artifacts
        .iter()
        .filter(|a| a.unchained)
        .map(|a| a.artifact_id.as_str())
        .collect();
    if unchained.is_empty() {
        return;
    }
    let consumed_by_trusted = |nonce: &str| {
        sealed
            .consumers
            .iter()
            .any(|(n, k)| n == nonce && authenticated.contains(k))
    };
    let bound = |id: &str| -> Option<&'static str> {
        if sealed
            .approvals
            .iter()
            .any(|(a, n)| a == id && consumed_by_trusted(n))
        {
            return Some("approval nonce");
        }
        if sealed
            .participants
            .iter()
            .any(|(p, _, host)| p == id && authenticated.contains(host))
        {
            return Some("countersigned participant");
        }
        if sealed
            .participants
            .iter()
            .any(|(_, inv, host)| inv == id && authenticated.contains(host))
        {
            return Some("redeemed invitation");
        }
        // The host's signed record that a bound participant answered its
        // live challenge, for this session.
        if sealed.liveness.iter().any(|(l, part, sess, k)| {
            l == id
                && sess == &receipt.session.id
                && authenticated.contains(k)
                && sealed
                    .participants
                    .iter()
                    .any(|(p, _, host)| p == part && authenticated.contains(host))
        }) {
            return Some("participant liveness");
        }
        None
    };
    let (bound_ids, loose): (Vec<&str>, Vec<&str>) =
        unchained.iter().partition(|id| bound(id).is_some());
    let order =
        "their position relative to the chain is the signer's claim only (package order unproven)";
    if loose.is_empty() {
        let how: std::collections::BTreeSet<&str> =
            bound_ids.iter().filter_map(|id| bound(id)).collect();
        checks.push(VerifyCheck::pass(
            "chain_completeness",
            &format!(
                "{} sealed artifact(s) are not chained but are bound by signed references from authenticated signers ({}): {}; {order}",
                bound_ids.len(),
                how.into_iter().collect::<Vec<_>>().join(", "),
                bound_ids.join(", ")
            ),
        ));
    } else {
        let also = if bound_ids.is_empty() {
            String::new()
        } else {
            format!(
                "; {} more are bound by signed references ({})",
                bound_ids.len(),
                bound_ids.join(", ")
            )
        };
        checks.push(VerifyCheck::warn(
            "chain_completeness",
            &format!(
                "{} sealed artifact(s) were signed during the session but never chained onto it, and nothing an authenticated signer signed accounts for them ({}); signed and sealed, but {order}{also}",
                loose.len(),
                loose.join(", ")
            ),
        ));
    }
}

/// `approval_signer`: the keys that signed sealed approvals. Pinned or this
/// ship's own: PASS. Otherwise WARN naming the pin (`--strict` fails it, and
/// [`package_verdict`] caps the verdict at `SignaturesPass`). A bad approval
/// signature fails its own `signature:` row, as for any artifact.
fn push_approval_signer(
    pkg_dir: &Path,
    approvers: &std::collections::BTreeSet<String>,
    trust: &crate::trust::TrustRootStore,
    checks: &mut Vec<VerifyCheck>,
) {
    if approvers.is_empty() {
        return;
    }
    let keys = package_verifying_keys(pkg_dir);
    let unpinned: Vec<&str> = approvers
        .iter()
        .map(String::as_str)
        .filter(|k| {
            keys.get(*k)
                .is_none_or(|vk| !SIGNER_KINDS.iter().any(|kind| trust.contains(vk, *kind)))
        })
        .collect();
    if unpinned.is_empty() {
        checks.push(VerifyCheck::pass(
            "approval_signer",
            &format!(
                "every approval is signed by a pinned key or this ship's own ({})",
                approvers.iter().cloned().collect::<Vec<_>>().join(", ")
            ),
        ));
        return;
    }
    let colliding = colliding_key_ids(pkg_dir, trust);
    let pins: Vec<String> = unpinned
        .iter()
        .filter(|k| !colliding.contains(**k))
        .filter_map(|k| {
            let vk = keys.get(*k)?;
            Some(format!(
                "treeship trust add {k} {} --kind cert_issuer  (fp {})",
                crate::trust::encode_ed25519_pubkey(vk),
                key_fingerprint(vk)
            ))
        })
        .collect();
    checks.push(VerifyCheck::warn(
        "approval_signer",
        &format!(
            "approval(s) signed by {} verify, but the approver key is not pinned here: an action consuming the approval is no more authorized than the approver is trusted. Pin it if you trust the approver: {}",
            unpinned.join(", "),
            pins.join("; ")
        ),
    ));
}

/// `signer_trust`: are the keys whose signatures verified trusted here?
///
/// A key is trusted when it is pinned (or this ship's own), and
/// authenticated when it is trusted or is the record key a trusted signer
/// named inside the sealed `session.close` ([`Vouched`]). All authenticated:
/// PASS. None trusted: WARN (the reader has decided nothing; `--strict`
/// fails). Some trusted and some not: FAIL -- a package the reader trusts
/// must not carry an artifact signed by a key nobody vouched for, which is
/// the shape of an injected artifact. No signer, no row; [`package_verdict`]
/// then cannot say `verified`.
fn push_signer_trust(
    pkg_dir: &Path,
    signers: &std::collections::BTreeSet<String>,
    vouched: Option<&Vouched>,
    trust: &crate::trust::TrustRootStore,
    checks: &mut Vec<VerifyCheck>,
) -> std::collections::BTreeSet<String> {
    if signers.is_empty() {
        return Default::default();
    }
    let keys = package_verifying_keys(pkg_dir);
    // A signer whose key cannot be looked up is not trusted.
    let trusted = |k: &str| {
        keys.get(k)
            .is_some_and(|vk| SIGNER_KINDS.iter().any(|kind| trust.contains(vk, *kind)))
    };
    let authenticated =
        |k: &str| trusted(k) || vouched.is_some_and(|v| v.key == k && trusted(&v.by));
    let unauthenticated: Vec<&str> = signers
        .iter()
        .map(String::as_str)
        .filter(|k| !authenticated(k))
        .collect();
    let trusted_keys: Vec<&str> = signers
        .iter()
        .map(String::as_str)
        .filter(|k| trusted(k))
        .collect();
    let colliding = colliding_key_ids(pkg_dir, trust);
    let pins = |ks: &[&str]| -> String {
        ks.iter()
            .filter(|k| !colliding.contains(**k))
            .filter_map(|k| {
                let vk = keys.get(*k)?;
                // No `--yes`: the key comes from the package itself, so
                // the reader confirms it (fingerprint shown) before pinning.
                Some(format!(
                    "treeship trust add {k} {} --kind cert_issuer  (fp {})",
                    crate::trust::encode_ed25519_pubkey(vk),
                    key_fingerprint(vk)
                ))
            })
            .collect::<Vec<_>>()
            .join("; ")
    };
    if unauthenticated.is_empty() {
        // The CLI adds this ship's own keys as roots so a package verifies
        // where it was produced; say so, because "pinned" reads as a third
        // party's decision and this is not one.
        let own: Vec<&str> = signers
            .iter()
            .filter(|k| {
                trust
                    .roots()
                    .iter()
                    .any(|r| &r.key_id == *k && r.label == OWN_KEY_LABEL)
            })
            .map(|k| k.as_str())
            .collect();
        let mut detail = if own.len() == signers.len() {
            format!(
                "all {} signing key(s) are this ship's own ({}); a stranger pins them before this row passes on their machine",
                signers.len(),
                own.join(", ")
            )
        } else if own.is_empty() {
            format!(
                "all {} signing key(s) are pinned trust roots",
                signers.len()
            )
        } else {
            format!(
                "{} signing key(s): {} pinned trust root(s), {} this ship's own ({})",
                signers.len(),
                signers.len() - own.len(),
                own.len(),
                own.join(", ")
            )
        };
        let matched: Vec<String> = signers
            .iter()
            .filter(|k| trusted(k))
            .filter_map(|k| keys.get(k).map(|vk| describe_trusted(k, vk, trust)))
            .collect();
        if !matched.is_empty() {
            detail.push_str(&format!("; matched: {}", matched.join(", ")));
        }
        if let Some(v) = vouched.filter(|v| !trusted(&v.key)) {
            detail.push_str(&format!(
                "; {} is not pinned but is the record key the session.close signed by {} names",
                v.key, v.by
            ));
        }
        checks.push(VerifyCheck::pass("signer_trust", &detail));
    } else if trusted_keys.is_empty() {
        checks.push(VerifyCheck::warn(
            "signer_trust",
            &format!(
                "signature(s) verify for the key(s) the package names, but none of them is a pinned trust root here: {}. Pin what you have decided to trust: {}",
                unauthenticated.join(", "),
                pins(&unauthenticated)
            ),
        ));
    } else {
        checks.push(VerifyCheck::fail(
            "signer_trust",
            &format!(
                "{} is pinned here, but {} also signed sealed artifacts and is neither pinned nor the record key a trusted session.close names: an artifact signed by a key nobody vouched for sits in a package you trust. If you have decided to trust it: {}",
                trusted_keys.join(", "),
                unauthenticated.join(", "),
                pins(&unauthenticated)
            ),
        ));
    }
    signers
        .iter()
        .filter(|k| authenticated(k))
        .cloned()
        .collect()
}

/// What the per-artifact pass established: the keys whose signatures
/// verified, and every verified `session.close` action (the statement the
/// close record must name).
#[derive(Default)]
struct SealedSet {
    signers: std::collections::BTreeSet<String>,
    /// Keys whose approval envelopes verified. Judged in their own
    /// `approval_signer` row, not in the mixed-signer check: an approver is
    /// often not the producer (a human's key on another ship).
    approval_signers: std::collections::BTreeSet<String>,
    /// Verified `session.close` actions.
    closes: Vec<SealedClose>,
    /// Verified `session.start` actions.
    starts: Vec<SealedClose>,
    /// Verified approval envelopes: (artifact id, signed nonce).
    approvals: Vec<(String, String)>,
    /// Verified, chained actions that consume an approval: (signed
    /// approvalNonce, signer key id).
    consumers: Vec<(String, String)>,
    /// Participants whose row passed: (artifact id, invitation_ref, host key
    /// id).
    participants: Vec<(String, String, String)>,
    /// Verified `session-liveness` records: (artifact id, participant_ref,
    /// session_ref, signer key id).
    liveness: Vec<(String, String, String, String)>,
}

/// A sealed `session.start` / `session.close` action whose signature, id and
/// digest verified.
struct SealedClose {
    id: String,
    keyid: String,
    chained: bool,
    statement: serde_json::Value,
}

/// A sealed participant, verified against the invitation it redeems (CLI-3).
/// The invitation must be sealed in this same package and signed by a key the
/// package carries; that key must be the invitation's issuer. Returns the
/// issuer's key id (for the signer-trust row) and the PASS detail.
fn verify_sealed_participant(
    art_dir: &Path,
    receipt: &SessionReceipt,
    entry: &ArtifactEntry,
    envelope: &crate::attestation::Envelope,
    keys: &std::collections::BTreeMap<String, ed25519_dalek::VerifyingKey>,
) -> Result<SealedParticipant, String> {
    use crate::statements::invitation::InvitationStatement;
    use crate::statements::session_participant::{
        verify_participant_artifact, SessionParticipantStatement,
    };
    let stmt: SessionParticipantStatement = envelope
        .unmarshal_statement()
        .map_err(|e| format!("participant payload invalid: {e}"))?;
    let inv_id = &stmt.invitation_ref;
    if !receipt.artifacts.iter().any(|a| &a.artifact_id == inv_id) {
        return Err(format!(
            "participant redeems invitation {inv_id}, which is not sealed in this package"
        ));
    }
    let raw = std::fs::read(art_dir.join(format!("{}.json", sanitize_filename(inv_id)))).map_err(
        |_| format!("invitation {inv_id} is sealed but its envelope is not in the package"),
    )?;
    let invitation = crate::attestation::Envelope::from_json(&raw)
        .map_err(|e| format!("invitation {inv_id} envelope does not parse: {e}"))?;
    let inv_keyid = invitation
        .signatures
        .first()
        .map(|s| s.keyid.clone())
        .ok_or_else(|| format!("invitation {inv_id} carries no signature"))?;
    let inv_key = keys.get(&inv_keyid).ok_or_else(|| {
        format!("invitation {inv_id} is signed by {inv_keyid}, a key the package does not carry")
    })?;
    verify_participant_artifact(
        envelope,
        &entry.artifact_id,
        &invitation,
        *inv_key,
        &receipt.session.id,
    )
    .map_err(|e| e.to_string())?;
    if let Some(listed) = entry.digest.as_deref() {
        use sha2::{Digest, Sha256};
        let bytes = envelope
            .to_json()
            .map_err(|e| format!("participant envelope encoding failed: {e}"))?;
        let actual = format!("sha256:{}", hex::encode(Sha256::digest(bytes)));
        if listed != actual {
            return Err(format!(
                "receipt lists digest {listed} but the countersigned envelope digests to {actual}"
            ));
        }
    }
    let max_uses = invitation
        .unmarshal_statement::<InvitationStatement>()
        .map_err(|e| format!("invitation {inv_id} payload invalid: {e}"))?
        .max_uses;
    Ok(SealedParticipant {
        detail: format!(
            "joining agent and host countersign verify over the participant's canonical bytes; the host key {inv_keyid} issued sealed invitation {inv_id}; id re-derived from the pending envelope"
        ),
        host_keyid: inv_keyid,
        invitation_ref: inv_id.clone(),
        max_uses,
    })
}

/// A sealed participant that verified: who countersigned it, which
/// invitation it redeems, and how many redemptions that invitation allows.
struct SealedParticipant {
    host_keyid: String,
    invitation_ref: String,
    max_uses: u32,
    detail: String,
}

/// Returns the sealed set it verified; the `signer_trust` row is pushed by
/// [`push_signer_trust`] once the close record has been bound.
fn verify_sealed_envelopes(
    pkg_dir: &Path,
    receipt: &SessionReceipt,
    structural_only: bool,
    checks: &mut Vec<VerifyCheck>,
) -> SealedSet {
    use std::collections::{BTreeMap, BTreeSet};

    if receipt.artifacts.is_empty() {
        return SealedSet::default();
    }
    let art_dir = pkg_dir.join(ARTIFACTS_DIR);
    let any_envelope = receipt.artifacts.iter().any(|a| {
        art_dir
            .join(format!("{}.json", sanitize_filename(&a.artifact_id)))
            .exists()
    });
    if !any_envelope {
        let detail = "the package carries no artifact envelopes (built before 0.31.2), so nothing here is signature-checked: the sealed set is structurally consistent and nothing more. Verify the artifacts from the producer's store, a bundle, or the hub with `treeship verify <id>`, or read structure only with --structural (verdict: structural-pass)";
        checks.push(if structural_only {
            VerifyCheck::warn("envelopes", detail)
        } else {
            VerifyCheck::fail("envelopes", detail)
        });
        return SealedSet::default();
    }

    // Keys the package names. A key missing here fails the signature check
    // for its artifacts; the package cannot vouch for a key it does not carry.
    let mut keys: BTreeMap<String, ed25519_dalek::VerifyingKey> = BTreeMap::new();
    match read_package_keys(pkg_dir) {
        Some(pk) => {
            for (id, encoded) in pk.keys {
                match crate::trust::decode_ed25519_pubkey(&encoded) {
                    Ok(vk) => {
                        keys.insert(id, vk);
                    }
                    Err(e) => checks.push(VerifyCheck::fail(
                        "keys.json",
                        &format!("key {id} is not a valid ed25519 public key: {e}"),
                    )),
                }
            }
        }
        None => checks.push(VerifyCheck::fail(
            "keys.json",
            "package has artifact envelopes but no keys.json naming the signing keys",
        )),
    }

    // None: the payload could not be read at all.
    let mut parents: Vec<(String, Option<SignedParent>)> = Vec::new();
    let mut signers: BTreeSet<String> = BTreeSet::new();
    let mut closes: Vec<SealedClose> = Vec::new();
    let mut starts: Vec<SealedClose> = Vec::new();
    let mut approval_signers: BTreeSet<String> = BTreeSet::new();
    let mut approvals: Vec<(String, String)> = Vec::new();
    let mut consumers: Vec<(String, String)> = Vec::new();
    // (row index, artifact id, invitation_ref, host): kept only if the row
    // still passes after the redemption count.
    let mut participant_rows: Vec<(usize, String, String, String)> = Vec::new();
    let mut liveness: Vec<(String, String, String, String)> = Vec::new();
    // Each sealed id once: the same artifact sealed twice would otherwise
    // pass twice (and, for a participant, count as two joins).
    let mut seen_ids: BTreeSet<&str> = BTreeSet::new();
    // Passing participant rows per invitation: (max_uses, row indices).
    let mut redemptions: BTreeMap<String, (u32, Vec<usize>)> = BTreeMap::new();
    for entry in &receipt.artifacts {
        let id = &entry.artifact_id;
        let name = format!("signature:{id}");
        if !seen_ids.insert(id.as_str()) {
            checks.push(VerifyCheck::fail(
                &name,
                "sealed more than once in this package",
            ));
            continue;
        }
        let path = art_dir.join(format!("{}.json", sanitize_filename(id)));
        let raw = match std::fs::read(&path) {
            Ok(b) => b,
            Err(_) => {
                checks.push(VerifyCheck::fail(
                    &name,
                    "sealed in the Merkle tree but its signed envelope is not in the package",
                ));
                parents.push((id.clone(), None));
                continue;
            }
        };
        let envelope = match crate::attestation::Envelope::from_json(&raw) {
            Ok(e) => e,
            Err(e) => {
                checks.push(VerifyCheck::fail(
                    &name,
                    &format!("envelope does not parse: {e}"),
                ));
                parents.push((id.clone(), None));
                continue;
            }
        };
        // A participant carries the joining agent's and the host's
        // signatures over its canonical bytes, not a DSSE PAE signature, so
        // it is checked against its sealed invitation instead (CLI-3). An
        // absent or failing invitation fails the row; it never falls back
        // to the generic check below.
        if envelope.payload_type == crate::statements::payload_type("session-participant") {
            match verify_sealed_participant(&art_dir, receipt, entry, &envelope, &keys) {
                Ok(p) => {
                    signers.insert(p.host_keyid.clone());
                    participant_rows.push((
                        checks.len(),
                        id.clone(),
                        p.invitation_ref.clone(),
                        p.host_keyid,
                    ));
                    let slot = redemptions
                        .entry(p.invitation_ref)
                        .or_insert((p.max_uses, Vec::new()));
                    slot.1.push(checks.len());
                    checks.push(VerifyCheck::pass(&name, &p.detail));
                }
                Err(detail) => checks.push(VerifyCheck::fail(&name, &detail)),
            }
            parents.push((id.clone(), None));
            continue;
        }
        let Some(sig) = envelope.signatures.first() else {
            checks.push(VerifyCheck::fail(&name, "envelope carries no signature"));
            parents.push((id.clone(), None));
            continue;
        };
        let Some(vk) = keys.get(&sig.keyid) else {
            checks.push(VerifyCheck::fail(
                &name,
                &format!("signed by {}, a key the package does not carry", sig.keyid),
            ));
            parents.push((id.clone(), None));
            continue;
        };
        match crate::attestation::verify_with_key(&envelope, &sig.keyid, *vk) {
            Ok(res) => {
                if res.artifact_id != *id {
                    checks.push(VerifyCheck::fail(
                        &name,
                        &format!(
                            "the signed bytes re-derive to {}, not the sealed id",
                            res.artifact_id
                        ),
                    ));
                } else if entry
                    .digest
                    .as_deref()
                    .map(|d| d != res.digest)
                    .unwrap_or(false)
                {
                    checks.push(VerifyCheck::fail(
                        &name,
                        &format!(
                            "receipt lists digest {} but the signed bytes digest to {}",
                            entry.digest.clone().unwrap_or_default(),
                            res.digest
                        ),
                    ));
                } else {
                    let body = envelope
                        .payload_bytes()
                        .ok()
                        .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok());
                    if envelope.payload_type == crate::statements::payload_type("approval") {
                        approval_signers.insert(sig.keyid.clone());
                        if let Some(n) = body
                            .as_ref()
                            .and_then(|v| v.get("nonce"))
                            .and_then(|n| n.as_str())
                        {
                            approvals.push((id.clone(), n.to_string()));
                        }
                    } else {
                        signers.insert(sig.keyid.clone());
                        if envelope.payload_type
                            == crate::statements::payload_type("session-liveness")
                        {
                            let field = |k: &str| {
                                body.as_ref()
                                    .and_then(|v| v.get(k))
                                    .and_then(|x| x.as_str())
                                    .unwrap_or("")
                                    .to_string()
                            };
                            liveness.push((
                                id.clone(),
                                field("participant_ref"),
                                field("session_ref"),
                                sig.keyid.clone(),
                            ));
                        }
                        if !entry.unchained {
                            if let Some(n) = body
                                .as_ref()
                                .and_then(|v| v.get("approvalNonce"))
                                .and_then(|n| n.as_str())
                            {
                                consumers.push((n.to_string(), sig.keyid.clone()));
                            }
                        }
                    }
                    if envelope.payload_type == crate::statements::payload_type("action") {
                        if let Some(v) = envelope
                            .payload_bytes()
                            .ok()
                            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
                        {
                            let action =
                                v.get("action").and_then(|a| a.as_str()).map(str::to_string);
                            let sealed = SealedClose {
                                id: id.clone(),
                                keyid: sig.keyid.clone(),
                                chained: !entry.unchained,
                                statement: v,
                            };
                            match action.as_deref() {
                                Some("session.close") => closes.push(sealed),
                                Some("session.start") => starts.push(sealed),
                                _ => {}
                            }
                        }
                    }
                    checks.push(VerifyCheck::pass(&name, &format!("Ed25519 signature by {} verifies; id and digest re-derived from the signed bytes", sig.keyid)));
                }
            }
            Err(e) => checks.push(VerifyCheck::fail(
                &name,
                &format!("invalid signature for key {}: {e}", sig.keyid),
            )),
        }
        let parent = envelope
            .payload_bytes()
            .ok()
            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
            .map(|v| signed_parent(&v));
        parents.push((id.clone(), parent));
    }

    // An invitation is redeemed at most `max_uses` times (1 for every
    // invitation minted today). The producer's countersign gate is one
    // defense; this is the verifier's: extra redemptions fail, in order.
    for (inv, (max_uses, rows)) in &redemptions {
        if rows.len() > *max_uses as usize {
            for &i in rows.iter().skip(*max_uses as usize) {
                let detail = format!(
                    "invitation {inv} redeemed {} times in this package, max_uses {max_uses}",
                    rows.len()
                );
                checks[i] = VerifyCheck::fail(&checks[i].name.clone(), &detail);
            }
        }
    }

    // Chain linkage: each chained entry's signed parentId is the previous
    // sealed entry. The first entry's parent may lie outside the package
    // (a previous session), so it is reported, not judged.
    let chained: Vec<(usize, &ArtifactEntry)> = receipt
        .artifacts
        .iter()
        .enumerate()
        .filter(|(_, a)| !a.unchained)
        .collect();
    let mut broken: Vec<String> = Vec::new();
    let mut legacy: Vec<&str> = Vec::new();
    for w in chained.windows(2) {
        let (_, prev) = w[0];
        let (_, cur) = w[1];
        let parent = parents
            .iter()
            .find(|(id, _)| *id == cur.artifact_id)
            .and_then(|(_, p)| p.clone());
        match parent {
            Some(SignedParent::Named(p)) if p == prev.artifact_id => {}
            Some(SignedParent::Named(p)) => broken.push(format!(
                "{} names parent {} but follows {}",
                cur.artifact_id, p, prev.artifact_id
            )),
            // An endorsement from 0.31.9 or earlier signs no parent. Its
            // place in the chain is the producer's storage claim: accepted
            // with a warning, which --strict promotes (CLI-1).
            Some(SignedParent::LegacyEndorsement) => legacy.push(cur.artifact_id.as_str()),
            Some(SignedParent::None) | None => {
                broken.push(format!("{} has no readable parentId", cur.artifact_id))
            }
        }
    }
    if chained.len() >= 2 {
        if !broken.is_empty() {
            checks.push(VerifyCheck::fail("chain_linkage", &broken.join("; ")));
        } else if !legacy.is_empty() {
            checks.push(VerifyCheck::warn(
                "chain_linkage",
                &format!(
                    "{} chained artifacts; every signed parent matches, but {} endorsement(s) made by 0.31.9 or earlier sign no parent, so their place in the chain is the producer's claim only: {}",
                    chained.len(),
                    legacy.len(),
                    legacy.join(", ")
                ),
            ));
        } else {
            checks.push(VerifyCheck::pass("chain_linkage", &format!("{} chained artifacts each name the previous one as parent, inside the signature", chained.len())));
        }
    }
    let participants = participant_rows
        .into_iter()
        .filter(|(i, ..)| checks[*i].status == VerifyStatus::Pass)
        .map(|(_, id, inv, host)| (id, inv, host))
        .collect();

    SealedSet {
        signers,
        approval_signers,
        closes,
        starts,
        approvals,
        consumers,
        participants,
        liveness,
    }
}

fn finish_package_checks(
    mut checks: Vec<VerifyCheck>,
    receipt: &SessionReceipt,
) -> Vec<VerifyCheck> {
    if receipt.merkle.leaf_count == receipt.artifacts.len() {
        checks.push(VerifyCheck::pass(
            "leaf_count",
            "Leaf count matches artifact count",
        ));
    } else {
        checks.push(VerifyCheck::fail(
            "leaf_count",
            &format!(
                "leaf_count {} != artifact count {}",
                receipt.merkle.leaf_count,
                receipt.artifacts.len(),
            ),
        ));
    }

    let ordered = receipt.timeline.windows(2).all(|w| {
        (&w[0].timestamp, w[0].sequence_no, &w[0].event_id)
            <= (&w[1].timestamp, w[1].sequence_no, &w[1].event_id)
    });
    if ordered {
        checks.push(VerifyCheck::pass(
            "timeline_order",
            "Timeline is correctly ordered",
        ));
    } else {
        checks.push(VerifyCheck::fail(
            "timeline_order",
            "Timeline entries are not in deterministic order",
        ));
    }

    checks
}

/// Emit the package-local + included-checkpoint replay checks. Both are
/// fully offline: package-local scans the embedded uses for duplicates;
/// included-checkpoint walks the embedded checkpoint records and
/// re-derives each `record_digest` against its stored value.
///
/// The local-journal check is NOT here -- it requires workspace access
/// and is added by the CLI wrapper in `commands/package.rs` that has the
/// resolved config_path. Keeping these two pure means an offline tool
/// (Hub-side validator, third-party verifier) can run the same checks
/// without needing a Treeship workspace.
pub(crate) fn add_approval_evidence_checks(
    checks: &mut Vec<VerifyCheck>,
    bundle: &ApprovalsBundle,
    trust: &crate::trust::TrustRootStore,
) {
    if bundle.uses.is_empty() && bundle.checkpoints.is_empty() {
        // Nothing to assert. Stay quiet rather than emit a "skipped"
        // row -- session packages without approvals shouldn't drag in
        // approval rows by accident.
        return;
    }

    // -- replay-package-local --
    // Two distinct violation cases inside the package:
    //   (a) uses sharing (grant_id, nonce_digest) EXCEED max_uses on
    //       that grant. Two uses of a max_uses=2 grant is fine; three
    //       is the violation. max_uses is read from the use record's
    //       own `max_uses` field (a snapshot from consume time).
    //   (b) two ApprovalUse records with the same use_id -- a copy
    //       artifact from a corrupt build, never legitimate.
    use std::collections::HashMap;
    let mut by_nonce: HashMap<(String, String), Vec<&ApprovalUse>> = HashMap::new();
    let mut by_use_id: HashMap<&str, Vec<&ApprovalUse>> = HashMap::new();
    for u in &bundle.uses {
        by_nonce
            .entry((u.grant_id.clone(), u.nonce_digest.clone()))
            .or_default()
            .push(u);
        by_use_id.entry(&u.use_id).or_default().push(u);
    }
    let over_max: Vec<((String, String), Vec<&ApprovalUse>, u32)> = by_nonce
        .iter()
        .filter_map(|(key, uses)| {
            let max = uses.iter().filter_map(|u| u.max_uses).next()?;
            if (uses.len() as u32) > max {
                Some((key.clone(), uses.to_vec(), max))
            } else {
                None
            }
        })
        .collect();
    let dup_use_ids: Vec<(&&str, &Vec<&ApprovalUse>)> =
        by_use_id.iter().filter(|(_, v)| v.len() > 1).collect();

    if over_max.is_empty() && dup_use_ids.is_empty() {
        checks.push(VerifyCheck::pass(
            "replay-package-local",
            &format!(
                "no duplicate approval use inside package ({} uses scanned)",
                bundle.uses.len()
            ),
        ));
    } else {
        let mut detail = String::from("package-local replay violation:");
        for ((grant_id, _nd), uses, max) in &over_max {
            detail.push_str(&format!(
                " grant {grant_id} consumed {} times in this package (max_uses={max});",
                uses.len(),
            ));
        }
        for (uid, uses) in &dup_use_ids {
            detail.push_str(&format!(" use_id {uid} appears {} times;", uses.len()));
        }
        checks.push(VerifyCheck::fail("replay-package-local", &detail));
    }

    // -- replay-included-checkpoint --
    // For each checkpoint, recompute its record_digest from canonical
    // form. If the stored digest doesn't match, the checkpoint was
    // tampered after sealing.
    if !bundle.checkpoints.is_empty() {
        let mut tampered = Vec::new();
        for cp in &bundle.checkpoints {
            let recomputed = journal_checkpoint_record_digest(cp);
            if recomputed != cp.record_digest {
                tampered.push((
                    cp.checkpoint_id.clone(),
                    cp.record_digest.clone(),
                    recomputed,
                ));
            }
        }
        if tampered.is_empty() {
            checks.push(VerifyCheck::pass(
                "replay-included-checkpoint",
                &format!(
                    "{} included journal checkpoint(s) verify offline",
                    bundle.checkpoints.len()
                ),
            ));
        } else {
            let detail = tampered
                .iter()
                .map(|(id, expected, actual)| {
                    format!("checkpoint {id} tampered (stored {expected}, recomputed {actual})")
                })
                .collect::<Vec<_>>()
                .join("; ");
            checks.push(VerifyCheck::fail("replay-included-checkpoint", &detail));
        }
    }

    // -- approval-use-record-digest --
    // Each ApprovalUse carries its own record_digest computed over the
    // canonical form of the record (minus the digest itself). Tampering
    // any field changes the digest. v0.9.10 PR A renames this from the
    // older `approval-use-integrity` because the prior label suggested
    // it covered nonce/action binding -- it didn't, and Codex's v0.9.9
    // adversarial review flagged the over-claim. The honest scope of
    // this row is "each use's stored digest matches its canonical
    // recompute"; the binding checks are now separate rows below.
    let mut tampered_uses = Vec::new();
    for u in &bundle.uses {
        let recomputed = approval_use_record_digest(u);
        if recomputed != u.record_digest {
            tampered_uses.push((u.use_id.clone(), u.record_digest.clone(), recomputed));
        }
    }
    if !bundle.uses.is_empty() {
        if tampered_uses.is_empty() {
            checks.push(VerifyCheck::pass(
                "approval-use-record-digest",
                &format!("{} use record(s) recompute identically", bundle.uses.len()),
            ));
        } else {
            let detail = tampered_uses
                .iter()
                .map(|(id, expected, actual)| {
                    format!("use {id} tampered (stored {expected}, recomputed {actual})")
                })
                .collect::<Vec<_>>()
                .join("; ");
            checks.push(VerifyCheck::fail("approval-use-record-digest", &detail));
        }
    }

    // -- approval-use-nonce-binding --
    // Cross-check each use's `nonce_digest` against the corresponding
    // grant's *signed* nonce. v0.9.9 trusted the use's nonce_digest
    // verbatim, which let an attacker who controls the package mutate
    // it (and recompute record_digest) to claim consumption of a grant
    // whose nonce was never actually used. This row closes that gap.
    //
    // Discipline: the grant envelope is the source of truth. Before
    // pulling the raw `nonce` from the grant's payload we verify the
    // envelope's *content addressing* -- recompute the artifact_id
    // from the envelope's PAE bytes and confirm it equals the grant_id
    // the package claims. v0.9.10 PR A round 1 only parsed the
    // envelope without this check; that left a forgery window where
    // an attacker could ship an arbitrary unsigned envelope under any
    // grant_id filename. v0.9.10 PR A round 2 closes the window: only
    // a bytes-identical envelope produces the same artifact_id under
    // SHA-256.
    if !bundle.uses.is_empty() {
        use crate::attestation::envelope::Envelope;
        use crate::attestation::{artifact_id_from_pae, pae};
        use crate::statements::{nonce_digest, ApprovalStatement};
        let mut grant_nonce_digest: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        let mut tampered_grants: Vec<String> = Vec::new();
        for (grant_id, env_bytes) in &bundle.grants {
            let env = match Envelope::from_json(env_bytes) {
                Ok(e) => e,
                Err(_) => {
                    tampered_grants.push(format!("grant {grant_id} envelope unparseable"));
                    continue;
                }
            };
            // Content-addressing check: derive the artifact_id from
            // the envelope's PAE bytes and confirm it matches the
            // claimed grant_id. If they differ the envelope was
            // substituted or its bytes were tampered post-sign.
            let derived = match env.payload_bytes() {
                Ok(p) => artifact_id_from_pae(&pae(&env.payload_type, &p)),
                Err(_) => {
                    tampered_grants.push(format!("grant {grant_id} envelope payload undecodable"));
                    continue;
                }
            };
            if &derived != grant_id {
                tampered_grants.push(format!(
                    "grant {grant_id} envelope content derives to {derived} -- envelope substituted or tampered",
                ));
                continue;
            }
            let approval: ApprovalStatement = match env.unmarshal_statement() {
                Ok(a) => a,
                Err(_) => {
                    tampered_grants
                        .push(format!("grant {grant_id} payload not an ApprovalStatement"));
                    continue;
                }
            };
            grant_nonce_digest.insert(grant_id.clone(), nonce_digest(&approval.nonce));
        }
        let mut mismatches: Vec<String> = Vec::new();
        let mut missing_grants: Vec<String> = Vec::new();
        for u in &bundle.uses {
            match grant_nonce_digest.get(&u.grant_id) {
                Some(expected) => {
                    if expected != &u.nonce_digest {
                        mismatches.push(format!(
                            "use {} claims nonce_digest {} but grant {} signed nonce hashes to {}",
                            u.use_id, u.nonce_digest, u.grant_id, expected,
                        ));
                    }
                }
                None => {
                    missing_grants.push(format!(
                        "use {} references grant {} but no usable grant envelope is in the package",
                        u.use_id, u.grant_id,
                    ));
                }
            }
        }
        if mismatches.is_empty() && missing_grants.is_empty() && tampered_grants.is_empty() {
            checks.push(VerifyCheck::pass(
                "approval-use-nonce-binding",
                &format!(
                    "{} use record(s) bind to content-addressed grant signed nonces",
                    bundle.uses.len(),
                ),
            ));
        } else {
            let mut parts: Vec<String> = Vec::new();
            if !tampered_grants.is_empty() {
                parts.push(tampered_grants.join("; "));
            }
            if !mismatches.is_empty() {
                parts.push(mismatches.join("; "));
            }
            if !missing_grants.is_empty() {
                parts.push(missing_grants.join("; "));
            }
            checks.push(VerifyCheck::fail(
                "approval-use-nonce-binding",
                &parts.join("; "),
            ));
        }
    }

    // -- approval-use-action-binding --
    // Cross-check each consuming action's `meta.approval_use_id`
    // against the package's use records. v0.9.9 ignored this pointer
    // entirely; the package didn't even ship action envelopes, so the
    // verifier could not see the field. v0.9.10 PR A: action envelopes
    // ride along in `artifacts/`, and this row pins that every action
    // declaring it consumed an approval has a use record for that
    // exact use_id, with matching grant_id and matching
    // `nonce_digest(approval_nonce)`.
    //
    // Honesty rule: when bundle.action_envelopes is empty (pre-v0.9.10
    // packages, or a v0.9.10 package with no consuming actions
    // recorded), this row reports `not asserted by package` rather
    // than silent PASS.
    if !bundle.uses.is_empty() {
        use crate::attestation::envelope::Envelope;
        use crate::attestation::{artifact_id_from_pae, pae};
        use crate::statements::{nonce_digest, ActionStatement};
        if bundle.action_envelopes.is_empty() {
            checks.push(VerifyCheck::warn(
                "approval-use-action-binding",
                "no action envelopes embedded -- action↔use binding not asserted by package (pre-v0.9.10)",
            ));
        } else {
            let use_ids: std::collections::HashSet<&str> =
                bundle.uses.iter().map(|u| u.use_id.as_str()).collect();
            let mut violations: Vec<String> = Vec::new();
            let mut bound_count = 0usize;
            let mut not_actions = 0usize;
            let action_v1 = crate::statements::payload_type("action");
            for (artifact_id, env_bytes) in &bundle.action_envelopes {
                let env = match Envelope::from_json(env_bytes) {
                    Ok(e) => e,
                    Err(_) => {
                        violations.push(format!("action {artifact_id} envelope unparseable"));
                        continue;
                    }
                };
                // Since 0.31.2 a package carries every sealed envelope under
                // artifacts/, not only the consuming actions this row was
                // written for. A grant, a coverage receipt or a judgement is
                // not an action and cannot consume an approval; it is not
                // subject to this row and was wrongly failed as "not an
                // ActionStatement" (QA on 0.31.9: the merchant package failed
                // on its grant and its coverage receipt). Only v1 action
                // envelopes are checked; the count of the rest is reported.
                if env.payload_type != action_v1 {
                    not_actions += 1;
                    continue;
                }
                // Content-addressing gate: derive the artifact_id
                // from the envelope's PAE bytes and require it to
                // match the filename stem the package shipped this
                // envelope under. Without this gate an attacker
                // controlling the package can write any forged
                // unsigned action JSON to artifacts/<id>.json and the
                // binding rows would trust it.
                let derived = match env.payload_bytes() {
                    Ok(p) => artifact_id_from_pae(&pae(&env.payload_type, &p)),
                    Err(_) => {
                        violations
                            .push(format!("action {artifact_id} envelope payload undecodable"));
                        continue;
                    }
                };
                if &derived != artifact_id {
                    violations.push(format!(
                        "action {artifact_id} envelope content derives to {derived} -- envelope substituted or tampered",
                    ));
                    continue;
                }
                let action: ActionStatement = match env.unmarshal_statement() {
                    Ok(a) => a,
                    Err(_) => {
                        violations.push(format!("action {artifact_id} not an ActionStatement"));
                        continue;
                    }
                };
                let raw_nonce = match action.approval_nonce.as_deref() {
                    Some(n) => n,
                    None => continue,
                };
                let claimed_use_id = action
                    .meta
                    .as_ref()
                    .and_then(|m| m.get("approval_use_id"))
                    .and_then(|v| v.as_str());
                let Some(claimed_use_id) = claimed_use_id else {
                    violations.push(format!(
                        "action {artifact_id} consumed an approval but its meta has no approval_use_id"
                    ));
                    continue;
                };
                if !use_ids.contains(claimed_use_id) {
                    violations.push(format!(
                        "action {artifact_id} claims approval_use_id={} but no such use is embedded",
                        claimed_use_id,
                    ));
                    continue;
                }
                let expected = nonce_digest(raw_nonce);
                let matched_use = bundle.uses.iter().find(|u| u.use_id == claimed_use_id);
                if let Some(u) = matched_use {
                    if u.nonce_digest != expected {
                        violations.push(format!(
                            "action {artifact_id} approval_nonce hashes to {} but use {} stores nonce_digest {}",
                            expected, claimed_use_id, u.nonce_digest,
                        ));
                        continue;
                    }
                    // The use record's actor and action are unsigned; the
                    // consuming action's are signed. A record edited to
                    // name another actor or action (digest recomputed)
                    // no longer describes the action that consumed it.
                    if u.actor != action.actor || u.action != action.action {
                        violations.push(format!(
                            "use {} records {} doing {} but the signed action {artifact_id} is {} doing {}",
                            claimed_use_id, u.actor, u.action, action.actor, action.action,
                        ));
                        continue;
                    }
                }
                bound_count += 1;
            }
            if violations.is_empty() {
                checks.push(VerifyCheck::pass(
                    "approval-use-action-binding",
                    &format!(
                        "{bound_count} consuming action(s) bind cleanly to content-addressed envelope(s){}",
                        if not_actions > 0 {
                            format!("; {not_actions} non-action envelope(s) not subject to this row")
                        } else {
                            String::new()
                        }
                    ),
                ));
            } else {
                checks.push(VerifyCheck::fail(
                    "approval-use-action-binding",
                    &violations.join("; "),
                ));
            }
        }
    }

    // -- approval-use-chain-continuity --
    // v0.9.9 verified each use's individual record_digest but never
    // walked the `previous_record_digest` chain across the embedded
    // records. An attacker could rewrite an entire chain consistently
    // (recomputing each digest along the way) and the per-record
    // checks all passed.
    //
    // Algorithm (v0.9.10 PR A round 2): build a graph of embedded
    // records keyed by record_digest, then require the embedded
    // records to form a SINGLE linked list with exactly one genesis
    // (previous_record_digest == "") and no cycles, forks, or
    // disconnected subchains.
    //
    //   - Dangling prev pointer (not in `owned`) -> fail.
    //   - More than one record with prev == ""    -> fail (mid-chain
    //     genesis is a forgery primitive).
    //   - Two records sharing the same prev       -> fail (fork).
    //   - Cycle reached during the walk           -> fail.
    //   - Walk doesn't reach every record         -> fail (disconnected
    //     subchain).
    //
    // We can only check *internal* consistency offline -- the package
    // doesn't ship the workspace journal's full history, so the chain
    // we see may be a contiguous prefix or window. Anchoring against
    // a Hub-signed checkpoint is replay-hub-org's job; here we report
    // structural consistency only.
    if !bundle.uses.is_empty() || !bundle.checkpoints.is_empty() {
        use std::collections::{HashMap, HashSet};
        // Each record carries a label for diagnostics + its own
        // record_digest + previous_record_digest.
        struct Node<'a> {
            label: String,
            digest: &'a str,
            prev: &'a str,
        }
        let mut nodes: Vec<Node> = Vec::new();
        for u in &bundle.uses {
            nodes.push(Node {
                label: format!("use {}", u.use_id),
                digest: u.record_digest.as_str(),
                prev: u.previous_record_digest.as_str(),
            });
        }
        for cp in &bundle.checkpoints {
            nodes.push(Node {
                label: format!("checkpoint {}", cp.checkpoint_id),
                digest: cp.record_digest.as_str(),
                prev: cp.previous_record_digest.as_str(),
            });
        }

        let owned: HashSet<&str> = std::iter::once("")
            .chain(nodes.iter().map(|n| n.digest))
            .collect();

        let mut violations: Vec<String> = Vec::new();
        // Dangling prev: pointer not in owned set.
        for n in &nodes {
            if !owned.contains(n.prev) {
                violations.push(format!(
                    "{} previous_record_digest {} not anchored in package",
                    n.label, n.prev,
                ));
            }
        }
        // Genesis count: only one record allowed to have prev == "".
        let genesis: Vec<&Node> = nodes.iter().filter(|n| n.prev.is_empty()).collect();
        if genesis.len() > 1 {
            violations.push(format!(
                "{} records claim previous_record_digest='' (genesis): {}",
                genesis.len(),
                genesis
                    .iter()
                    .map(|n| n.label.clone())
                    .collect::<Vec<_>>()
                    .join(", "),
            ));
        }
        // Forks: two records sharing the same non-empty prev.
        let mut by_prev: HashMap<&str, Vec<&Node>> = HashMap::new();
        for n in &nodes {
            by_prev.entry(n.prev).or_default().push(n);
        }
        for (prev, group) in &by_prev {
            if group.len() > 1 && !prev.is_empty() {
                violations.push(format!(
                    "fork: {} records share previous_record_digest {}: {}",
                    group.len(),
                    prev,
                    group
                        .iter()
                        .map(|n| n.label.clone())
                        .collect::<Vec<_>>()
                        .join(", "),
                ));
            }
        }

        // Walk from genesis (if exactly one) following digest-as-prev
        // links. Detect cycles and unreachable records.
        if violations.is_empty() {
            let by_digest: HashMap<&str, &Node> = nodes.iter().map(|n| (n.digest, n)).collect();
            let next_of: HashMap<&str, &Node> = nodes
                .iter()
                .filter(|n| !n.prev.is_empty())
                .map(|n| (n.prev, n))
                .collect();
            let start = genesis.first().copied();
            let mut visited: HashSet<&str> = HashSet::new();
            let mut current = start;
            while let Some(node) = current {
                if !visited.insert(node.digest) {
                    violations.push(format!(
                        "cycle detected at {} (record_digest {})",
                        node.label, node.digest,
                    ));
                    break;
                }
                current = next_of.get(node.digest).copied();
            }
            // Disconnected: walk didn't include every node.
            if violations.is_empty() && visited.len() != nodes.len() {
                let unreached: Vec<String> = nodes
                    .iter()
                    .filter(|n| !visited.contains(n.digest))
                    .map(|n| n.label.clone())
                    .collect();
                if !unreached.is_empty() {
                    violations.push(format!(
                        "disconnected subchain: {} record(s) not reachable from genesis: {}",
                        unreached.len(),
                        unreached.join(", "),
                    ));
                }
            }
            let _ = by_digest; // reserved for future cross-checks
        }

        if violations.is_empty() {
            checks.push(VerifyCheck::pass(
                "approval-use-chain-continuity",
                &format!(
                    "{} record(s) form a single connected linked list from one genesis with no cycles or forks",
                    nodes.len(),
                ),
            ));
        } else {
            checks.push(VerifyCheck::fail(
                "approval-use-chain-continuity",
                &violations.join("; "),
            ));
        }
    }

    // -- replay-hub-org -- v0.9.9 PR 6.
    // The strongest level Treeship can speak to today. The release
    // rule is non-negotiable: PASS only when (1) at least one embedded
    // checkpoint declares kind=HubOrg, (2) every required Hub field is
    // populated, (3) the signature verifies against the embedded
    // public key, AND (4) the checkpoint covers every embedded
    // ApprovalUse via covered_use_ids. Anything short of that means
    // "no row" or "fail" -- never silent pass.
    //
    // No row at all when the package has no Hub-kind checkpoint:
    // matches the v0.9.9 PR 4-5 behavior where the panel renders
    // "- hub-org   not checked (no Hub checkpoint in package)" so a
    // reader doesn't misread an absent row as a failure.
    let hub_checkpoints: Vec<&JournalCheckpoint> = bundle
        .checkpoints
        .iter()
        .filter(|cp| cp.checkpoint_kind == crate::statements::CheckpointKind::HubOrg)
        .collect();
    if !hub_checkpoints.is_empty() {
        let mut all_ok = true;
        let mut details: Vec<String> = Vec::new();
        let mut have_valid_signature = false;
        // Security-critical failures (untrusted-issuer / tampered /
        // not-hub-kind) must FAIL unconditionally, not warn. Audit
        // lane J fix-up: previously these emitted WARN and the CLI
        // wrapper's --strict promoted to FAIL, which meant the
        // headline audit case (self-signed hub-org forgery) passed
        // green-but-yellow in default mode. The release rule is
        // "trust pinning is on by default"; expressed in this row
        // as "any signature/issuer failure is a hard fail."
        let mut security_fatal = false;

        for cp in &hub_checkpoints {
            match crate::statements::verify_hub_checkpoint_signature(cp, trust) {
                crate::statements::HubCheckpointVerification::Valid => {
                    have_valid_signature = true;
                    // Coverage: every embedded use_id MUST appear in
                    // this checkpoint's covered_use_ids. A checkpoint
                    // that doesn't cover the package's uses cannot
                    // promote replay-hub-org for those uses.
                    let covered: std::collections::HashSet<&String> =
                        cp.covered_use_ids.iter().collect();
                    let missing: Vec<String> = bundle
                        .uses
                        .iter()
                        .filter(|u| !covered.contains(&u.use_id))
                        .map(|u| u.use_id.clone())
                        .collect();
                    if missing.is_empty() {
                        details.push(format!(
                            "{} signed by {} verifies; covers {} use(s)",
                            cp.checkpoint_id,
                            cp.hub_id,
                            cp.covered_use_ids.len(),
                        ));
                    } else {
                        all_ok = false;
                        details.push(format!(
                            "{} verifies but does not cover {} use(s): {}",
                            cp.checkpoint_id,
                            missing.len(),
                            missing.join(", "),
                        ));
                    }
                }
                crate::statements::HubCheckpointVerification::MissingFields(field) => {
                    all_ok = false;
                    details.push(format!(
                        "{} declares kind=hub-org but field `{}` is missing",
                        cp.checkpoint_id, field,
                    ));
                }
                crate::statements::HubCheckpointVerification::Tampered => {
                    all_ok = false;
                    security_fatal = true;
                    details.push(format!(
                        "{} hub signature failed verification (tampered or wrong key)",
                        cp.checkpoint_id,
                    ));
                }
                crate::statements::HubCheckpointVerification::NotHubKind => {
                    // Filter ensures this is unreachable; keep the
                    // arm so a future filter relaxation doesn't go
                    // silent.
                    all_ok = false;
                    security_fatal = true;
                    details.push(format!(
                        "{} kind toggled out of hub-org during verify",
                        cp.checkpoint_id,
                    ));
                }
                crate::statements::HubCheckpointVerification::UntrustedIssuer => {
                    all_ok = false;
                    security_fatal = true;
                    details.push(format!(
                        "{} hub_public_key is not a trusted root (configure via `treeship trust add`)",
                        cp.checkpoint_id,
                    ));
                }
            }
        }
        if all_ok && have_valid_signature {
            checks.push(VerifyCheck::pass("replay-hub-org", &details.join("; ")));
        } else if security_fatal {
            // Untrusted issuer or tampered signature: fail-by-default
            // regardless of --strict. Self-signed forgeries must not
            // pass yellow.
            checks.push(VerifyCheck::fail("replay-hub-org", &details.join("; ")));
        } else {
            // Hub checkpoint is present but does not satisfy every
            // non-security gate (missing-field, coverage gap).
            // Default mode warns; the CLI verify wrapper's --strict
            // promotes to fail.
            checks.push(VerifyCheck::warn("replay-hub-org", &details.join("; ")));
        }
    }
    // No hub-org checkpoints embedded -> no row. The Approval
    // Authority panel still renders "- hub-org   not checked".

    let _ = ReplayCheckLevel::HubOrg;
    let _ = approval_revocation_record_digest as fn(&ApprovalRevocation) -> String;
    let _ = ReplayCheck::not_performed;
}

/// A single verification check result.
#[derive(Debug, Clone)]
pub struct VerifyCheck {
    pub name: String,
    pub status: VerifyStatus,
    pub detail: String,
}

/// Status of a verification check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerifyStatus {
    Pass,
    Fail,
    Warn,
}

impl VerifyCheck {
    pub fn pass(name: &str, detail: &str) -> Self {
        Self {
            name: name.into(),
            status: VerifyStatus::Pass,
            detail: detail.into(),
        }
    }
    pub fn fail(name: &str, detail: &str) -> Self {
        Self {
            name: name.into(),
            status: VerifyStatus::Fail,
            detail: detail.into(),
        }
    }
    pub fn warn(name: &str, detail: &str) -> Self {
        Self {
            name: name.into(),
            status: VerifyStatus::Warn,
            detail: detail.into(),
        }
    }
}

impl VerifyCheck {
    pub fn passed(&self) -> bool {
        self.status == VerifyStatus::Pass
    }
}

/// HTML template for the self-contained verifier preview.
/// Loaded at compile time so the binary carries no runtime file dependencies.
const PREVIEW_TEMPLATE: &str = include_str!("preview_template.html");

/// Brand display serif (Fraunces, SIL OFL 1.1) — latin variable slice, weights
/// 300..500. Embedded as base64 into the self-contained preview so the document
/// renders with the brand type offline, no CDN. Body and mono use the system
/// stack. See design/fonts/.
// Vendored inside the crate, not referenced out of the workspace. `cargo
// package` only tarballs files under the crate root, so an `include_bytes!`
// reaching up to `design/fonts/` builds fine here and fails to compile once
// published -- which is exactly how treeship-core missed crates.io in v0.22.0
// while npm and PyPI shipped. Kept in sync with `design/fonts/` by
// `scripts/check-vendored-fonts.py`.
const FRAUNCES_WOFF2: &[u8] = include_bytes!("../../assets/fonts/fraunces-latin-var.woff2");

/// The `data:` URI for the embedded Fraunces woff2, substituted into the
/// template's `@font-face`. Standard (not URL-safe) base64: it sits in a CSS
/// `url(...)`, not a URL path.
fn fraunces_data_uri() -> String {
    use base64::engine::general_purpose::STANDARD;
    use base64::Engine;
    format!("data:font/woff2;base64,{}", STANDARD.encode(FRAUNCES_WOFF2))
}

/// Generate a self-contained preview.html that embeds the receipt JSON
/// and runs Merkle verification client-side using Web Crypto API.
///
/// The HTML works fully air-gapped: no network calls, no CDN, no server.
/// Open it in any modern browser and it automatically verifies the receipt
/// and shows pass/fail for each check.
pub fn render_preview_html(receipt: &SessionReceipt) -> String {
    render_preview_html_with_approvals(receipt, None)
}

/// What the preview shows under "Approval gates": every grant the package
/// embeds under `approvals/grants` and every use under `approvals/uses`.
///
/// The preview used to read approvals only from the chained artifacts, so a
/// session whose approvals were consumed (and therefore exported into the
/// `approvals/` directory, where the verifier checks them) rendered "No
/// approval gates recorded" while `package verify` printed `PASS
/// replay-local-journal`. This is the same evidence the verifier reads,
/// summarised for a reader. A grant envelope that does not parse is listed
/// by id with `parsed: false` rather than dropped: the reader should see
/// that evidence exists even when this page cannot describe it.
pub fn preview_approvals_json(bundle: Option<&ApprovalsBundle>) -> serde_json::Value {
    let Some(b) = bundle else {
        return serde_json::Value::Null;
    };
    if b.grants.is_empty() && b.uses.is_empty() {
        return serde_json::Value::Null;
    }
    let grants: Vec<serde_json::Value> = b
        .grants
        .iter()
        .map(|(grant_id, bytes)| {
            let parsed = crate::attestation::Envelope::from_json(bytes)
                .ok()
                .and_then(|env| env.unmarshal_statement::<ApprovalStatement>().ok());
            match parsed {
                Some(st) => serde_json::json!({
                    "grant_id": grant_id,
                    "parsed": true,
                    "approver": st.approver,
                    "description": st.description,
                    "timestamp": st.timestamp,
                    "expires_at": st.expires_at,
                    "scope": st.scope.as_ref().map(|sc| serde_json::json!({
                        "allowed_actors": sc.allowed_actors,
                        "allowed_actions": sc.allowed_actions,
                        "allowed_subjects": sc.allowed_subjects,
                        "max_uses": sc.max_actions,
                        "valid_until": sc.valid_until,
                    })),
                }),
                None => serde_json::json!({ "grant_id": grant_id, "parsed": false }),
            }
        })
        .collect();
    let uses: Vec<serde_json::Value> = b
        .uses
        .iter()
        .map(|u| serde_json::to_value(u).unwrap_or(serde_json::Value::Null))
        .collect();
    serde_json::json!({ "grants": grants, "uses": uses })
}

/// `render_preview_html`, plus the approval evidence the package embeds.
pub fn render_preview_html_with_approvals(
    receipt: &SessionReceipt,
    bundle: Option<&ApprovalsBundle>,
) -> String {
    let approvals_json = preview_approvals_json(bundle).to_string();
    let safe_approvals = approvals_json.replace('<', r"\u003c");
    let receipt_json = serde_json::to_string_pretty(receipt).unwrap_or_else(|_| "{}".to_string());
    // Defense-in-depth: escape </script sequences so a malicious receipt
    // field cannot break out of the JSON data block. The primary defense
    // is type="application/json" which the HTML parser does not execute,
    // but this escaping adds a second layer.
    // Escape ALL '<' as '\u003c' in the JSON string to prevent any
    // case-variant of </script> from breaking out of the data block.
    // This is bulletproof: no HTML parser can see a tag open inside the JSON.
    let safe_json = receipt_json.replace('<', r"\u003c");

    // The only placeholder that must take the receipt JSON is the data
    // block. replacen(.., 1) substitutes exactly that first occurrence, so
    // even if the token is ever reused elsewhere in the template (e.g. a JS
    // placeholder check) the receipt body is never injected into it. The
    // template's own placeholder check uses a split sentinel for the same
    // reason. The page title is set at runtime from the parsed JSON.
    PREVIEW_TEMPLATE
        .replacen("__RECEIPT_JSON__", &safe_json, 1)
        .replacen("__APPROVALS_JSON__", &safe_approvals, 1)
        .replace("__FONT_FRAUNCES__", &fraunces_data_uri())
}

/// Find the `coverage.v1` receipt among the sealed envelopes and summarise
/// it; warn when the package carries none.
fn coverage_check(pkg_dir: &Path, receipt: &SessionReceipt) -> VerifyCheck {
    let art_dir = pkg_dir.join(ARTIFACTS_DIR);
    for entry in &receipt.artifacts {
        let path = art_dir.join(format!("{}.json", sanitize_filename(&entry.artifact_id)));
        let Ok(raw) = std::fs::read(&path) else {
            continue;
        };
        let Ok(env) = crate::attestation::Envelope::from_json(&raw) else {
            continue;
        };
        let Some(stmt) = env
            .payload_bytes()
            .ok()
            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
        else {
            continue;
        };
        if stmt.get("kind").and_then(|k| k.as_str()) != Some("coverage.v1") {
            continue;
        }
        let Some(p) = stmt.get("payload") else {
            continue;
        };
        let level = p
            .get("declared_level")
            .and_then(|v| v.as_str())
            .unwrap_or("?");
        let harnesses: Vec<String> = p
            .get("harnesses")
            .and_then(|h| h.as_array())
            .map(|arr| {
                arr.iter()
                    .map(|h| {
                        let id = h.get("harness_id").and_then(|v| v.as_str()).unwrap_or("?");
                        let modes: Vec<&str> = h
                            .get("connection_modes")
                            .and_then(|m| m.as_array())
                            .map(|m| m.iter().filter_map(|x| x.as_str()).collect())
                            .unwrap_or_default();
                        if modes.is_empty() {
                            id.to_string()
                        } else {
                            format!("{id} via {}", modes.join("+"))
                        }
                    })
                    .collect()
            })
            .unwrap_or_default();
        let events = p
            .get("observed")
            .and_then(|o| o.get("events"))
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        let types = p
            .get("observed")
            .and_then(|o| o.get("event_types"))
            .and_then(|t| t.as_object())
            .map(|m| m.len())
            .unwrap_or(0);
        let gaps = p
            .get("gaps")
            .and_then(|g| g.as_array())
            .map(|g| g.len())
            .unwrap_or(0);
        let via = if harnesses.is_empty() {
            "no harness state".to_string()
        } else {
            harnesses.join(", ")
        };
        return VerifyCheck::pass(
            "coverage",
            &format!(
                "{}: declared {level} ({via}); {events} events observed across {types} types; {gaps} stated gap(s). A declared level is the harness's potential, not proof of what happened outside it",
                entry.artifact_id
            ),
        );
    }
    VerifyCheck::warn(
        "coverage",
        "no coverage receipt in the sealed set: the package does not say what the harness could observe (sealed before 0.31.6, or minted without one)",
    )
}

/// One sealed action, as much of it as the retries row needs.
struct SealedAction {
    action: String,
    actor: String,
    retry: Option<serde_json::Value>,
    /// The signed idempotency key of this attempt (v1 `idempotencyKey`, v2
    /// `idempotency_key`), or the one inside its retry block.
    idempotency_key: Option<String>,
    /// What the attempt says it changed: v2 `effect.readback`, else
    /// `effect.output_hash`, else v1 `meta.output_digest`.
    effect_signature: Option<String>,
    effect_verified: bool,
}

/// Walk the sealed envelopes for action statements and check every retry
/// chain. `None` when no action names an earlier attempt.
fn retries_check(pkg_dir: &Path, receipt: &SessionReceipt) -> Option<VerifyCheck> {
    use std::collections::{BTreeMap, BTreeSet};
    let art_dir = pkg_dir.join(ARTIFACTS_DIR);
    let mut actions: BTreeMap<String, SealedAction> = BTreeMap::new();
    for entry in &receipt.artifacts {
        let path = art_dir.join(format!("{}.json", sanitize_filename(&entry.artifact_id)));
        let Ok(raw) = std::fs::read(&path) else {
            continue;
        };
        let Ok(env) = crate::attestation::Envelope::from_json(&raw) else {
            continue;
        };
        let Some(stmt) = env
            .payload_bytes()
            .ok()
            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
        else {
            continue;
        };
        let ty = stmt.get("type").and_then(|t| t.as_str()).unwrap_or("");
        if !ty.contains("/action/") {
            continue;
        }
        let effect = stmt.get("effect");
        let effect_signature = effect
            .and_then(|e| e.get("readback"))
            .and_then(|v| v.as_str())
            .or_else(|| {
                effect
                    .and_then(|e| e.get("output_hash"))
                    .and_then(|v| v.as_str())
            })
            .or_else(|| {
                stmt.get("meta")
                    .and_then(|m| m.get("output_digest"))
                    .and_then(|v| v.as_str())
            })
            .map(str::to_string);
        let effect_verified = matches!(
            effect
                .and_then(|e| e.get("effect_confidence"))
                .and_then(|v| v.as_str()),
            Some("verified") | Some("partial")
        );
        actions.insert(
            entry.artifact_id.clone(),
            SealedAction {
                action: stmt
                    .get("action")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string(),
                actor: stmt
                    .get("actor")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string(),
                idempotency_key: stmt
                    .get("idempotencyKey")
                    .or_else(|| stmt.get("idempotency_key"))
                    .or_else(|| stmt.get("retry").and_then(|r| r.get("idempotency_key")))
                    .and_then(|v| v.as_str())
                    .map(str::to_string),
                retry: stmt.get("retry").cloned(),
                effect_signature,
                effect_verified,
            },
        );
    }
    let retries: Vec<(&String, &SealedAction)> =
        actions.iter().filter(|(_, a)| a.retry.is_some()).collect();
    if retries.is_empty() {
        return None;
    }
    let mut problems: Vec<String> = Vec::new();
    let mut chains: BTreeSet<String> = BTreeSet::new();
    for (id, a) in &retries {
        let r = a.retry.as_ref().unwrap();
        let of = r.get("of").and_then(|v| v.as_str()).unwrap_or("");
        let attempt = r.get("attempt").and_then(|v| v.as_u64()).unwrap_or(0);
        let cause = r.get("cause").and_then(|v| v.as_str()).unwrap_or("unknown");
        let key = r.get("idempotency_key").and_then(|v| v.as_str());
        let Some(prev) = actions.get(of) else {
            problems.push(format!(
                "{id} (attempt {attempt}, {cause}) retries {of}, which is not in this package"
            ));
            chains.insert(of.to_string());
            continue;
        };
        // The chain root is the attempt with no retry block.
        let mut root = of.to_string();
        let mut hops = 0;
        while let Some(p) = actions.get(&root) {
            match p
                .retry
                .as_ref()
                .and_then(|x| x.get("of"))
                .and_then(|v| v.as_str())
            {
                Some(next) if hops < 64 => {
                    root = next.to_string();
                    hops += 1;
                }
                _ => break,
            }
        }
        chains.insert(root);
        if prev.action != a.action || prev.actor != a.actor {
            problems.push(format!(
                "{id} retries {of} but is a different action or actor ({} by {} vs {} by {})",
                a.action, a.actor, prev.action, prev.actor
            ));
        }
        let prev_attempt = prev
            .retry
            .as_ref()
            .and_then(|x| x.get("attempt"))
            .and_then(|v| v.as_u64())
            .unwrap_or(1);
        if attempt != prev_attempt + 1 {
            problems.push(format!(
                "{id} is attempt {attempt} but retries attempt {prev_attempt}"
            ));
        }
        let prev_key = prev.idempotency_key.as_deref();
        if let (Some(k), Some(pk)) = (key, prev_key) {
            if k != pk {
                problems.push(format!(
                    "{id} retries {of} with a different idempotency key: the second attempt is not idempotent with the first"
                ));
            }
        }
        if let (Some(cur), Some(before)) = (&a.effect_signature, &prev.effect_signature) {
            if cur != before {
                problems.push(format!(
                    "{id} and {of} both report an effect and they differ ({} vs {}): two mutations, not one recovery",
                    &cur[..cur.len().min(24)],
                    &before[..before.len().min(24)]
                ));
            }
        }
        if cause == "timeout" && prev.effect_verified {
            problems.push(format!(
                "{id} retried {of} for a timeout, but {of} reports a verified effect: the first attempt landed"
            ));
        }
    }
    let n = retries.len();
    let c = chains.len();
    if problems.is_empty() {
        Some(VerifyCheck::pass(
            "retries",
            &format!(
                "{n} retry attempt(s) across {c} chain(s): same action and actor, attempts count up, idempotency keys agree, and no two attempts report a distinct effect"
            ),
        ))
    } else {
        Some(VerifyCheck::warn(
            "retries",
            &format!(
                "{n} retry attempt(s) across {c} chain(s); {}: {}",
                problems.len(),
                problems.join("; ")
            ),
        ))
    }
}

/// Summarise the `judgement.v1` receipts in the sealed set: how many, which
/// judges, and whether any was acted on below its own threshold. `None`
/// when the package carries no judgement.
fn judgements_check(pkg_dir: &Path, receipt: &SessionReceipt) -> Option<VerifyCheck> {
    let art_dir = pkg_dir.join(ARTIFACTS_DIR);
    let mut total = 0usize;
    let mut judges: BTreeSet<String> = BTreeSet::new();
    let mut flagged: Vec<String> = Vec::new();
    // Escalations are open questions until a signed resolution names them.
    let mut escalated: Vec<String> = Vec::new();
    let mut effects: std::collections::BTreeMap<String, String> = Default::default();
    // judgement id -> (by, decision, overrides the judge?)
    let mut resolutions: std::collections::BTreeMap<String, (String, String, bool)> =
        Default::default();
    for entry in &receipt.artifacts {
        let path = art_dir.join(format!("{}.json", sanitize_filename(&entry.artifact_id)));
        let Ok(raw) = std::fs::read(&path) else {
            continue;
        };
        let Ok(env) = crate::attestation::Envelope::from_json(&raw) else {
            continue;
        };
        let Some(stmt) = env
            .payload_bytes()
            .ok()
            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
        else {
            continue;
        };
        if stmt.get("kind").and_then(|k| k.as_str()) != Some("judgement.resolution.v1") {
            continue;
        }
        let Some(p) = stmt.get("payload") else {
            continue;
        };
        let (Some(j), Some(by), Some(d)) = (
            p.get("judgement").and_then(|v| v.as_str()),
            p.get("by").and_then(|v| v.as_str()),
            p.get("decision").and_then(|v| v.as_str()),
        ) else {
            continue;
        };
        resolutions.insert(
            j.to_string(),
            (by.to_string(), d.to_string(), p.get("overrides").is_some()),
        );
    }
    for entry in &receipt.artifacts {
        let path = art_dir.join(format!("{}.json", sanitize_filename(&entry.artifact_id)));
        let Ok(raw) = std::fs::read(&path) else {
            continue;
        };
        let Ok(env) = crate::attestation::Envelope::from_json(&raw) else {
            continue;
        };
        let Some(stmt) = env
            .payload_bytes()
            .ok()
            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
        else {
            continue;
        };
        if stmt.get("kind").and_then(|k| k.as_str()) != Some("judgement.v1") {
            continue;
        }
        let Some(p) = stmt.get("payload") else {
            continue;
        };
        total += 1;
        if let Some(m) = p
            .get("judge")
            .and_then(|j| j.get("model"))
            .and_then(|v| v.as_str())
        {
            judges.insert(m.to_string());
        }
        let outcome = p.get("outcome").and_then(|v| v.as_str()).unwrap_or("");
        if let Some(e) = p.get("effect").and_then(|v| v.as_str()) {
            effects.insert(entry.artifact_id.clone(), e.to_string());
        }
        if outcome == "escalated" {
            escalated.push(entry.artifact_id.clone());
        }
        if outcome != "acted" {
            continue;
        }
        let threshold = p
            .get("threshold")
            .and_then(|t| t.get("value"))
            .and_then(|v| v.as_f64());
        let applies_to = p
            .get("threshold")
            .and_then(|t| t.get("applies_to"))
            .and_then(|v| v.as_str())
            .unwrap_or("confidence");
        let answer = p.get("answer");
        let measured = match applies_to {
            "noul" => answer.and_then(|a| a.get("noul")).and_then(|v| v.as_f64()),
            _ => answer
                .and_then(|a| a.get("confidence"))
                .and_then(|v| v.as_f64())
                .or_else(|| answer.and_then(|a| a.get("noul")).and_then(|v| v.as_f64())),
        };
        // What "acted" means depends on the question. On a confidence, the
        // caller acted on the answer, so the confidence must have met the
        // bar. On a yes/no probability the bar cuts both ways: at or above
        // it the answer is "yes" and the caller's effect should be the
        // refusing one (deny or ask); below it the answer is "no" and the
        // effect should be allow or warn. A judgement is outside its bar
        // when the effect contradicts the side of the threshold the answer
        // fell on. A rules judge answering 0.0 to "unsafe?" and the caller
        // proceeding is exactly what the bar asked for, not a violation.
        let effect = p.get("effect").and_then(|v| v.as_str());
        match (threshold, measured) {
            (None, _) => flagged.push(format!(
                "{} acted with no threshold declared",
                entry.artifact_id
            )),
            (Some(t), Some(m)) if applies_to == "noul" => {
                let yes = m >= t;
                let refusing = matches!(effect, Some("deny") | Some("ask"));
                let allowing = matches!(effect, Some("allow") | Some("warn"));
                if yes && allowing {
                    flagged.push(format!(
                        "{} acted to {} at noul {m:.3}, at or above its threshold {t:.3} (the answer was yes)",
                        entry.artifact_id,
                        effect.unwrap_or("")
                    ));
                } else if !yes && refusing {
                    flagged.push(format!(
                        "{} acted to {} at noul {m:.3}, below its threshold {t:.3} (the answer was no)",
                        entry.artifact_id,
                        effect.unwrap_or("")
                    ));
                } else if effect.is_none() && !yes {
                    flagged.push(format!(
                        "{} acted at noul {m:.3} below its threshold {t:.3} with no effect recorded",
                        entry.artifact_id
                    ));
                }
            }
            (Some(t), Some(m)) if m < t => flagged.push(format!(
                "{} acted at {applies_to} {m:.3} below its threshold {t:.3}",
                entry.artifact_id
            )),
            (Some(t), None) => flagged.push(format!(
                "{} acted against a threshold of {t:.3} on {applies_to} but the answer carries no {applies_to}",
                entry.artifact_id
            )),
            _ => {}
        }
    }
    if total == 0 {
        return None;
    }
    let who = judges.into_iter().collect::<Vec<_>>().join(", ");
    // Escalations: resolved by whom, or still open. A human's decision is a
    // separate signed artifact, so "the human overrode this" is a claim the
    // human made, not a field the machine filled in.
    let resolved: Vec<String> = escalated
        .iter()
        .filter_map(|j| {
            resolutions.get(j).map(|(by, d, o)| {
                format!(
                    "{j} {d} by {by}{}",
                    if *o { " (overriding the judge)" } else { "" }
                )
            })
        })
        .collect();
    let open: Vec<&String> = escalated
        .iter()
        .filter(|j| !resolutions.contains_key(*j))
        .collect();
    let overrides: Vec<String> = resolutions
        .iter()
        .filter(|(j, (_, _, o))| *o && !escalated.contains(j))
        .map(|(j, (by, d, _))| {
            format!(
                "{j} ({}) {d} by {by}",
                effects.get(j).cloned().unwrap_or_default()
            )
        })
        .collect();
    let mut tail = String::new();
    if !escalated.is_empty() {
        tail.push_str(&format!(
            "; {} escalated, {} resolved{}{}",
            escalated.len(),
            resolved.len(),
            if resolved.is_empty() {
                String::new()
            } else {
                format!(" ({})", resolved.join(", "))
            },
            if open.is_empty() {
                String::new()
            } else {
                format!(
                    ", {} OPEN with no signed resolution in this package: {}",
                    open.len(),
                    open.iter()
                        .map(|s| s.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            },
        ));
    }
    if !overrides.is_empty() {
        tail.push_str(&format!(
            "; {} judge decision(s) overridden by a signed resolution: {}",
            overrides.len(),
            overrides.join(", ")
        ));
    }
    if flagged.is_empty() && open.is_empty() {
        Some(VerifyCheck::pass(
            "judgements",
            &format!(
                "{total} judgement(s) by {who}; every one acted on met its declared threshold{tail}. The row reads the caller's record; it does not re-run a judge"
            ),
        ))
    } else if flagged.is_empty() {
        Some(VerifyCheck::warn(
            "judgements",
            &format!(
                "{total} judgement(s) by {who}; every one acted on met its declared threshold{tail}"
            ),
        ))
    } else {
        Some(VerifyCheck::warn(
            "judgements",
            &format!(
                "{total} judgement(s) by {who}; {} acted on outside its own bar: {}{tail}",
                flagged.len(),
                flagged.join("; ")
            ),
        ))
    }
}

#[cfg(test)]
mod signed_scope_tests {
    use super::signed_max_actions;

    #[test]
    fn max_actions_is_read_exactly_or_refused_never_truncated() {
        let scope = |m: serde_json::Value| serde_json::json!({"scope": {"maxActions": m}});
        assert_eq!(signed_max_actions(None), Ok(None));
        assert_eq!(signed_max_actions(Some(&serde_json::json!({}))), Ok(None));
        assert_eq!(
            signed_max_actions(Some(&scope(serde_json::json!(1)))),
            Ok(Some(1))
        );
        assert_eq!(
            signed_max_actions(Some(&scope(serde_json::json!(u32::MAX)))),
            Ok(Some(u32::MAX))
        );
        // 2^32 + 1 used to truncate to 1.
        let big = u64::from(u32::MAX) + 2;
        let err = signed_max_actions(Some(&scope(serde_json::json!(big)))).unwrap_err();
        assert!(err.contains("beyond the supported range"), "{err}");
        let err = signed_max_actions(Some(&scope(serde_json::json!("3")))).unwrap_err();
        assert!(err.contains("not a whole number"), "{err}");
        let err = signed_max_actions(Some(&scope(serde_json::json!(-1)))).unwrap_err();
        assert!(err.contains("not a whole number"), "{err}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::event::*;
    use crate::session::manifest::SessionManifest;
    use crate::session::receipt::{ArtifactEntry, ReceiptComposer};

    fn make_receipt() -> SessionReceipt {
        let manifest = SessionManifest::new(
            "ssn_pkg_test".into(),
            "agent://test".into(),
            "2026-04-05T08:00:00Z".into(),
            1743843600000,
        );

        let mk = |seq: u64, inst: &str, et: EventType| -> SessionEvent {
            SessionEvent {
                session_id: "ssn_pkg_test".into(),
                event_id: format!("evt_{:016x}", seq),
                timestamp: format!("2026-04-05T08:{:02}:00Z", seq),
                sequence_no: seq,
                trace_id: "trace_1".into(),
                span_id: format!("span_{seq}"),
                parent_span_id: None,
                agent_id: format!("agent://{inst}"),
                agent_instance_id: inst.into(),
                agent_name: inst.into(),
                agent_role: None,
                host_id: "host_1".into(),
                tool_runtime_id: None,
                event_type: et,
                artifact_ref: None,
                meta: None,
            }
        };

        let events = vec![
            mk(0, "root", EventType::SessionStarted),
            mk(
                1,
                "root",
                EventType::AgentStarted {
                    parent_agent_instance_id: None,
                },
            ),
            mk(
                2,
                "root",
                EventType::AgentCalledTool {
                    tool_name: "read_file".into(),
                    tool_input_digest: None,
                    tool_output_digest: None,
                    duration_ms: Some(10),
                },
            ),
            mk(
                3,
                "root",
                EventType::AgentCompleted {
                    termination_reason: None,
                },
            ),
            mk(
                4,
                "root",
                EventType::SessionClosed {
                    summary: Some("Done".into()),
                    duration_ms: Some(60000),
                },
            ),
        ];

        let artifacts = vec![ArtifactEntry {
            artifact_id: "art_001".into(),
            payload_type: "action".into(),
            digest: None,
            signed_at: None,
            unchained: false,
        }];

        ReceiptComposer::compose(&manifest, &events, artifacts)
    }

    #[test]
    fn build_and_read_package() {
        let receipt = make_receipt();
        let tmp = std::env::temp_dir().join(format!("treeship-pkg-test-{}", rand::random::<u32>()));

        let output = build_package(&receipt, &tmp).unwrap();
        assert!(output.path.exists());
        assert!(output.path.join("receipt.json").exists());
        assert!(output.path.join("merkle.json").exists());
        assert!(output.path.join("render.json").exists());
        assert!(output.path.join("preview.html").exists());
        assert!(output.receipt_digest.starts_with("sha256:"));
        assert!(output.file_count >= 4);

        // Read back
        let read_back = read_package(&output.path).unwrap();
        assert_eq!(read_back.session.id, "ssn_pkg_test");
        assert_eq!(read_back.type_, RECEIPT_TYPE);

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn verify_valid_package() {
        let receipt = make_receipt();
        let tmp =
            std::env::temp_dir().join(format!("treeship-pkg-verify-{}", rand::random::<u32>()));

        let output = build_package(&receipt, &tmp).unwrap();
        let checks = verify_package_structural(&output.path).unwrap();

        let fails: Vec<_> = checks
            .iter()
            .filter(|c| c.status == VerifyStatus::Fail)
            .collect();
        assert!(fails.is_empty(), "unexpected failures: {fails:?}");

        let passes: Vec<_> = checks
            .iter()
            .filter(|c| c.status == VerifyStatus::Pass)
            .collect();
        assert!(
            passes.len() >= 5,
            "expected at least 5 pass checks, got {}",
            passes.len()
        );

        let _ = std::fs::remove_dir_all(&tmp);
    }

    // AUD-07: a receipt stamped reconcile_degraded must surface a WARN on
    // verify, so a consumer is told the file ledger may be incomplete rather
    // than reading the package as a clean, complete audit trail.
    #[test]
    fn verify_warns_when_reconcile_degraded() {
        let mut receipt = make_receipt();
        receipt.proofs.reconcile_degraded = true;
        let tmp =
            std::env::temp_dir().join(format!("treeship-pkg-degraded-{}", rand::random::<u32>()));

        let output = build_package(&receipt, &tmp).unwrap();
        let checks = verify_package_structural(&output.path).unwrap();

        let warned = checks
            .iter()
            .any(|c| c.name == "reconcile_degraded" && c.status == VerifyStatus::Warn);
        assert!(warned, "expected a reconcile_degraded WARN, got {checks:?}");
        // It is a WARN, not a hard fail (the signatures/Merkle are still valid).
        let fails: Vec<_> = checks
            .iter()
            .filter(|c| c.status == VerifyStatus::Fail)
            .collect();
        assert!(fails.is_empty(), "must not hard-fail: {fails:?}");

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn verify_no_degraded_warn_when_clean() {
        // The default receipt has reconcile_degraded=false: no such WARN.
        let receipt = make_receipt();
        let tmp =
            std::env::temp_dir().join(format!("treeship-pkg-clean-{}", rand::random::<u32>()));
        let output = build_package(&receipt, &tmp).unwrap();
        let checks = verify_package_structural(&output.path).unwrap();
        assert!(
            !checks.iter().any(|c| c.name == "reconcile_degraded"),
            "clean receipt must not emit a reconcile_degraded check"
        );
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn verify_detects_missing_receipt() {
        let tmp =
            std::env::temp_dir().join(format!("treeship-pkg-empty-{}", rand::random::<u32>()));
        std::fs::create_dir_all(&tmp).unwrap();

        let err = read_package(&tmp);
        assert!(err.is_err());

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn preview_html_renders_approval_evidence_from_the_bundle() {
        // The package embeds consumed approvals under approvals/ (that is what
        // `package verify` checks as replay-local-journal). The preview must
        // show them too: a reader saw "No approval gates recorded" on a
        // session whose approval was minted, spent once, and verified.
        use crate::attestation::sign::sign;
        use crate::attestation::Ed25519Signer;
        use crate::statements::ApprovalScope;
        use crate::statements::TYPE_APPROVAL_USE;

        let receipt = make_receipt();
        assert_eq!(preview_approvals_json(None), serde_json::Value::Null);
        assert_eq!(
            preview_approvals_json(Some(&ApprovalsBundle::default())),
            serde_json::Value::Null,
            "an empty bundle is the same as none"
        );

        let signer = Ed25519Signer::generate("key_test_preview").unwrap();
        let mut grant = ApprovalStatement::new("human://operator", "nonce-preview-0001");
        grant.description = Some("apply change chg-0001: 3% clearance".into());
        grant.scope = Some(ApprovalScope {
            max_actions: Some(1),
            valid_until: None,
            allowed_actors: vec!["agent://merchant".into()],
            allowed_actions: vec!["commerce.tool.apply_change.intent".into()],
            allowed_subjects: vec!["change://chg-0001".into()],
            extra: None,
        });
        let signed = sign("application/vnd.treeship.approval.v1+json", &grant, &signer).unwrap();
        let grant_id = signed.artifact_id.to_string();
        let grant_bytes = serde_json::to_vec(&signed.envelope).unwrap();

        let use_record = ApprovalUse {
            type_: TYPE_APPROVAL_USE.into(),
            use_id: "use_preview_0001".into(),
            grant_id: grant_id.clone(),
            grant_digest: signed.digest.clone(),
            nonce_digest: "sha256:00".into(),
            actor: "agent://merchant".into(),
            action: "commerce.tool.apply_change.intent".into(),
            subject: "change://chg-0001".into(),
            session_id: Some("ssn_pkg_test".into()),
            action_artifact_id: Some("art_apply_intent".into()),
            receipt_digest: None,
            use_number: 1,
            max_uses: Some(1),
            idempotency_key: None,
            created_at: "2026-09-07T10:45:49Z".into(),
            expires_at: None,
            previous_record_digest: String::new(),
            record_digest: String::new(),
            signature: None,
            signature_alg: None,
            signing_key_id: None,
        };
        let bundle = ApprovalsBundle {
            grants: vec![
                (grant_id.clone(), grant_bytes),
                ("art_garbage".into(), b"not json".to_vec()),
            ],
            uses: vec![use_record],
            ..Default::default()
        };

        let summary = preview_approvals_json(Some(&bundle));
        let grants = summary["grants"].as_array().unwrap();
        assert_eq!(grants.len(), 2);
        assert_eq!(grants[0]["parsed"], true);
        assert_eq!(grants[0]["approver"], "human://operator");
        assert_eq!(grants[0]["scope"]["max_uses"], 1);
        assert_eq!(
            grants[0]["scope"]["allowed_subjects"][0],
            "change://chg-0001"
        );
        // An unparsable grant is listed, not dropped, and says so.
        assert_eq!(grants[1]["parsed"], false);
        assert_eq!(grants[1]["grant_id"], "art_garbage");
        let uses = summary["uses"].as_array().unwrap();
        assert_eq!(uses[0]["use_number"], 1);
        assert_eq!(uses[0]["action_artifact_id"], "art_apply_intent");

        let html = render_preview_html_with_approvals(&receipt, Some(&bundle));
        assert!(html.contains("id=\"approvals-data\""));
        assert!(html.contains("\"approver\":\"human://operator\""));
        assert!(html.contains("\"subject\":\"change://chg-0001\""));
        assert!(
            !html.contains("__APPROVALS_JSON__"),
            "placeholder must be substituted"
        );
        // Without a bundle the data block is a JSON null, never an empty
        // string that would throw in JSON.parse and hide the whole page.
        let plain = render_preview_html(&receipt);
        assert!(plain.contains("type=\"application/json\">null</script>"));
    }

    #[test]
    fn preview_html_contains_session_info() {
        let receipt = make_receipt();
        let html = render_preview_html(&receipt);
        assert!(html.contains("ssn_pkg_test"));
        assert!(html.contains("treeship.dev"));
        assert!(html.contains("Timeline"));

        // Regression: the receipt JSON must land ONLY in the data block,
        // never in the inline JS. A prior bug used replace() (all matches)
        // against a template that carried the placeholder token twice (data
        // slot + a JS placeholder check), injecting the receipt body into a
        // JS string literal. That produced an uncaught SyntaxError, so the
        // whole script never ran and the preview hung on "Verifying
        // receipt...". The JS check now uses a split sentinel that must
        // survive substitution verbatim, and replacen(.., 1) fills only the
        // first occurrence.
        assert!(
            html.contains("'__RECEIPT'+'_JSON__'"),
            "JS placeholder check was clobbered by the receipt substitution",
        );
        assert!(
            !html.contains("application/json\">__RECEIPT_JSON__</script>"),
            "data slot was not substituted with the receipt JSON",
        );
        // The session id (a receipt value) must appear inside the data block,
        // not leak into executable JS, so a quick structural sanity check:
        // there is exactly one unsubstituted token left at most (none here).
        assert_eq!(
            html.matches("__RECEIPT_JSON__").count(),
            0,
            "no raw placeholder token should remain after substitution",
        );
    }
}