eggpack-github 0.1.2

GitHub draft release staging adapter and local staging payload materializer
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
//! GitHub draft release staging adapter and local staging payload materializer.
//!
//! M003a owns two bounded capabilities: materialize a complete local staging
//! payload from M004 finalization plus `ReleaseManifest` plus deterministic
//! bootstrap generators, and reconcile that payload into a GitHub draft
//! release through a provider-specific adapter. There is no publication
//! authority, no tag creation/move/delete, and no `publish` endpoint.

#![forbid(unsafe_code)]
#![deny(missing_docs)]

use eggpack_bootstrap::{BootstrapInstallPolicyV1, BootstrapSpec};
use eggpack_contract::{DistributionContract, ExpandedAssets};
use eggpack_manifest::ReleaseManifest;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::{Component, Path, PathBuf};
use std::sync::Mutex;

const API_BASE: &str = "https://api.github.com";
const UPLOAD_BASE: &str = "https://uploads.github.com";
const API_VERSION: &str = "2026-03-10";
const USER_AGENT: &str = "eggpack-github/0.1.0";
const MAX_TAG_PEEL_DEPTH: usize = 8;
const MAX_POLICY_JSON: usize = 256 * 1024;
const RELEASE_IDENTITY_SCHEMA_VERSION: u32 = 1;
const MAX_PAYLOAD_JSON: usize = 1_048_576;
const MAX_BODY_NOTES: usize = 65_536;
const MAX_TITLE: usize = 256;
const MAX_NAME_SEGMENT: usize = 128;
const FIXED_MANIFEST_NAME: &str = "release-manifest.json";
const FIXED_POSIX_NAME: &str = "install.sh";
const FIXED_POWERSHELL_NAME: &str = "install.ps1";
/// Maximum upload read/write chunk, bounding per-asset transfer memory.
const UPLOAD_CHUNK_BYTES: usize = 64 * 1024;
/// GitHub's fixed page size for both the release and asset listings.
const LIST_PAGE_SIZE: usize = 100;

/// Bounded staging failure with redacted diagnostics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GithubError(String);

impl fmt::Display for GithubError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

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

fn fail(message: impl Into<String>) -> GithubError {
    GithubError(message.into())
}

/// Finite producer mapping from an immutable source tag to manifest identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReleaseIdentityMode {
    /// Preserve the historical opaque tag as the manifest release id.
    ExactTag,
    /// Map exactly `vMAJOR.MINOR.PATCH` to `MAJOR.MINOR.PATCH`.
    VPrefixedStableSemver,
}

impl ReleaseIdentityMode {
    /// Resolve the finite manifest identity for one validated source tag.
    pub fn release_id(self, tag: &str) -> Result<String, GithubError> {
        validate_tag(tag)?;
        match self {
            Self::ExactTag => Ok(tag.to_owned()),
            Self::VPrefixedStableSemver => {
                let version = tag
                    .strip_prefix('v')
                    .ok_or_else(|| fail("stable semantic tag must start with v"))?;
                let parts: Vec<&str> = version.split('.').collect();
                if parts.len() != 3
                    || parts.iter().any(|part| {
                        part.is_empty()
                            || !part.bytes().all(|byte| byte.is_ascii_digit())
                            || (part.len() > 1 && part.starts_with('0'))
                            || part.parse::<u64>().is_err()
                    })
                {
                    return Err(fail("tag is not v-prefixed stable semantic version"));
                }
                Ok(version.to_owned())
            }
        }
    }
}

/// Strict draft staging policy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GitHubDraftPolicyV1 {
    /// Schema version, exactly 1.
    pub schema_version: u32,
    /// GitHub repository owner.
    pub owner: String,
    /// GitHub repository name.
    pub repository: String,
    /// Exact existing tag to stage.
    pub tag: String,
    /// Version of the optional mapped-identity tuple; absent in legacy mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_identity_schema_version: Option<u32>,
    /// Opt-in identity mode. Absent preserves historical exact-tag JSON.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_identity_mode: Option<ReleaseIdentityMode>,
    /// Mapped manifest identity. Present exactly when the opt-in mode is used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_id: Option<String>,
    /// Checked-out source revision bound by runtime identity resolution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_revision: Option<String>,
    /// Draft release title.
    pub title: String,
    /// Bounded release notes body.
    #[serde(default)]
    pub body: String,
    /// Prerelease intent.
    #[serde(default)]
    pub prerelease: bool,
    /// Token environment variable name, allowlisted to `GITHUB_TOKEN`.
    #[serde(default = "default_token_env")]
    pub token_env: String,
    /// Per-request timeout in seconds.
    #[serde(default = "default_timeout_secs")]
    pub request_timeout_secs: u64,
    /// Maximum metadata response bytes.
    #[serde(default = "default_max_metadata_bytes")]
    pub max_metadata_bytes: usize,
    /// Maximum bounded release-list pages.
    #[serde(default = "default_max_list_pages")]
    pub max_list_pages: u32,
}

fn default_token_env() -> String {
    "GITHUB_TOKEN".to_owned()
}

fn default_timeout_secs() -> u64 {
    30
}

fn default_max_metadata_bytes() -> usize {
    1_000_000
}

fn default_max_list_pages() -> u32 {
    16
}

impl GitHubDraftPolicyV1 {
    /// Parse strict bounded JSON policy.
    pub fn from_json(text: &str) -> Result<Self, GithubError> {
        if text.len() > MAX_POLICY_JSON {
            return Err(fail("github draft policy exceeds size bound"));
        }
        let value: Self =
            serde_json::from_str(text).map_err(|_| fail("invalid github draft policy JSON"))?;
        value.validate()?;
        Ok(value)
    }

    /// Serialize deterministically after validation.
    pub fn to_json(&self) -> Result<String, GithubError> {
        self.validate()?;
        serde_json::to_string(self).map_err(|_| fail("github draft policy encode failed"))
    }

    /// Validate all bounds and injection rules.
    pub fn validate(&self) -> Result<(), GithubError> {
        if self.schema_version != 1 {
            return Err(fail("unsupported github draft policy version"));
        }
        validate_owner(&self.owner)?;
        validate_repo(&self.repository)?;
        validate_tag(&self.tag)?;
        match (
            self.release_identity_schema_version,
            self.release_identity_mode,
            self.release_id.as_deref(),
            self.source_revision.as_deref(),
        ) {
            (None, None, None, None) => {}
            (
                Some(RELEASE_IDENTITY_SCHEMA_VERSION),
                Some(mode),
                Some(release_id),
                Some(_revision),
            ) if mode
                .release_id(&self.tag)
                .is_ok_and(|expected| expected == release_id) => {}
            _ => {
                return Err(fail(
                    "draft identity envelope is incomplete or inconsistent",
                ))
            }
        }
        if let Some(revision) = self.source_revision.as_deref() {
            if revision.len() != 40
                || !revision
                    .bytes()
                    .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
            {
                return Err(fail("draft source revision is invalid"));
            }
        }
        validate_title(&self.title)?;
        validate_body(&self.body)?;
        if self.token_env != "GITHUB_TOKEN" {
            return Err(fail("token env must be GITHUB_TOKEN"));
        }
        if !(5..=120).contains(&self.request_timeout_secs) {
            return Err(fail("request timeout out of bounds"));
        }
        if self.max_metadata_bytes == 0 || self.max_metadata_bytes > 8_000_000 {
            return Err(fail("max metadata bytes out of bounds"));
        }
        if self.max_list_pages == 0 || self.max_list_pages > 32 {
            return Err(fail("max list pages out of bounds"));
        }
        Ok(())
    }

    /// Exact release download origin for bootstrap installers.
    pub fn download_origin(&self) -> String {
        format!(
            "https://github.com/{}/{}/releases/download/{}",
            self.owner, self.repository, self.tag
        )
    }

    /// Manifest id bound by this policy, preserving legacy exact-tag policy.
    pub fn resolved_release_id(&self) -> &str {
        self.release_id.as_deref().unwrap_or(&self.tag)
    }
}

/// Semantic kind of one staged file.
///
/// M003d compatibility: the payload schema remains v1. `GeneratedDefault`
/// payloads use exactly the M003a kind set, so existing v1 readers parse
/// them unchanged. `ProductWrappers` payloads additionally use
/// `ProductPosixWrapper` / `ProductPowershellWrapper`; v1 readers that do
/// not know those variants reject such payloads (fail-closed) rather than
/// silently reinterpreting them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StagingAssetKind {
    /// Finalized M004 artifact bytes.
    FinalizedArtifact,
    /// Checksum sidecar for a finalized artifact.
    ChecksumSidecar,
    /// Standalone deterministic release manifest.
    ReleaseManifest,
    /// Deterministic POSIX installer.
    PosixInstaller,
    /// Deterministic PowerShell installer.
    PowershellInstaller,
    /// Consumer-owned POSIX wrapper copied exactly from the verified source
    /// tree and staged as the public `install.sh` (M003d only).
    ProductPosixWrapper,
    /// Consumer-owned PowerShell wrapper copied exactly from the verified
    /// source tree and staged as the public `install.ps1` (M003d only).
    ProductPowershellWrapper,
}

/// One ordered staged file record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StagingAsset {
    /// Safe flat asset name.
    pub name: String,
    /// Local relative path under payload root (flat, equals name).
    pub path: String,
    /// Exact byte size.
    pub size: u64,
    /// Lowercase SHA-256 hex.
    pub sha256: String,
    /// Media type for upload.
    pub media_type: String,
    /// Semantic kind.
    pub kind: StagingAssetKind,
}

/// Deterministic local staging payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StagingPayloadV1 {
    /// Schema version, exactly 1.
    pub schema_version: u32,
    /// Product id from manifest.
    pub product_id: String,
    /// Release id from manifest.
    pub release_id: String,
    /// Source revision from manifest.
    pub source_revision: String,
    /// Repository owner.
    pub owner: String,
    /// Repository name.
    pub repository: String,
    /// Exact existing tag.
    pub tag: String,
    /// Draft title.
    pub title: String,
    /// Prerelease intent.
    pub prerelease: bool,
    /// Bounded release notes.
    pub body: String,
    /// Ordered asset records sorted by name.
    pub assets: Vec<StagingAsset>,
}

impl StagingPayloadV1 {
    /// Parse strict bounded JSON payload.
    pub fn from_json(text: &str) -> Result<Self, GithubError> {
        if text.len() > MAX_PAYLOAD_JSON {
            return Err(fail("staging payload exceeds size bound"));
        }
        let value: Self =
            serde_json::from_str(text).map_err(|_| fail("invalid staging payload JSON"))?;
        value.validate()?;
        Ok(value)
    }

    /// Serialize deterministically after validation.
    pub fn to_json(&self) -> Result<String, GithubError> {
        self.validate()?;
        let mut canonical = self.clone();
        canonical.assets.sort_by(|a, b| a.name.cmp(&b.name));
        serde_json::to_string(&canonical).map_err(|_| fail("staging payload encode failed"))
    }

    /// Validate bounds, paths, digests, and ordering.
    pub fn validate(&self) -> Result<(), GithubError> {
        if self.schema_version != 1 {
            return Err(fail("unsupported staging payload version"));
        }
        if self.product_id.is_empty()
            || self.product_id.len() > MAX_NAME_SEGMENT
            || self.release_id.is_empty()
            || self.release_id.len() > MAX_NAME_SEGMENT
            || self.source_revision.is_empty()
            || self.source_revision.len() > MAX_NAME_SEGMENT
        {
            return Err(fail("staging payload identity out of bounds"));
        }
        validate_owner(&self.owner)?;
        validate_repo(&self.repository)?;
        validate_tag(&self.tag)?;
        validate_title(&self.title)?;
        validate_body(&self.body)?;
        if self.assets.is_empty() || self.assets.len() > 1024 {
            return Err(fail("staging payload asset count out of bounds"));
        }
        let mut seen = BTreeSet::new();
        for asset in &self.assets {
            validate_asset_name(&asset.name)?;
            validate_relative_path(&asset.path)?;
            if asset.path != asset.name {
                return Err(fail("staging payload path must equal flat asset name"));
            }
            if asset.size == 0 {
                return Err(fail("staging asset size must be non-zero"));
            }
            validate_sha256(&asset.sha256)?;
            if asset.media_type.is_empty() || asset.media_type.len() > 128 {
                return Err(fail("staging asset media type out of bounds"));
            }
            if !seen.insert(asset.name.to_ascii_lowercase()) {
                return Err(fail("duplicate staging asset name"));
            }
        }
        Ok(())
    }
}

/// Bounded staging receipt (producer evidence, not an install receipt).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GitHubDraftReceiptV1 {
    /// Schema version, exactly 1.
    pub schema_version: u32,
    /// Repository owner.
    pub owner: String,
    /// Repository name.
    pub repository: String,
    /// Product release id.
    pub release_id: String,
    /// Exact tag.
    pub tag: String,
    /// Source revision.
    pub source_revision: String,
    /// GitHub numeric release id.
    pub github_release_id: u64,
    /// Draft state, always true.
    pub draft: bool,
    /// Immutable state, always false for staged drafts.
    pub immutable: bool,
    /// Ordered asset names.
    pub assets: Vec<StagingAsset>,
    /// True when the release was created by this invocation.
    pub created: bool,
    /// Count of uploaded assets.
    pub uploaded: u32,
    /// Count of reused exact assets.
    pub reused: u32,
}

impl GitHubDraftReceiptV1 {
    /// Parse strict bounded JSON receipt.
    pub fn from_json(text: &str) -> Result<Self, GithubError> {
        if text.len() > MAX_PAYLOAD_JSON {
            return Err(fail("staging receipt exceeds size bound"));
        }
        let value: Self =
            serde_json::from_str(text).map_err(|_| fail("invalid staging receipt JSON"))?;
        value.validate()?;
        Ok(value)
    }

    /// Serialize after validation.
    pub fn to_json(&self) -> Result<String, GithubError> {
        self.validate()?;
        serde_json::to_string(self).map_err(|_| fail("staging receipt encode failed"))
    }

    /// Validate receipt shape.
    pub fn validate(&self) -> Result<(), GithubError> {
        if self.schema_version != 1 {
            return Err(fail("unsupported staging receipt version"));
        }
        validate_owner(&self.owner)?;
        validate_repo(&self.repository)?;
        validate_tag(&self.tag)?;
        if !self.draft || self.immutable {
            return Err(fail("receipt must describe a mutable draft"));
        }
        if self.assets.is_empty() || self.assets.len() > 1024 {
            return Err(fail("receipt asset count out of bounds"));
        }
        if self
            .uploaded
            .checked_add(self.reused)
            .is_none_or(|total| total as usize != self.assets.len())
        {
            return Err(fail("receipt upload/reuse counts must cover assets"));
        }
        Ok(())
    }
}

fn validate_owner(value: &str) -> Result<(), GithubError> {
    if value.is_empty() || value.len() > 64 {
        return Err(fail("owner out of bounds"));
    }
    if value.chars().any(char::is_control) {
        return Err(fail("owner contains control characters"));
    }
    if !value
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
    {
        return Err(fail("owner contains unsupported characters"));
    }
    if value.starts_with('-') || value.ends_with('-') || value.contains("..") {
        return Err(fail("owner has unsafe shape"));
    }
    Ok(())
}

fn validate_repo(value: &str) -> Result<(), GithubError> {
    if value.is_empty() || value.len() > 64 {
        return Err(fail("repository out of bounds"));
    }
    if value.chars().any(char::is_control) {
        return Err(fail("repository contains control characters"));
    }
    if !value
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
    {
        return Err(fail("repository contains unsupported characters"));
    }
    if value.contains("..") {
        return Err(fail("repository has unsafe shape"));
    }
    Ok(())
}

fn validate_tag(value: &str) -> Result<(), GithubError> {
    // The canonical exact-tag safety rule is owned by `eggpack-core`; this
    // crate keeps its own diagnostic wording for each refusal class.
    eggpack_core::validate_exact_tag_safety(value).map_err(|error| {
        fail(match error {
            eggpack_core::ExactTagSafetyError::OutOfBounds => "tag out of bounds",
            eggpack_core::ExactTagSafetyError::ControlCharacters => {
                "tag contains control characters"
            }
            eggpack_core::ExactTagSafetyError::QueryOrInjectionCharacters => {
                "tag contains query/injection characters"
            }
            eggpack_core::ExactTagSafetyError::UnsafePathShape => "tag has unsafe path shape",
            eggpack_core::ExactTagSafetyError::UnsafeGitRefPath => {
                "tag has unsafe git ref path shape"
            }
        })
    })
}

fn validate_title(value: &str) -> Result<(), GithubError> {
    if value.is_empty() || value.len() > MAX_TITLE {
        return Err(fail("title out of bounds"));
    }
    if value.chars().any(char::is_control) {
        return Err(fail("title contains control characters"));
    }
    Ok(())
}

fn validate_body(value: &str) -> Result<(), GithubError> {
    if value.len() > MAX_BODY_NOTES {
        return Err(fail("release notes exceed bound"));
    }
    if value.chars().any(|c| c == '\0') {
        return Err(fail("release notes contain NUL"));
    }
    Ok(())
}

fn validate_asset_name(value: &str) -> Result<(), GithubError> {
    if value.is_empty() || value.len() > 255 {
        return Err(fail("asset name out of bounds"));
    }
    if value == "." || value == ".." {
        return Err(fail("asset name is not a safe flat name"));
    }
    if value.contains('/') || value.contains('\\') {
        return Err(fail("asset name must be flat"));
    }
    if value.chars().any(char::is_control) {
        return Err(fail("asset name contains control characters"));
    }
    Ok(())
}

fn validate_relative_path(value: &str) -> Result<(), GithubError> {
    if value.is_empty() || value.len() > 512 {
        return Err(fail("staging path out of bounds"));
    }
    if Path::new(value).is_absolute() {
        return Err(fail("staging path must be relative"));
    }
    if value.contains('\\') {
        return Err(fail("staging path must use flat relative form"));
    }
    let path = Path::new(value);
    for component in path.components() {
        match component {
            Component::Normal(_) => {}
            _ => return Err(fail("staging path contains traversal")),
        }
    }
    validate_asset_name(value)?;
    Ok(())
}

fn validate_sha256(value: &str) -> Result<(), GithubError> {
    // The SHA-256 hex acceptance set is owned by `eggpack-manifest`
    // (ADR-0006); this crate applies it rather than restating it.
    eggpack_manifest::validate_sha256_hex(value).map_err(|error| {
        fail(match error {
            eggpack_manifest::Sha256Error::AllZeros => "sha256 must not be the all-zeros digest",
            _ => "sha256 must be 64 lowercase hex characters",
        })
    })
}

/// Read a credential from the environment without logging it.
pub fn read_token(env_name: &str) -> Result<String, GithubError> {
    if env_name != "GITHUB_TOKEN" {
        return Err(fail("token env must be GITHUB_TOKEN"));
    }
    let value = std::env::var(env_name).map_err(|_| fail("github token is absent"))?;
    if value.is_empty() || value.len() > 4096 || value.chars().any(char::is_control) {
        return Err(fail("github token is absent"));
    }
    Ok(value)
}

/// Digest one staging file with the canonical producer file-digest helper.
///
/// The bytes are never held in memory: a finalized release bundle can be far
/// larger than the process should grow to accommodate, and the rest of this
/// crate already streams — `streamed_upload_body` and `verify_file` both read
/// in `UPLOAD_CHUNK_BYTES` chunks. Peak memory here is therefore independent
/// of artifact size.
///
/// The digest rule itself is owned by `eggpack-core`; this wrapper only keeps
/// the crate's own staging diagnostic wording.
fn digest_file(path: &Path) -> Result<(u64, String), GithubError> {
    eggpack_core::file_digest(path).map_err(|error| fail(staging_digest_message(error)))
}

/// Map a canonical file-digest refusal to this crate's staging diagnostic.
fn staging_digest_message(error: eggpack_core::DigestError) -> &'static str {
    match error {
        eggpack_core::DigestError::Unavailable => "staging file is unavailable",
        eggpack_core::DigestError::NotRegularFile | eggpack_core::DigestError::Empty => {
            "staging file must be a non-empty regular file"
        }
        eggpack_core::DigestError::OpenFailed | eggpack_core::DigestError::ReadFailed => {
            "staging file cannot be read"
        }
        eggpack_core::DigestError::SizeOverflow => "staging file size exceeds the platform bound",
        eggpack_core::DigestError::ChangedDuringRead => "staging file changed during read",
    }
}

fn reject_symlink_dir(path: &Path, label: &str) -> Result<(), GithubError> {
    let metadata =
        std::fs::symlink_metadata(path).map_err(|_| fail(format!("{label} is unavailable")))?;
    if metadata.file_type().is_symlink() || !metadata.is_dir() {
        return Err(fail(format!("{label} is not a real directory")));
    }
    Ok(())
}

fn ensure_absent_private_dir(path: &Path, label: &str) -> Result<(), GithubError> {
    if std::fs::symlink_metadata(path).is_ok() {
        return Err(fail(format!("{label} must be absent")));
    }
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."));
    reject_symlink_dir(&parent, "output parent")?;
    std::fs::create_dir(path).map_err(|_| fail(format!("{label} could not be created")))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
            .map_err(|_| fail(format!("{label} permissions could not be restricted")))?;
    }
    Ok(())
}

/// Materialize a complete deterministic staging payload.
///
/// The finalized root is revalidated against the contract and manifest; exact
/// finalized assets are copied into a private staging directory alongside a
/// standalone `release-manifest.json` and deterministic bootstrap installers.
///
/// This is the generated-default installer presentation. It is the same
/// single implementation that serves
/// [`prepare_staging_payload_with_presentation`], with the presentation
/// selected as an argument.
#[allow(clippy::too_many_arguments)]
pub fn prepare_staging_payload(
    contract: &DistributionContract,
    manifest: &ReleaseManifest,
    finalized_root: &Path,
    policy: &GitHubDraftPolicyV1,
    install_policy: &BootstrapInstallPolicyV1,
    output_dir: &Path,
) -> Result<StagingPayloadV1, GithubError> {
    prepare_staging_payload_with_presentation_inner(
        contract,
        manifest,
        finalized_root,
        policy,
        install_policy,
        &InstallerPresentationV1::generated_default(),
        None,
        output_dir,
    )
}

/// Materialize a staging payload with an explicit installer presentation.
///
/// The presentation selects only the installer surface. Every other step —
/// validation, inventory construction, sidecars, installers, digest loop,
/// canonical sort, and payload assembly — is one implementation, shared with
/// [`prepare_staging_payload`].
#[allow(clippy::too_many_arguments)]
pub fn prepare_staging_payload_with_presentation(
    contract: &DistributionContract,
    manifest: &ReleaseManifest,
    finalized_root: &Path,
    policy: &GitHubDraftPolicyV1,
    install_policy: &BootstrapInstallPolicyV1,
    presentation: &InstallerPresentationV1,
    source_root: &Path,
    output_dir: &Path,
) -> Result<StagingPayloadV1, GithubError> {
    prepare_staging_payload_with_presentation_inner(
        contract,
        manifest,
        finalized_root,
        policy,
        install_policy,
        presentation,
        Some(source_root),
        output_dir,
    )
}

// ---------------------------------------------------------------------------
// M003d — installer presentation policy and static draft template.
// ---------------------------------------------------------------------------

/// Maximum product wrapper source bytes (1 MiB per wrapper, M003d section 6).
pub const MAX_WRAPPER_BYTES: u64 = 1024 * 1024;
const MAX_PRESENTATION_JSON: usize = 64 * 1024;
const MAX_TEMPLATE_JSON: usize = 64 * 1024;
const MAX_TITLE_PREFIX: usize = 128;

/// Strict versioned staging installer policy owned by the staging layer.
///
/// - `GeneratedDefault` preserves M003a behavior byte-for-byte: generated
///   exact-release installers are staged as the public `install.sh` /
///   `install.ps1`.
/// - `ProductWrappers` stages four installer assets: consumer-owned wrapper
///   bytes copied exactly as the public `install.sh` / `install.ps1`, plus
///   Eggpack-generated exact installers under configured non-colliding
///   names (eggsact: `install-exact.sh` / `install-exact.ps1`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstallerPresentationV1 {
    /// Schema version, exactly 1.
    pub schema_version: u32,
    /// Presentation mode.
    pub mode: InstallerPresentationModeV1,
}

/// Installer presentation mode.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum InstallerPresentationModeV1 {
    /// Generated exact installers are the public install surface.
    GeneratedDefault,
    /// Product-owned wrappers are the public install surface.
    ProductWrappers(ProductWrapperSourcesV1),
}

/// Product wrapper source configuration (M003d section 6).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProductWrapperSourcesV1 {
    /// Repository-relative POSIX wrapper source (staged as `install.sh`).
    pub posix_source: String,
    /// Repository-relative PowerShell wrapper source (staged as `install.ps1`).
    pub powershell_source: String,
    /// Staged asset name for the generated exact POSIX installer.
    pub generated_posix_name: String,
    /// Staged asset name for the generated exact PowerShell installer.
    pub generated_powershell_name: String,
}

impl InstallerPresentationV1 {
    /// Generated-default presentation (M003a behavior).
    pub fn generated_default() -> Self {
        Self {
            schema_version: 1,
            mode: InstallerPresentationModeV1::GeneratedDefault,
        }
    }

    /// Parse a strict bounded JSON presentation document.
    pub fn from_json(text: &str) -> Result<Self, GithubError> {
        if text.len() > MAX_PRESENTATION_JSON {
            return Err(fail("installer presentation exceeds size bound"));
        }
        let value: Self =
            serde_json::from_str(text).map_err(|_| fail("invalid installer presentation JSON"))?;
        value.validate()?;
        Ok(value)
    }

    /// Serialize deterministically after validation.
    pub fn to_json(&self) -> Result<String, GithubError> {
        self.validate()?;
        serde_json::to_string(self).map_err(|_| fail("installer presentation encode failed"))
    }

    /// Validate schema version, wrapper paths, and generated names.
    pub fn validate(&self) -> Result<(), GithubError> {
        if self.schema_version != 1 {
            return Err(fail("unsupported installer presentation version"));
        }
        match &self.mode {
            InstallerPresentationModeV1::GeneratedDefault => Ok(()),
            InstallerPresentationModeV1::ProductWrappers(sources) => {
                validate_wrapper_source_path(&sources.posix_source)?;
                validate_wrapper_source_path(&sources.powershell_source)?;
                if sources.posix_source == sources.powershell_source {
                    return Err(fail("product wrapper sources must be distinct files"));
                }
                validate_generated_installer_name(&sources.generated_posix_name)?;
                validate_generated_installer_name(&sources.generated_powershell_name)?;
                if sources
                    .generated_posix_name
                    .eq_ignore_ascii_case(&sources.generated_powershell_name)
                {
                    return Err(fail("generated installer names must not collide"));
                }
                Ok(())
            }
        }
    }
}

fn validate_wrapper_source_path(path: &str) -> Result<(), GithubError> {
    if path.is_empty() || path.len() > 512 || path.contains('\0') || path.contains('\\') {
        return Err(fail("wrapper source is not a bounded relative path"));
    }
    if path.starts_with('/') || path.contains(':') {
        return Err(fail("wrapper source escapes its root"));
    }
    if path.split('/').any(|segment| {
        segment.is_empty() || segment == "." || segment == ".." || segment.len() > 128
    }) {
        return Err(fail("wrapper source escapes its root"));
    }
    if path.chars().any(char::is_control) {
        return Err(fail("wrapper source contains control characters"));
    }
    Ok(())
}

fn validate_generated_installer_name(name: &str) -> Result<(), GithubError> {
    validate_asset_name(name)?;
    let lower = name.to_ascii_lowercase();
    if lower == FIXED_MANIFEST_NAME || lower == FIXED_POSIX_NAME || lower == FIXED_POWERSHELL_NAME {
        return Err(fail(
            "generated installer name collides with a reserved staging name",
        ));
    }
    Ok(())
}

/// Read one product wrapper source exactly (no interpolation, no execution).
///
/// The source root must be a real non-symlink directory; the resolved file
/// must stay beneath it, be a regular non-symlink file, and fit the
/// 1 MiB bound. Bytes are copied exactly.
fn read_wrapper_source(source_root: &Path, relative: &str) -> Result<Vec<u8>, GithubError> {
    reject_symlink_dir(source_root, "wrapper source root")?;
    validate_wrapper_source_path(relative)?;
    let path = source_root.join(relative);
    let metadata =
        std::fs::symlink_metadata(&path).map_err(|_| fail("wrapper source is unavailable"))?;
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        return Err(fail("wrapper source must be a regular file"));
    }
    if metadata.len() == 0 || metadata.len() > MAX_WRAPPER_BYTES {
        return Err(fail("wrapper source size out of bounds"));
    }
    let bytes = std::fs::read(&path).map_err(|_| fail("wrapper source cannot be read"))?;
    if bytes.len() as u64 != metadata.len() {
        return Err(fail("wrapper source changed during read"));
    }
    Ok(bytes)
}

/// Static reusable GitHub draft template (M003d section 4C).
///
/// Contains only identity-independent fields known before the future tag:
/// owner/repository, fixed title prefix, bounded body/notes, prerelease
/// flag, token environment, and transport bounds. It MUST NOT contain a
/// release id, source revision, exact tag, GitHub release id, or digests.
/// Runtime resolution appends the exact validated tag to the title prefix;
/// no arbitrary string templating exists.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GitHubDraftTemplateV1 {
    /// Schema version, exactly 1.
    pub schema_version: u32,
    /// GitHub repository owner.
    pub owner: String,
    /// GitHub repository name.
    pub repository: String,
    /// Fixed title prefix; the exact tag is appended at resolve time.
    pub title_prefix: String,
    /// Bounded fixed release notes.
    #[serde(default)]
    pub body: String,
    /// Prerelease intent.
    #[serde(default)]
    pub prerelease: bool,
    /// Token environment variable name, allowlisted to `GITHUB_TOKEN`.
    #[serde(default = "default_token_env")]
    pub token_env: String,
    /// Per-request timeout in seconds.
    #[serde(default = "default_timeout_secs")]
    pub request_timeout_secs: u64,
    /// Maximum metadata response bytes.
    #[serde(default = "default_max_metadata_bytes")]
    pub max_metadata_bytes: usize,
    /// Maximum bounded release-list pages.
    #[serde(default = "default_max_list_pages")]
    pub max_list_pages: u32,
}

impl GitHubDraftTemplateV1 {
    /// Parse a strict bounded JSON template document.
    pub fn from_json(text: &str) -> Result<Self, GithubError> {
        if text.len() > MAX_TEMPLATE_JSON {
            return Err(fail("github draft template exceeds size bound"));
        }
        let value: Self =
            serde_json::from_str(text).map_err(|_| fail("invalid github draft template JSON"))?;
        value.validate()?;
        Ok(value)
    }

    /// Serialize deterministically after validation.
    pub fn to_json(&self) -> Result<String, GithubError> {
        self.validate()?;
        serde_json::to_string(self).map_err(|_| fail("github draft template encode failed"))
    }

    /// Validate all bounds and injection rules.
    pub fn validate(&self) -> Result<(), GithubError> {
        if self.schema_version != 1 {
            return Err(fail("unsupported github draft template version"));
        }
        validate_owner(&self.owner)?;
        validate_repo(&self.repository)?;
        if self.title_prefix.is_empty()
            || self.title_prefix.len() > MAX_TITLE_PREFIX
            || self.title_prefix.chars().any(char::is_control)
        {
            return Err(fail("draft title prefix out of bounds"));
        }
        validate_body(&self.body)?;
        if self.token_env != "GITHUB_TOKEN" {
            return Err(fail("token env must be GITHUB_TOKEN"));
        }
        if !(5..=120).contains(&self.request_timeout_secs) {
            return Err(fail("request timeout out of bounds"));
        }
        if self.max_metadata_bytes == 0 || self.max_metadata_bytes > 8_000_000 {
            return Err(fail("max metadata bytes out of bounds"));
        }
        if self.max_list_pages == 0 || self.max_list_pages > 32 {
            return Err(fail("max list pages out of bounds"));
        }
        Ok(())
    }

    /// Resolve the static template against one exact validated tag.
    ///
    /// Uses the exact tag as-is (no product-specific transformation) and
    /// appends it to the fixed title prefix. The tag itself is validated
    /// with the same rules as [`GitHubDraftPolicyV1`].
    pub fn resolve(&self, tag: &str) -> Result<GitHubDraftPolicyV1, GithubError> {
        self.validate()?;
        validate_tag(tag)?;
        let title = format!("{}{}", self.title_prefix, tag);
        validate_title(&title)?;
        Ok(GitHubDraftPolicyV1 {
            schema_version: 1,
            owner: self.owner.clone(),
            repository: self.repository.clone(),
            tag: tag.to_owned(),
            release_identity_schema_version: None,
            release_identity_mode: None,
            release_id: None,
            source_revision: None,
            title,
            body: self.body.clone(),
            prerelease: self.prerelease,
            token_env: self.token_env.clone(),
            request_timeout_secs: self.request_timeout_secs,
            max_metadata_bytes: self.max_metadata_bytes,
            max_list_pages: self.max_list_pages,
        })
    }

    /// Resolve the static template with a checked-in finite identity mode.
    pub fn resolve_with_identity(
        &self,
        tag: &str,
        mode: ReleaseIdentityMode,
        source_revision: &str,
    ) -> Result<GitHubDraftPolicyV1, GithubError> {
        let release_id = mode.release_id(tag)?;
        let mut policy = self.resolve(tag)?;
        if mode != ReleaseIdentityMode::ExactTag {
            policy.release_identity_schema_version = Some(RELEASE_IDENTITY_SCHEMA_VERSION);
            policy.release_identity_mode = Some(mode);
            policy.release_id = Some(release_id);
            policy.source_revision = Some(source_revision.to_owned());
        }
        policy.validate()?;
        Ok(policy)
    }
}

/// Materialize a staging payload for one installer presentation.
///
/// This is the single staging-payload builder. The presentation selects only
/// the installer surface; every other step — validation, inventory
/// construction, sidecars, installers, digest loop, canonical sort, and
/// payload assembly — is implemented exactly once.
#[allow(clippy::too_many_arguments)]
fn prepare_staging_payload_with_presentation_inner(
    contract: &DistributionContract,
    manifest: &ReleaseManifest,
    finalized_root: &Path,
    policy: &GitHubDraftPolicyV1,
    install_policy: &BootstrapInstallPolicyV1,
    presentation: &InstallerPresentationV1,
    source_root: Option<&Path>,
    output_dir: &Path,
) -> Result<StagingPayloadV1, GithubError> {
    presentation.validate()?;
    let (sources, source_root) = match &presentation.mode {
        InstallerPresentationModeV1::GeneratedDefault => (None, None),
        InstallerPresentationModeV1::ProductWrappers(sources) => (
            Some(sources),
            Some(source_root.ok_or_else(|| fail("product wrappers require a source root"))?),
        ),
    };
    // The generated exact installers are the public install surface in the
    // default presentation; product wrappers move them to distinct names.
    let (generated_posix_name, generated_powershell_name) = match sources {
        Some(sources) => (
            sources.generated_posix_name.clone(),
            sources.generated_powershell_name.clone(),
        ),
        None => (
            FIXED_POSIX_NAME.to_owned(),
            FIXED_POWERSHELL_NAME.to_owned(),
        ),
    };
    policy.validate()?;
    manifest
        .validate()
        .map_err(|_| fail("invalid release manifest"))?;
    if contract.product.id != manifest.product_id {
        return Err(fail("contract and manifest product mismatch"));
    }
    if policy.release_identity_mode.is_some() && manifest.release_id != policy.resolved_release_id()
    {
        return Err(fail(
            "manifest release id differs from draft identity policy",
        ));
    }
    if policy
        .source_revision
        .as_deref()
        .is_some_and(|revision| revision != manifest.source_revision)
    {
        return Err(fail(
            "manifest source revision differs from draft identity policy",
        ));
    }
    reject_symlink_dir(finalized_root, "finalized root")?;

    // Collect expected inventory from contract expansion plus manifest facts.
    let mut expected: BTreeMap<String, (bool, u64, String)> = BTreeMap::new();
    for target in &manifest.targets {
        let expanded = contract
            .expand(&target.target, &manifest.release_id)
            .map_err(|_| fail("manifest target is not supported by contract"))?;
        match (&expanded.assets, &target.form) {
            (
                ExpandedAssets::Direct(direct),
                eggpack_manifest::ArtifactForm::Direct { artifact, .. },
            ) => {
                if direct.asset_file != artifact.name {
                    return Err(fail("contract and manifest direct asset differ"));
                }
                if expected
                    .insert(
                        artifact.name.clone(),
                        (true, artifact.size, artifact.sha256.clone()),
                    )
                    .is_some()
                {
                    return Err(fail("duplicate release asset name"));
                }
                if expected
                    .insert(direct.sidecar_file.clone(), (false, 0, String::new()))
                    .is_some()
                {
                    return Err(fail("duplicate release asset name"));
                }
            }
            (
                ExpandedAssets::Bundle(bundle),
                eggpack_manifest::ArtifactForm::Bundle { entries },
            ) => {
                if bundle.entries.len() != entries.len() {
                    return Err(fail("bundle contract and manifest entry counts differ"));
                }
                let mut expanded_map = BTreeMap::new();
                for entry in &bundle.entries {
                    if expanded_map
                        .insert(entry.asset_file.clone(), entry.sidecar_file.clone())
                        .is_some()
                    {
                        return Err(fail("duplicate bundle asset"));
                    }
                }
                for entry in entries {
                    let sidecar = expanded_map
                        .get(&entry.artifact.name)
                        .ok_or_else(|| fail("bundle contract and manifest entries differ"))?;
                    if expected
                        .insert(
                            entry.artifact.name.clone(),
                            (true, entry.artifact.size, entry.artifact.sha256.clone()),
                        )
                        .is_some()
                    {
                        return Err(fail("duplicate release asset name"));
                    }
                    if expected
                        .insert(sidecar.clone(), (false, 0, String::new()))
                        .is_some()
                    {
                        return Err(fail("duplicate release asset name"));
                    }
                }
            }
            (
                ExpandedAssets::Archive(archive),
                eggpack_manifest::ArtifactForm::Archive { artifact, .. },
            ) => {
                if archive.archive_file != artifact.name {
                    return Err(fail("contract and manifest archive filenames differ"));
                }
                if expected
                    .insert(
                        artifact.name.clone(),
                        (true, artifact.size, artifact.sha256.clone()),
                    )
                    .is_some()
                {
                    return Err(fail("duplicate release asset name"));
                }
                if expected
                    .insert(archive.sidecar_file.clone(), (false, 0, String::new()))
                    .is_some()
                {
                    return Err(fail("duplicate release asset name"));
                }
            }
            _ => return Err(fail("contract and manifest forms differ for target")),
        }
    }

    // Auxiliary collision guard, extended with the generated exact-installer
    // names: neither contract assets nor generated names may collide
    // (case-insensitively) with reserved staging names or each other.
    let generated_names = [
        generated_posix_name.clone(),
        generated_powershell_name.clone(),
    ];
    for name in expected.keys() {
        let lower = name.to_ascii_lowercase();
        if lower == FIXED_MANIFEST_NAME
            || lower == FIXED_POSIX_NAME
            || lower == FIXED_POWERSHELL_NAME
            || generated_names
                .iter()
                .any(|generated| generated.to_ascii_lowercase() == lower)
        {
            return Err(fail("release asset collides with staging auxiliary name"));
        }
    }

    // Inventory of the finalized root.
    let mut observed: BTreeMap<String, PathBuf> = BTreeMap::new();
    let entries =
        std::fs::read_dir(finalized_root).map_err(|_| fail("finalized root cannot be listed"))?;
    for entry in entries {
        let entry = entry.map_err(|_| fail("finalized root entry unavailable"))?;
        let file_type = entry
            .file_type()
            .map_err(|_| fail("finalized entry type unavailable"))?;
        if file_type.is_symlink() || !file_type.is_file() {
            return Err(fail("finalized root must contain only regular files"));
        }
        let name = entry.file_name().to_string_lossy().into_owned();
        validate_asset_name(&name)?;
        if observed.insert(name.clone(), entry.path()).is_some() {
            return Err(fail("duplicate finalized file"));
        }
    }
    let expected_names: BTreeSet<String> = expected.keys().cloned().collect();
    let observed_names: BTreeSet<String> = observed.keys().cloned().collect();
    if expected_names != observed_names {
        return Err(fail("finalized root files do not exactly match manifest"));
    }

    // Verify artifact bytes and sidecar contents.
    for (name, (is_artifact, size, sha)) in &expected {
        let path = observed
            .get(name)
            .ok_or_else(|| fail("finalized file missing"))?;
        if *is_artifact {
            let (actual_size, actual_sha) = digest_file(path)?;
            if actual_size != *size || actual_sha != *sha {
                return Err(fail("finalized file differs from manifest"));
            }
        }
    }
    for (name, (is_artifact, _, _)) in &expected {
        if *is_artifact {
            continue;
        }
        // Sidecar: "<sha>  <file>\n" for its artifact sibling is validated
        // by locating the artifact that shares the sidecar stem. The exact
        // sidecar filename mapping comes from contract expansion; here we
        // verify content shape and matching digest without trusting names.
        let path = observed
            .get(name)
            .ok_or_else(|| fail("finalized file missing"))?;
        let text = std::fs::read_to_string(path).map_err(|_| fail("sidecar cannot be read"))?;
        if text.len() > 4096 {
            return Err(fail("sidecar exceeds bound"));
        }
        let trimmed = text.trim_end_matches(['\n', '\r']);
        let mut parts = trimmed.splitn(2, "  ");
        let sha = parts
            .next()
            .ok_or_else(|| fail("sidecar content invalid"))?;
        let file = parts
            .next()
            .ok_or_else(|| fail("sidecar content invalid"))?;
        validate_sha256(sha)?;
        validate_asset_name(file)?;
        let artifact_path = finalized_root.join(file);
        if !observed.contains_key(file) {
            return Err(fail("sidecar references unknown artifact"));
        }
        let (actual_size, actual_sha) = digest_file(&artifact_path)?;
        if actual_sha != sha {
            return Err(fail("sidecar digest differs from artifact"));
        }
        let _ = actual_size;
        // Require the `.sha256` suffix.
        // Contract expansion supplies the exact names, so this is
        // only a consistency check.
        if !name.ends_with(".sha256") {
            return Err(fail("sidecar filename invalid"));
        }
    }

    ensure_absent_private_dir(output_dir, "staging output")?;
    let cleanup = |_: ()| {
        let _ = std::fs::remove_dir_all(output_dir);
    };

    // Copy exact finalized assets.
    for (name, path) in &observed {
        let dest = output_dir.join(name);
        std::fs::copy(path, &dest).map_err(|_| {
            cleanup(());
            fail("staging copy failed")
        })?;
    }

    // Standalone manifest handoff.
    let manifest_json = manifest
        .to_json()
        .map_err(|_| fail("manifest encode failed"))?;
    let manifest_path = output_dir.join(FIXED_MANIFEST_NAME);
    std::fs::write(&manifest_path, manifest_json.as_bytes()).map_err(|_| {
        cleanup(());
        fail("staging manifest write failed")
    })?;
    let roundtrip = ReleaseManifest::from_json(&manifest_json).map_err(|_| {
        cleanup(());
        fail("staging manifest roundtrip failed")
    })?;
    let roundtrip_json = roundtrip.to_json().map_err(|_| {
        cleanup(());
        fail("staging manifest roundtrip failed")
    })?;
    if roundtrip_json != manifest_json {
        cleanup(());
        return Err(fail("staging manifest does not decode to exact manifest"));
    }

    // Deterministic bootstrap installers with exact-tag origin.
    let origin = policy.download_origin();
    let spec = BootstrapSpec {
        origin,
        fixture_http: false,
    };
    let posix =
        eggpack_bootstrap::render_posix_with_policy(contract, manifest, &spec, install_policy)
            .map_err(|_| {
                cleanup(());
                fail("posix installer generation failed")
            })?;
    let powershell =
        eggpack_bootstrap::render_powershell_with_policy(contract, manifest, &spec, install_policy)
            .map_err(|_| {
                cleanup(());
                fail("powershell installer generation failed")
            })?;
    // Exact-tag origin only; never latest/download.
    if posix.contains("latest/download") || powershell.contains("latest/download") {
        cleanup(());
        return Err(fail("installer uses unsupported latest origin"));
    }
    // The generated exact installers are staged under the presentation's
    // names. Product wrappers additionally become the public install surface
    // under the fixed names.
    let (posix_wrapper, powershell_wrapper) = match (sources, source_root) {
        (Some(sources), Some(source_root)) => {
            // Product wrappers are the public surface; generated exact
            // installers keep distinct non-colliding names as
            // qualified-bootstrap evidence.
            let posix_wrapper =
                read_wrapper_source(source_root, &sources.posix_source).map_err(|_| {
                    cleanup(());
                    fail("product posix wrapper is unavailable")
                })?;
            let powershell_wrapper = read_wrapper_source(source_root, &sources.powershell_source)
                .map_err(|_| {
                cleanup(());
                fail("product powershell wrapper is unavailable")
            })?;
            (Some(posix_wrapper), Some(powershell_wrapper))
        }
        _ => (None, None),
    };
    std::fs::write(output_dir.join(&generated_posix_name), posix.as_bytes()).map_err(|_| {
        cleanup(());
        fail("posix installer write failed")
    })?;
    std::fs::write(
        output_dir.join(&generated_powershell_name),
        powershell.as_bytes(),
    )
    .map_err(|_| {
        cleanup(());
        fail("powershell installer write failed")
    })?;
    if let (Some(posix_wrapper), Some(powershell_wrapper)) = (posix_wrapper, powershell_wrapper) {
        std::fs::write(output_dir.join(FIXED_POSIX_NAME), posix_wrapper.as_slice()).map_err(
            |_| {
                cleanup(());
                fail("product posix wrapper write failed")
            },
        )?;
        std::fs::write(
            output_dir.join(FIXED_POWERSHELL_NAME),
            powershell_wrapper.as_slice(),
        )
        .map_err(|_| {
            cleanup(());
            fail("product powershell wrapper write failed")
        })?;
    }

    // Build deterministic payload records.
    let mut assets = Vec::new();
    let mut staged_names: BTreeSet<String> = BTreeSet::new();
    let mut staged_entries: Vec<(String, StagingAssetKind, String)> = Vec::new();
    for name in observed.keys() {
        let is_artifact = expected
            .get(name)
            .map(|(is_artifact, _, _)| *is_artifact)
            .unwrap_or(false);
        let (kind, media) = if is_artifact {
            (
                StagingAssetKind::FinalizedArtifact,
                "application/octet-stream".to_owned(),
            )
        } else {
            (StagingAssetKind::ChecksumSidecar, "text/plain".to_owned())
        };
        staged_entries.push((name.clone(), kind, media));
    }
    staged_entries.push((
        FIXED_MANIFEST_NAME.to_owned(),
        StagingAssetKind::ReleaseManifest,
        "application/json".to_owned(),
    ));
    staged_entries.push((
        generated_posix_name.clone(),
        StagingAssetKind::PosixInstaller,
        "text/x-shellscript".to_owned(),
    ));
    staged_entries.push((
        generated_powershell_name.clone(),
        StagingAssetKind::PowershellInstaller,
        "text/x-powershell".to_owned(),
    ));
    if sources.is_some() {
        staged_entries.push((
            FIXED_POSIX_NAME.to_owned(),
            StagingAssetKind::ProductPosixWrapper,
            "text/x-shellscript".to_owned(),
        ));
        staged_entries.push((
            FIXED_POWERSHELL_NAME.to_owned(),
            StagingAssetKind::ProductPowershellWrapper,
            "text/x-powershell".to_owned(),
        ));
    }
    for (name, kind, media) in staged_entries {
        if !staged_names.insert(name.to_ascii_lowercase()) {
            cleanup(());
            return Err(fail("duplicate staging asset name"));
        }
        let (size, sha) = digest_file(&output_dir.join(&name)).map_err(|_| {
            cleanup(());
            fail("staged file digest failed")
        })?;
        assets.push(StagingAsset {
            name: name.clone(),
            path: name,
            size,
            sha256: sha,
            media_type: media,
            kind,
        });
    }
    assets.sort_by(|a, b| a.name.cmp(&b.name));

    let payload = StagingPayloadV1 {
        schema_version: 1,
        product_id: manifest.product_id.clone(),
        release_id: manifest.release_id.clone(),
        source_revision: manifest.source_revision.clone(),
        owner: policy.owner.clone(),
        repository: policy.repository.clone(),
        tag: policy.tag.clone(),
        title: policy.title.clone(),
        prerelease: policy.prerelease,
        body: policy.body.clone(),
        assets,
    };
    payload.validate().map_err(|_| {
        cleanup(());
        fail("staging payload invalid")
    })?;
    Ok(payload)
}

// ---------------------------------------------------------------------------
// GitHub adapter
// ---------------------------------------------------------------------------

/// Exact tag reference target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefTarget {
    /// Commit or tag object SHA.
    pub sha: String,
    /// Object type (`commit` or `tag`).
    pub kind: String,
}

/// Annotated tag object peeling step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TagObject {
    /// Peeled object SHA.
    pub object_sha: String,
    /// Peeled object type.
    pub object_type: String,
}

/// Remote release summary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteRelease {
    /// GitHub numeric release id.
    pub id: u64,
    /// Exact tag name.
    pub tag_name: String,
    /// Release title.
    pub name: String,
    /// Release notes.
    pub body: String,
    /// Draft state.
    pub draft: bool,
    /// Immutable state.
    pub immutable: bool,
    /// Prerelease intent.
    pub prerelease: bool,
    /// Upload URL template/host.
    pub upload_url: String,
}

/// Remote release asset.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteAsset {
    /// GitHub numeric asset id.
    pub id: u64,
    /// Exact asset name.
    pub name: String,
    /// Exact byte size.
    pub size: u64,
    /// Asset state (`uploaded` or `starter`).
    pub state: String,
    /// Optional `sha256:<hex>` digest.
    pub digest: Option<String>,
}

/// Provider transport seam for GitHub staging.
///
/// Production uses fixed `https://api.github.com` plus upload host
/// `https://uploads.github.com` through `eggfetch-core` with a lean profile
/// (no retries, no redirects). Tests inject a deterministic fixture.
pub trait GithubApi: Send + Sync {
    /// Fetch exact `refs/tags/<tag>` reference.
    fn get_ref(
        &self,
        owner: &str,
        repo: &str,
        tag: &str,
    ) -> impl std::future::Future<Output = Result<RefTarget, GithubError>> + Send;
    /// Fetch one annotated tag object by SHA.
    fn get_tag(
        &self,
        owner: &str,
        repo: &str,
        sha: &str,
    ) -> impl std::future::Future<Output = Result<TagObject, GithubError>> + Send;
    /// List releases for one page (1-indexed, `per_page=100`).
    fn list_releases(
        &self,
        owner: &str,
        repo: &str,
        page: u32,
    ) -> impl std::future::Future<Output = Result<Vec<RemoteRelease>, GithubError>> + Send;
    /// Create a new draft release for an exact existing tag.
    fn create_release(
        &self,
        owner: &str,
        repo: &str,
        tag: &str,
        title: &str,
        body: &str,
        prerelease: bool,
    ) -> impl std::future::Future<Output = Result<RemoteRelease, GithubError>> + Send;
    /// List all assets for one release.
    fn list_assets(
        &self,
        owner: &str,
        repo: &str,
        release_id: u64,
        page: u32,
    ) -> impl std::future::Future<Output = Result<Vec<RemoteAsset>, GithubError>> + Send;
    /// Upload one asset; 502/422 are reported as errors with `http_502` /
    /// `http_422_duplicate` prefixes so the caller can apply narrow recovery.
    #[allow(clippy::too_many_arguments)]
    fn upload_asset(
        &self,
        owner: &str,
        repo: &str,
        release_id: u64,
        name: &str,
        file: Box<dyn std::io::Read + Send>,
        length: u64,
        content_type: &str,
    ) -> impl std::future::Future<Output = Result<RemoteAsset, GithubError>> + Send;
    /// Delete one asset by id (only the narrow starter recovery may call this).
    fn delete_asset(
        &self,
        owner: &str,
        repo: &str,
        asset_id: u64,
    ) -> impl std::future::Future<Output = Result<(), GithubError>> + Send;
}

trait ReadSeek: std::io::Read + std::io::Seek {
    fn source_len(&self) -> Result<u64, GithubError>;
}
impl ReadSeek for std::fs::File {
    fn source_len(&self) -> Result<u64, GithubError> {
        Ok(self
            .metadata()
            .map_err(|_| fail("staged file is unavailable"))?
            .len())
    }
}
impl<T: AsRef<[u8]> + Send> ReadSeek for std::io::Cursor<T> {
    fn source_len(&self) -> Result<u64, GithubError> {
        Ok(self.get_ref().as_ref().len() as u64)
    }
}

fn is_http_502(error: &GithubError) -> bool {
    error.0.starts_with("http_502")
}

fn is_http_422_duplicate(error: &GithubError) -> bool {
    error.0.starts_with("http_422_duplicate")
}

fn validate_sha40(value: &str) -> Result<(), GithubError> {
    if value.len() != 40
        || !value
            .bytes()
            .all(|b| b.is_ascii_hexdigit() && (b.is_ascii_digit() || b.is_ascii_lowercase()))
    {
        // GitHub SHAs are lowercase hex; be strict but do not leak values.
        return Err(fail("remote SHA has invalid shape"));
    }
    Ok(())
}

/// Verify an exact tag resolves to the payload source revision.
///
/// Lightweight tags must point directly at the revision. Annotated tags are
/// peeled with a bounded loop and must terminate at a commit with the exact
/// revision. No tag write endpoint exists.
pub async fn verify_tag_source(
    transport: &impl GithubApi,
    owner: &str,
    repo: &str,
    tag: &str,
    source_revision: &str,
) -> Result<(), GithubError> {
    let reference = transport.get_ref(owner, repo, tag).await?;
    if reference.kind == "commit" {
        validate_sha40(&reference.sha)?;
        if reference.sha != source_revision {
            return Err(fail("tag does not match source revision"));
        }
        return Ok(());
    }
    if reference.kind != "tag" {
        return Err(fail("tag reference has unexpected type"));
    }
    validate_sha40(&reference.sha)?;
    let mut current = reference.sha;
    for _ in 0..MAX_TAG_PEEL_DEPTH {
        let object = transport.get_tag(owner, repo, &current).await?;
        if object.object_type == "commit" {
            validate_sha40(&object.object_sha)?;
            if object.object_sha != source_revision {
                return Err(fail("tag does not match source revision"));
            }
            return Ok(());
        }
        if object.object_type != "tag" {
            return Err(fail("annotated tag did not resolve to a commit"));
        }
        validate_sha40(&object.object_sha)?;
        current = object.object_sha;
    }
    Err(fail("annotated tag depth exceeds bound"))
}

fn find_exact_release(
    releases: &[RemoteRelease],
    tag: &str,
) -> Result<Option<RemoteRelease>, GithubError> {
    let mut matches = Vec::new();
    for release in releases {
        if release.tag_name == tag {
            matches.push(release.clone());
        }
    }
    if matches.len() > 1 {
        return Err(fail("duplicate same-tag release records"));
    }
    Ok(matches.into_iter().next())
}

fn check_upload_url(
    url: &str,
    owner: &str,
    repository: &str,
    release_id: u64,
) -> Result<(), GithubError> {
    let normalized = url.strip_suffix("{?name,label}").unwrap_or(url);
    let parsed = url::Url::parse(normalized).map_err(|_| fail("upload URL is invalid"))?;
    if parsed.scheme() != "https"
        || parsed.host_str() != Some("uploads.github.com")
        || parsed.username() != ""
        || parsed.password().is_some()
        || parsed.port().is_some_and(|port| port != 443)
        || parsed.fragment().is_some()
        || parsed.path() != format!("/repos/{owner}/{repository}/releases/{release_id}/assets")
        || parsed.query().is_some()
    {
        return Err(fail("upload host is not the expected GitHub host"));
    }
    Ok(())
}

fn upload_url(
    owner: &str,
    repository: &str,
    release_id: u64,
    name: &str,
) -> Result<String, GithubError> {
    validate_asset_name(name)?;
    let mut url = url::Url::parse(&format!(
        "{UPLOAD_BASE}/repos/{owner}/{repository}/releases/{release_id}/assets"
    ))
    .map_err(|_| fail("upload URL construction failed"))?;
    url.query_pairs_mut().append_pair("name", name);
    Ok(url.into())
}

fn streamed_upload_body(
    file: Box<dyn std::io::Read + Send>,
    length: u64,
) -> Result<eggfetch_core::RequestBody, GithubError> {
    let length =
        usize::try_from(length).map_err(|_| fail("asset length exceeds platform bound"))?;
    Ok(eggfetch_core::RequestBody::from_stream(
        futures_util::stream::try_unfold(file, |mut file| async move {
            use std::io::Read;
            let mut chunk = vec![0; UPLOAD_CHUNK_BYTES];
            let count = file
                .read(&mut chunk)
                .map_err(|error| eggfetch_core::Error::Io(std::sync::Arc::new(error)))?;
            if count == 0 {
                Ok(None)
            } else {
                chunk.truncate(count);
                Ok(Some((bytes::Bytes::from(chunk), file)))
            }
        }),
        Some(length),
    ))
}

/// Page through one listing endpoint, failing closed when the bound is hit.
///
/// A batch that is completely filled (`LIST_PAGE_SIZE`) may have more pages
/// behind it, so running out of pages while that is still true means the
/// listing was truncated. The caller would otherwise act on a partial view —
/// for releases, by concluding the target tag has no release and creating a
/// second one for a tag that already has one — so truncation is an explicit
/// error, never a short list. `label` names the listing in that message.
async fn list_all_pages<T, F, Fut>(
    max_pages: u32,
    label: &'static str,
    mut fetch: F,
) -> Result<Vec<T>, GithubError>
where
    F: FnMut(u32) -> Fut,
    Fut: std::future::Future<Output = Result<Vec<T>, GithubError>>,
{
    let mut all = Vec::new();
    for page in 1..=max_pages {
        let batch = fetch(page).await?;
        let full = batch.len() >= LIST_PAGE_SIZE;
        all.extend(batch);
        if !full {
            return Ok(all);
        }
        if page == max_pages {
            return Err(fail(match label {
                "asset" => "asset pagination bound exhausted",
                _ => "release pagination bound exhausted",
            }));
        }
    }
    Ok(all)
}

async fn list_all_releases(
    transport: &impl GithubApi,
    policy: &GitHubDraftPolicyV1,
) -> Result<Vec<RemoteRelease>, GithubError> {
    list_all_pages(policy.max_list_pages, "release", |page| {
        transport.list_releases(&policy.owner, &policy.repository, page)
    })
    .await
}

async fn list_all_assets(
    transport: &impl GithubApi,
    policy: &GitHubDraftPolicyV1,
    release_id: u64,
) -> Result<Vec<RemoteAsset>, GithubError> {
    list_all_pages(policy.max_list_pages, "asset", |page| {
        transport.list_assets(&policy.owner, &policy.repository, release_id, page)
    })
    .await
}

fn verify_file(file: &mut dyn ReadSeek, expected: &StagingAsset) -> Result<(), GithubError> {
    use std::io::SeekFrom;
    if file.source_len()? != expected.size {
        return Err(fail("local asset size differs from payload"));
    }
    file.seek(SeekFrom::Start(0))
        .map_err(|_| fail("staged file cannot be read"))?;
    let mut hasher = sha2::Sha256::new();
    let mut buf = [0u8; UPLOAD_CHUNK_BYTES];
    loop {
        let count = file
            .read(&mut buf)
            .map_err(|_| fail("staged file cannot be read"))?;
        if count == 0 {
            break;
        }
        use sha2::Digest;
        hasher.update(&buf[..count]);
    }
    use sha2::Digest;
    let digest = hasher
        .finalize()
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect::<String>();
    if digest != expected.sha256 {
        return Err(fail("local asset digest differs from payload"));
    }
    file.seek(SeekFrom::Start(0))
        .map_err(|_| fail("staged file cannot be read"))?;
    Ok(())
}

/// Testable staging core with explicit local bytes.
pub async fn stage_with_bytes<F>(
    payload: &StagingPayloadV1,
    policy: &GitHubDraftPolicyV1,
    transport: &impl GithubApi,
    token: &str,
    mut bytes_for: F,
) -> Result<GitHubDraftReceiptV1, GithubError>
where
    F: FnMut(&str) -> Result<Vec<u8>, GithubError>,
{
    stage_with_source(payload, policy, transport, token, |name| {
        Ok(Box::new(std::io::Cursor::new(bytes_for(name)?)) as Box<dyn ReadSeek + Send>)
    })
    .await
}

async fn stage_with_source<F>(
    payload: &StagingPayloadV1,
    policy: &GitHubDraftPolicyV1,
    transport: &impl GithubApi,
    token: &str,
    mut source_for: F,
) -> Result<GitHubDraftReceiptV1, GithubError>
where
    F: FnMut(&str) -> Result<Box<dyn ReadSeek + Send>, GithubError>,
{
    if token.is_empty() || token.len() > 4096 || token.chars().any(char::is_control) {
        return Err(fail("github token is absent"));
    }
    payload.validate()?;
    policy.validate()?;
    if payload.owner != policy.owner
        || payload.repository != policy.repository
        || payload.tag != policy.tag
        || (policy.release_identity_mode.is_some()
            && payload.release_id != policy.resolved_release_id())
        || policy
            .source_revision
            .as_deref()
            .is_some_and(|revision| revision != payload.source_revision)
        || payload.title != policy.title
        || payload.prerelease != policy.prerelease
        || payload.body != policy.body
    {
        return Err(fail("staging payload does not match draft policy"));
    }

    verify_tag_source(
        transport,
        &policy.owner,
        &policy.repository,
        &policy.tag,
        &payload.source_revision,
    )
    .await?;

    // A truncated release listing would hide the existing draft for this tag,
    // and staging would then try to create a second release for a tag that
    // already has one. Bound exhaustion fails closed here, exactly as it does
    // on the asset listing.
    let seen = list_all_releases(transport, policy).await?;
    let existing = find_exact_release(&seen, &policy.tag)?;
    let (release, created) = match existing {
        None => {
            let created = transport
                .create_release(
                    &policy.owner,
                    &policy.repository,
                    &policy.tag,
                    &policy.title,
                    &policy.body,
                    policy.prerelease,
                )
                .await?;
            if created.tag_name != policy.tag || !created.draft || created.immutable {
                return Err(fail("created release has unexpected state"));
            }
            (created, true)
        }
        Some(current) => {
            if !current.draft || current.immutable {
                return Err(fail("existing release is not a mutable draft"));
            }
            if current.tag_name != policy.tag {
                return Err(fail("existing draft tag mismatch"));
            }
            if current.name != policy.title
                || current.prerelease != policy.prerelease
                || current.body != policy.body
            {
                return Err(fail("existing draft title/prerelease/body mismatch"));
            }
            (current, false)
        }
    };
    check_upload_url(
        &release.upload_url,
        &policy.owner,
        &policy.repository,
        release.id,
    )?;

    let mut expected: BTreeMap<String, &StagingAsset> = BTreeMap::new();
    for asset in &payload.assets {
        if expected.insert(asset.name.clone(), asset).is_some() {
            return Err(fail("duplicate payload asset name"));
        }
    }

    let remote = list_all_assets(transport, policy, release.id).await?;
    {
        let mut names = BTreeSet::new();
        for asset in &remote {
            if !names.insert(asset.name.to_ascii_lowercase()) {
                return Err(fail("duplicate same-name remote asset"));
            }
            if !expected.contains_key(&asset.name) {
                return Err(fail("unexpected remote asset"));
            }
        }
    }
    let mut remote_by_name: BTreeMap<String, RemoteAsset> = BTreeMap::new();
    for asset in remote {
        remote_by_name.insert(asset.name.clone(), asset);
    }

    let mut uploaded: u32 = 0;
    let mut reused: u32 = 0;
    for (name, local) in &expected {
        match remote_by_name.get(name) {
            None => {
                let mut file = source_for(name)?;
                verify_file(file.as_mut(), local)?;
                match transport
                    .upload_asset(
                        &policy.owner,
                        &policy.repository,
                        release.id,
                        name,
                        Box::new(file),
                        local.size,
                        &local.media_type,
                    )
                    .await
                {
                    Ok(record) => {
                        if record.name != *name {
                            return Err(fail("upload response renamed the asset"));
                        }
                        if record.state != "uploaded" {
                            return Err(fail("upload response state is not uploaded"));
                        }
                        if record.size != local.size {
                            return Err(fail("upload response size mismatch"));
                        }
                        if let Some(digest) = &record.digest {
                            if digest != &format!("sha256:{}", local.sha256) {
                                return Err(fail("upload response digest mismatch"));
                            }
                        }
                        uploaded = uploaded
                            .checked_add(1)
                            .ok_or_else(|| fail("upload count overflow"))?;
                    }
                    Err(error) => {
                        if is_http_422_duplicate(&error) {
                            return Err(fail("duplicate-name upload rejected"));
                        }
                        if is_http_502(&error) {
                            let after = list_all_assets(transport, policy, release.id).await?;
                            let starters: Vec<&RemoteAsset> = after
                                .iter()
                                .filter(|asset| {
                                    asset.name == *name
                                        && asset.state == "starter"
                                        && asset.size == 0
                                })
                                .collect();
                            if starters.len() == 1 {
                                transport
                                    .delete_asset(&policy.owner, &policy.repository, starters[0].id)
                                    .await?;
                            }
                            return Err(fail("upload failed with 502; starter cleaned when exact"));
                        }
                        return Err(error);
                    }
                }
            }
            Some(record) => {
                if record.state != "uploaded" {
                    return Err(fail("remote asset is not uploaded"));
                }
                if record.size != local.size {
                    return Err(fail("same-name remote asset size mismatch"));
                }
                match &record.digest {
                    Some(digest) if digest == &format!("sha256:{}", local.sha256) => {
                        reused = reused
                            .checked_add(1)
                            .ok_or_else(|| fail("reuse count overflow"))?;
                    }
                    _ => return Err(fail("same-name remote asset digest mismatch")),
                }
            }
        }
    }

    let final_assets = list_all_assets(transport, policy, release.id).await?;
    {
        let mut names = BTreeSet::new();
        for asset in &final_assets {
            if !names.insert(asset.name.clone()) {
                return Err(fail("duplicate same-name remote asset"));
            }
        }
        if names.len() != expected.len() {
            return Err(fail("staged asset set is incomplete"));
        }
        for (name, local) in &expected {
            let record = final_assets
                .iter()
                .find(|asset| &asset.name == name)
                .ok_or_else(|| fail("staged asset missing after upload"))?;
            if record.state != "uploaded"
                || record.size != local.size
                || record.digest.as_deref() != Some(&format!("sha256:{}", local.sha256))
            {
                return Err(fail("staged asset evidence mismatch"));
            }
        }
    }

    verify_tag_source(
        transport,
        &policy.owner,
        &policy.repository,
        &policy.tag,
        &payload.source_revision,
    )
    .await?;

    let mut ordered = payload.assets.clone();
    ordered.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(GitHubDraftReceiptV1 {
        schema_version: 1,
        owner: policy.owner.clone(),
        repository: policy.repository.clone(),
        release_id: payload.release_id.clone(),
        tag: policy.tag.clone(),
        source_revision: payload.source_revision.clone(),
        github_release_id: release.id,
        draft: true,
        immutable: false,
        assets: ordered,
        created,
        uploaded,
        reused,
    })
}

/// Stage using a staging directory on disk.
pub async fn stage_with_dir(
    payload: &StagingPayloadV1,
    policy: &GitHubDraftPolicyV1,
    transport: &impl GithubApi,
    token: &str,
    staging_dir: &Path,
) -> Result<GitHubDraftReceiptV1, GithubError> {
    payload.validate()?;
    policy.validate()?;
    reject_symlink_dir(staging_dir, "staging directory")?;
    let mut files = BTreeMap::new();
    for asset in &payload.assets {
        let path = staging_dir.join(&asset.name);
        let metadata =
            std::fs::symlink_metadata(&path).map_err(|_| fail("staged file is unavailable"))?;
        if metadata.file_type().is_symlink() || !metadata.is_file() {
            return Err(fail("staged file must be a regular file"));
        }
        let mut file =
            std::fs::File::open(&path).map_err(|_| fail("staged file cannot be read"))?;
        if !file
            .metadata()
            .map_err(|_| fail("staged file is unavailable"))?
            .is_file()
        {
            return Err(fail("staged file must be a regular file"));
        }
        verify_file(&mut file, asset)?;
        files.insert(asset.name.clone(), file);
    }
    stage_with_source(payload, policy, transport, token, |name| {
        let file = files
            .remove(name)
            .ok_or_else(|| fail("staged file is unavailable"))?;
        Ok(Box::new(file) as Box<dyn ReadSeek + Send>)
    })
    .await
}

// ---------------------------------------------------------------------------
// Production transport (eggfetch-core, lean profile)
// ---------------------------------------------------------------------------

/// Production GitHub transport with fixed hosts.
///
/// Uses `eggfetch-core 0.4.0` with explicit lean features (`standard-http1`,
/// `tls-rustls`, `tls-native-roots`, `json`) rather than the default
/// retry/redirect policy. Retries are disabled and redirects are not followed;
/// 3xx responses fail closed. Bounded timeouts and body sizes apply to every
/// request. The `Debug` implementation redacts the credential.
pub struct EggfetchTransport {
    client: eggfetch_core::Client,
    token: String,
    timeout_secs: u64,
    max_metadata_bytes: usize,
}

impl fmt::Debug for EggfetchTransport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EggfetchTransport")
            .field("timeout_secs", &self.timeout_secs)
            .field("max_metadata_bytes", &self.max_metadata_bytes)
            .field("token", &"<redacted>")
            .finish_non_exhaustive()
    }
}

impl EggfetchTransport {
    /// Create a production transport. The token is held in memory only and
    /// never serialized or logged.
    pub fn new(
        token: String,
        timeout_secs: u64,
        max_metadata_bytes: usize,
    ) -> Result<Self, GithubError> {
        if token.is_empty() || token.len() > 4096 || token.chars().any(char::is_control) {
            return Err(fail("github token is absent"));
        }
        if !(5..=120).contains(&timeout_secs) {
            return Err(fail("request timeout out of bounds"));
        }
        if max_metadata_bytes == 0 || max_metadata_bytes > 8_000_000 {
            return Err(fail("max metadata bytes out of bounds"));
        }
        let timeout = eggfetch_core::Timeout::from_secs(timeout_secs);
        let client = eggfetch_core::Client::builder()
            .user_agent(USER_AGENT)
            .timeout(timeout)
            .build();
        Ok(Self {
            client,
            token,
            timeout_secs,
            max_metadata_bytes,
        })
    }

    fn auth(&self) -> Result<eggfetch_core::AuthScheme, GithubError> {
        eggfetch_core::AuthScheme::bearer(self.token.clone())
            .map_err(|_| fail("github token has invalid shape"))
    }

    fn timeout(&self) -> eggfetch_core::Timeout {
        eggfetch_core::Timeout::from_secs(self.timeout_secs)
    }

    async fn read_json<T: serde::de::DeserializeOwned>(
        &self,
        mut response: eggfetch_core::Response,
    ) -> Result<T, GithubError> {
        let status = response.status().as_u16();
        if (300..400).contains(&status) {
            return Err(fail("unexpected redirect; redirects are disabled"));
        }
        if !(200..300).contains(&status) {
            return match status {
                404 => Err(fail("github resource not found")),
                422 => Err(fail("http_422_duplicate: github rejected duplicate name")),
                502 => Err(fail("http_502: github reported a gateway failure")),
                _ => Err(fail("github request failed")),
            };
        }
        response
            .json::<T>()
            .await
            .map_err(|_| fail("github response decode failed"))
    }
}

#[derive(Debug, Deserialize)]
struct ApiRefObject {
    sha: String,
    #[serde(rename = "type")]
    kind: String,
}

#[derive(Debug, Deserialize)]
struct ApiRefResponse {
    object: ApiRefObject,
}

#[derive(Debug, Deserialize)]
struct ApiTagObjectInner {
    sha: String,
    #[serde(rename = "type")]
    kind: String,
}

#[derive(Debug, Deserialize)]
struct ApiTagResponse {
    object: ApiTagObjectInner,
}

#[derive(Debug, Deserialize)]
struct ApiRelease {
    id: u64,
    tag_name: String,
    name: Option<String>,
    body: Option<String>,
    draft: bool,
    /// Optional in the REST payload: a response that omits the field means the
    /// release was not reported immutable. The default is required for
    /// compatibility — making it mandatory would fail every release read
    /// against an API that does not return it. Staging still fails closed:
    /// a reported `true` refuses the draft, and an unreported one is rejected
    /// by the upload call itself.
    #[serde(default)]
    immutable: bool,
    prerelease: bool,
    upload_url: String,
}

#[derive(Debug, Deserialize)]
struct ApiAsset {
    id: u64,
    name: String,
    size: u64,
    state: String,
    digest: Option<String>,
}

impl GithubApi for EggfetchTransport {
    async fn get_ref(&self, owner: &str, repo: &str, tag: &str) -> Result<RefTarget, GithubError> {
        let url = format!("{API_BASE}/repos/{owner}/{repo}/git/ref/tags/{tag}");
        let response = self
            .client
            .get(&url)
            .map_err(|_| fail("github request build failed"))?
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", API_VERSION)
            .auth(self.auth()?)
            .timeout(self.timeout())
            .max_decoded_body_size(self.max_metadata_bytes)
            .send()
            .await
            .map_err(|_| fail("github tag lookup failed"))?;
        let body: ApiRefResponse = self.read_json(response).await?;
        Ok(RefTarget {
            sha: body.object.sha,
            kind: body.object.kind,
        })
    }

    async fn get_tag(&self, owner: &str, repo: &str, sha: &str) -> Result<TagObject, GithubError> {
        let url = format!("{API_BASE}/repos/{owner}/{repo}/git/tags/{sha}");
        let response = self
            .client
            .get(&url)
            .map_err(|_| fail("github request build failed"))?
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", API_VERSION)
            .auth(self.auth()?)
            .timeout(self.timeout())
            .max_decoded_body_size(self.max_metadata_bytes)
            .send()
            .await
            .map_err(|_| fail("github tag object lookup failed"))?;
        let body: ApiTagResponse = self.read_json(response).await?;
        Ok(TagObject {
            object_sha: body.object.sha,
            object_type: body.object.kind,
        })
    }

    async fn list_releases(
        &self,
        owner: &str,
        repo: &str,
        page: u32,
    ) -> Result<Vec<RemoteRelease>, GithubError> {
        let url = format!("{API_BASE}/repos/{owner}/{repo}/releases?per_page=100&page={page}");
        let response = self
            .client
            .get(&url)
            .map_err(|_| fail("github request build failed"))?
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", API_VERSION)
            .auth(self.auth()?)
            .timeout(self.timeout())
            .max_decoded_body_size(self.max_metadata_bytes)
            .send()
            .await
            .map_err(|_| fail("github release list failed"))?;
        let body: Vec<ApiRelease> = self.read_json(response).await?;
        Ok(body
            .into_iter()
            .map(|item| RemoteRelease {
                id: item.id,
                tag_name: item.tag_name,
                name: item.name.unwrap_or_default(),
                body: item.body.unwrap_or_default(),
                draft: item.draft,
                immutable: item.immutable,
                prerelease: item.prerelease,
                upload_url: item.upload_url,
            })
            .collect())
    }

    async fn create_release(
        &self,
        owner: &str,
        repo: &str,
        tag: &str,
        title: &str,
        body: &str,
        prerelease: bool,
    ) -> Result<RemoteRelease, GithubError> {
        let url = format!("{API_BASE}/repos/{owner}/{repo}/releases");
        let request_body = serde_json::json!({
            "tag_name": tag,
            "name": title,
            "body": body,
            "draft": true,
            "prerelease": prerelease,
            "make_latest": "false",
        });
        let response = self
            .client
            .post(&url)
            .map_err(|_| fail("github request build failed"))?
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", API_VERSION)
            .auth(self.auth()?)
            .timeout(self.timeout())
            .max_decoded_body_size(self.max_metadata_bytes)
            .json(&request_body)
            .map_err(|_| fail("github request encode failed"))?
            .send()
            .await
            .map_err(|_| fail("github release creation failed"))?;
        let item: ApiRelease = self.read_json(response).await?;
        Ok(RemoteRelease {
            id: item.id,
            tag_name: item.tag_name,
            name: item.name.unwrap_or_default(),
            body: item.body.unwrap_or_default(),
            draft: item.draft,
            immutable: item.immutable,
            prerelease: item.prerelease,
            upload_url: item.upload_url,
        })
    }

    async fn list_assets(
        &self,
        owner: &str,
        repo: &str,
        release_id: u64,
        page: u32,
    ) -> Result<Vec<RemoteAsset>, GithubError> {
        let url = format!(
            "{API_BASE}/repos/{owner}/{repo}/releases/{release_id}/assets?per_page=100&page={page}"
        );
        let response = self
            .client
            .get(&url)
            .map_err(|_| fail("github request build failed"))?
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", API_VERSION)
            .auth(self.auth()?)
            .timeout(self.timeout())
            .max_decoded_body_size(self.max_metadata_bytes)
            .send()
            .await
            .map_err(|_| fail("github asset list failed"))?;
        let body: Vec<ApiAsset> = self.read_json(response).await?;
        Ok(body
            .into_iter()
            .map(|item| RemoteAsset {
                id: item.id,
                name: item.name,
                size: item.size,
                state: item.state,
                digest: item.digest,
            })
            .collect())
    }

    async fn upload_asset(
        &self,
        owner: &str,
        repo: &str,
        release_id: u64,
        name: &str,
        file: Box<dyn std::io::Read + Send>,
        length: u64,
        content_type: &str,
    ) -> Result<RemoteAsset, GithubError> {
        let url = upload_url(owner, repo, release_id, name)?;
        let body = streamed_upload_body(file, length)?;
        let response = self
            .client
            .post(&url)
            .map_err(|_| fail("github request build failed"))?
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", API_VERSION)
            .header("Content-Type", content_type)
            .auth(self.auth()?)
            .timeout(self.timeout())
            .max_decoded_body_size(self.max_metadata_bytes)
            .body(body)
            .send()
            .await
            .map_err(|_| fail("github asset upload failed"))?;
        let status = response.status().as_u16();
        if status == 502 {
            return Err(fail("http_502: github reported a gateway failure"));
        }
        if status == 422 {
            return Err(fail("http_422_duplicate: github rejected duplicate name"));
        }
        if (300..400).contains(&status) {
            return Err(fail("unexpected redirect; redirects are disabled"));
        }
        if status != 201 {
            return Err(fail("github asset upload failed"));
        }
        let item: ApiAsset = self.read_json(response).await?;
        Ok(RemoteAsset {
            id: item.id,
            name: item.name,
            size: item.size,
            state: item.state,
            digest: item.digest,
        })
    }

    async fn delete_asset(
        &self,
        owner: &str,
        repo: &str,
        asset_id: u64,
    ) -> Result<(), GithubError> {
        let url = format!("{API_BASE}/repos/{owner}/{repo}/releases/assets/{asset_id}");
        let response = self
            .client
            .delete(&url)
            .map_err(|_| fail("github request build failed"))?
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", API_VERSION)
            .auth(self.auth()?)
            .timeout(self.timeout())
            .max_decoded_body_size(self.max_metadata_bytes)
            .send()
            .await
            .map_err(|_| fail("github asset delete failed"))?;
        let status = response.status().as_u16();
        if status != 204 {
            return Err(fail("github asset delete failed"));
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Deterministic fixture transport for tests
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
struct FixtureReleaseState {
    release: RemoteRelease,
}

#[derive(Debug)]
struct FixtureInner {
    ref_sha: Option<String>,
    ref_kind: String,
    tag_objects: BTreeMap<String, (String, String)>,
    releases: Vec<FixtureReleaseState>,
    assets: BTreeMap<u64, Vec<RemoteAsset>>,
    asset_pages: BTreeMap<(u64, u32), Vec<RemoteAsset>>,
    next_release_id: u64,
    next_asset_id: u64,
    upload_rename_next: bool,
    upload_digest_mismatch_next: bool,
    upload_omit_digest_next: bool,
    upload_size_mismatch_next: bool,
    upload_fail_502_create_starter: bool,
    upload_fail_502_next: Option<String>,
    upload_fail_422_next: bool,
    create_calls: u32,
    upload_calls: u32,
    delete_calls: u32,
}

/// Deterministic in-memory GitHub fixture: a test double, not an adapter.
///
/// It performs no network I/O.
/// `seed_*`, `set_*`, and `fail_*` define every remote result.
/// Tests use those injectors to model staging responses.
/// It implements `GithubApi`, but the trait cannot distinguish
/// it from the real transport.
/// A production caller could report staging success without
/// network traffic.
///
/// It is hidden from rendered docs but is not test-gated.
/// Production wiring is a defect even though it compiles.
/// Use only in `#[cfg(test)]` modules or test crates.
///
/// Fidelity limits: releases stay in seeded order.
/// The fixture applies no filtering.
/// `get_tag` resolves only explicitly registered tag objects.
#[doc(hidden)]
#[derive(Debug)]
pub struct FixtureGithub {
    inner: Mutex<FixtureInner>,
}

impl FixtureGithub {
    /// Create a fixture with an exact lightweight tag.
    pub fn with_tag(commit_sha: &str) -> Self {
        Self {
            inner: Mutex::new(FixtureInner {
                ref_sha: Some(commit_sha.to_owned()),
                ref_kind: "commit".to_owned(),
                tag_objects: BTreeMap::new(),
                releases: Vec::new(),
                assets: BTreeMap::new(),
                asset_pages: BTreeMap::new(),
                next_release_id: 100,
                next_asset_id: 1000,
                upload_rename_next: false,
                upload_digest_mismatch_next: false,
                upload_omit_digest_next: false,
                upload_size_mismatch_next: false,
                upload_fail_502_create_starter: true,
                upload_fail_502_next: None,
                upload_fail_422_next: false,
                create_calls: 0,
                upload_calls: 0,
                delete_calls: 0,
            }),
        }
    }

    /// Set the tag reference (for movement tests).
    pub fn set_ref(&self, sha: Option<String>, kind: &str) {
        let mut inner = self.inner.lock().unwrap();
        inner.ref_sha = sha;
        inner.ref_kind = kind.to_owned();
    }

    /// Register an annotated tag peeling step.
    pub fn add_tag_object(&self, sha: &str, object_type: &str, object_sha: &str) {
        let mut inner = self.inner.lock().unwrap();
        inner.tag_objects.insert(
            sha.to_owned(),
            (object_type.to_owned(), object_sha.to_owned()),
        );
    }

    /// Seed one existing release.
    pub fn seed_release(&self, release: RemoteRelease, assets: Vec<RemoteAsset>) {
        let mut inner = self.inner.lock().unwrap();
        let id = release.id;
        inner.releases.push(FixtureReleaseState { release });
        inner.assets.insert(id, assets);
        if id >= inner.next_release_id {
            inner.next_release_id = id + 1;
        }
    }

    /// Override one remote asset-list page for pagination edge-case tests.
    pub fn set_asset_page(&self, release_id: u64, page: u32, assets: Vec<RemoteAsset>) {
        self.inner
            .lock()
            .unwrap()
            .asset_pages
            .insert((release_id, page), assets);
    }

    /// Fail the next upload for `name` with 502.
    pub fn fail_upload_502_next(&self, name: &str, create_starter: bool) {
        let mut inner = self.inner.lock().unwrap();
        inner.upload_fail_502_next = Some(name.to_owned());
        inner.upload_fail_502_create_starter = create_starter;
    }

    /// Fail the next upload with 422 duplicate.
    pub fn fail_upload_422_next(&self) {
        let mut inner = self.inner.lock().unwrap();
        inner.upload_fail_422_next = true;
    }

    /// Rename the next uploaded asset.
    pub fn rename_next_upload(&self) {
        let mut inner = self.inner.lock().unwrap();
        inner.upload_rename_next = true;
    }

    /// Return a wrong digest for the next upload.
    pub fn digest_mismatch_next(&self) {
        let mut inner = self.inner.lock().unwrap();
        inner.upload_digest_mismatch_next = true;
    }

    /// Return a wrong size for the next upload.
    pub fn size_mismatch_next(&self) {
        let mut inner = self.inner.lock().unwrap();
        inner.upload_size_mismatch_next = true;
    }

    /// Omit the digest field from the next upload response.
    ///
    /// Real uploads answer with a digest, so the fixture returns one by
    /// default; this models a response that leaves it out, which the staging
    /// core must still reject at its final inventory check.
    pub fn omit_digest_next(&self) {
        let mut inner = self.inner.lock().unwrap();
        inner.upload_omit_digest_next = true;
    }

    /// Number of release creations.
    pub fn create_calls(&self) -> u32 {
        self.inner.lock().unwrap().create_calls
    }

    /// Number of upload attempts.
    pub fn upload_calls(&self) -> u32 {
        self.inner.lock().unwrap().upload_calls
    }

    /// Number of asset deletions.
    pub fn delete_calls(&self) -> u32 {
        self.inner.lock().unwrap().delete_calls
    }

    /// Current assets for one release.
    pub fn assets_for(&self, release_id: u64) -> Vec<RemoteAsset> {
        self.inner
            .lock()
            .unwrap()
            .assets
            .get(&release_id)
            .cloned()
            .unwrap_or_default()
    }
}

/// Build a fixture release record for [`FixtureGithub`].
///
/// Test-double helper: see that type's documentation.
#[doc(hidden)]
pub fn fixture_release(
    id: u64,
    tag: &str,
    title: &str,
    body: &str,
    prerelease: bool,
    draft: bool,
    immutable: bool,
) -> RemoteRelease {
    RemoteRelease {
        id,
        tag_name: tag.to_owned(),
        name: title.to_owned(),
        body: body.to_owned(),
        draft,
        immutable,
        prerelease,
        upload_url: format!("{UPLOAD_BASE}/repos/acme/widget/releases/{id}/assets{{?name,label}}"),
    }
}

/// Build a fixture asset record for [`FixtureGithub`].
///
/// Test-double helper: see that type's documentation.
#[doc(hidden)]
pub fn fixture_asset(
    id: u64,
    name: &str,
    size: u64,
    state: &str,
    sha_hex: Option<&str>,
) -> RemoteAsset {
    RemoteAsset {
        id,
        name: name.to_owned(),
        size,
        state: state.to_owned(),
        digest: sha_hex.map(|hex| format!("sha256:{hex}")),
    }
}

impl GithubApi for FixtureGithub {
    async fn get_ref(
        &self,
        _owner: &str,
        _repo: &str,
        _tag: &str,
    ) -> Result<RefTarget, GithubError> {
        let inner = self.inner.lock().unwrap();
        match &inner.ref_sha {
            None => Err(fail("github resource not found")),
            Some(sha) => Ok(RefTarget {
                sha: sha.clone(),
                kind: inner.ref_kind.clone(),
            }),
        }
    }

    async fn get_tag(
        &self,
        _owner: &str,
        _repo: &str,
        sha: &str,
    ) -> Result<TagObject, GithubError> {
        let inner = self.inner.lock().unwrap();
        match inner.tag_objects.get(sha) {
            None => Err(fail("github resource not found")),
            Some((kind, object_sha)) => Ok(TagObject {
                object_sha: object_sha.clone(),
                object_type: kind.clone(),
            }),
        }
    }

    async fn list_releases(
        &self,
        _owner: &str,
        _repo: &str,
        page: u32,
    ) -> Result<Vec<RemoteRelease>, GithubError> {
        let inner = self.inner.lock().unwrap();
        // Paged like the real endpoint rather than returning everything on
        // page 1: a listing that can never fill a page cannot exercise the
        // bound-exhaustion path at all.
        let all: Vec<RemoteRelease> = inner
            .releases
            .iter()
            .map(|state| state.release.clone())
            .collect();
        let start = (page.saturating_sub(1) as usize).saturating_mul(LIST_PAGE_SIZE);
        Ok(all.into_iter().skip(start).take(LIST_PAGE_SIZE).collect())
    }

    async fn create_release(
        &self,
        owner: &str,
        repo: &str,
        tag: &str,
        title: &str,
        body: &str,
        prerelease: bool,
    ) -> Result<RemoteRelease, GithubError> {
        let mut inner = self.inner.lock().unwrap();
        inner.create_calls += 1;
        // GitHub answers `422 already_exists` for a tag that already has a
        // release. Accepting it here would let a caller create a second
        // release for one tag and report success, which is exactly what the
        // staging core must never do.
        if inner
            .releases
            .iter()
            .any(|state| state.release.tag_name == tag)
        {
            return Err(fail(
                "http_422_already_exists: github rejected duplicate release tag",
            ));
        }
        let id = inner.next_release_id;
        inner.next_release_id += 1;
        let release = RemoteRelease {
            id,
            tag_name: tag.to_owned(),
            name: title.to_owned(),
            body: body.to_owned(),
            draft: true,
            immutable: false,
            prerelease,
            upload_url: format!(
                "{UPLOAD_BASE}/repos/{owner}/{repo}/releases/{id}/assets{{?name,label}}"
            ),
        };
        inner.releases.push(FixtureReleaseState {
            release: release.clone(),
        });
        inner.assets.insert(id, Vec::new());
        Ok(release)
    }

    async fn list_assets(
        &self,
        _owner: &str,
        _repo: &str,
        release_id: u64,
        page: u32,
    ) -> Result<Vec<RemoteAsset>, GithubError> {
        let inner = self.inner.lock().unwrap();
        if let Some(page_assets) = inner.asset_pages.get(&(release_id, page)) {
            return Ok(page_assets.clone());
        }
        let all = inner.assets.get(&release_id).cloned().unwrap_or_default();
        let start = (page.saturating_sub(1) as usize).saturating_mul(LIST_PAGE_SIZE);
        Ok(all.into_iter().skip(start).take(LIST_PAGE_SIZE).collect())
    }

    async fn upload_asset(
        &self,
        _owner: &str,
        _repo: &str,
        release_id: u64,
        name: &str,
        mut file: Box<dyn std::io::Read + Send>,
        length: u64,
        _content_type: &str,
    ) -> Result<RemoteAsset, GithubError> {
        use std::io::Read;
        let mut bytes = Vec::new();
        file.read_to_end(&mut bytes)
            .map_err(|_| fail("fixture upload read failed"))?;
        if bytes.len() as u64 != length {
            return Err(fail("fixture upload length mismatch"));
        }
        let mut inner = self.inner.lock().unwrap();
        inner.upload_calls += 1;
        if inner.upload_fail_422_next {
            inner.upload_fail_422_next = false;
            return Err(fail("http_422_duplicate: github rejected duplicate name"));
        }
        if let Some(expected) = inner.upload_fail_502_next.clone() {
            if expected == name {
                inner.upload_fail_502_next = None;
                if inner.upload_fail_502_create_starter {
                    let id = inner.next_asset_id;
                    inner.next_asset_id += 1;
                    inner
                        .assets
                        .entry(release_id)
                        .or_default()
                        .push(RemoteAsset {
                            id,
                            name: name.to_owned(),
                            size: 0,
                            state: "starter".to_owned(),
                            digest: None,
                        });
                }
                return Err(fail("http_502: github reported a gateway failure"));
            }
        }
        use sha2::Digest;
        let digest: String = sha2::Sha256::digest(&bytes)
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        let id = inner.next_asset_id;
        inner.next_asset_id += 1;
        let record_name = if inner.upload_rename_next {
            inner.upload_rename_next = false;
            format!("{name}.renamed")
        } else {
            name.to_owned()
        };
        let size = if inner.upload_size_mismatch_next {
            inner.upload_size_mismatch_next = false;
            bytes.len() as u64 + 1
        } else {
            bytes.len() as u64
        };
        let digest_value = if inner.upload_digest_mismatch_next {
            inner.upload_digest_mismatch_next = false;
            Some("sha256:".to_owned() + &"0".repeat(64))
        } else if inner.upload_omit_digest_next {
            inner.upload_omit_digest_next = false;
            None
        } else {
            Some(format!("sha256:{digest}"))
        };
        let record = RemoteAsset {
            id,
            name: record_name,
            size,
            state: "uploaded".to_owned(),
            digest: digest_value,
        };
        inner
            .assets
            .entry(release_id)
            .or_default()
            .push(record.clone());
        Ok(record)
    }

    async fn delete_asset(
        &self,
        _owner: &str,
        _repo: &str,
        asset_id: u64,
    ) -> Result<(), GithubError> {
        let mut inner = self.inner.lock().unwrap();
        inner.delete_calls += 1;
        for assets in inner.assets.values_mut() {
            if let Some(position) = assets.iter().position(|asset| asset.id == asset_id) {
                assets.remove(position);
                return Ok(());
            }
        }
        Err(fail("github asset delete failed"))
    }
}

#[cfg(test)]
mod tests;

/// M003l: the SHA-256 acceptance set is the canonical one, applied here
/// rather than restated.
#[cfg(test)]
mod m003l_rule_convergence_tests {
    use super::*;

    #[test]
    fn sha256_acceptance_set_is_the_canonical_one() {
        const DIGESTS: &[&str] = &[
            "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90",
            "0000000000000000000000000000000000000000000000000000000000000000",
            "A1B2C3D4E5F60718293A4B5C6D7E8F90A1B2C3D4E5F60718293A4B5C6D7E8F90",
            "g1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90",
            "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f9",
            "a1b2c3d4",
            "",
        ];
        for digest in DIGESTS {
            assert_eq!(
                validate_sha256(digest).is_ok(),
                eggpack_manifest::validate_sha256_hex(digest).is_ok(),
                "GitHub call site diverged for {digest:?}"
            );
        }
        // The all-zeros placeholder is refused.
        assert!(validate_sha256(&"0".repeat(64)).is_err());
        // A canonical digest is accepted.
        assert!(validate_sha256(
            "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90"
        )
        .is_ok());
    }

    #[test]
    fn exact_tag_safety_is_the_canonical_one() {
        // Every character class the pre-convergence rule refused is still
        // refused, and the canonical rule adds the git-ref-path concerns.
        for tag in [
            "",
            "v1.2.3#",
            "v1.2.3@",
            "v1.2.3'",
            "v1.2.3\"",
            "v1.2.3`",
            "v1.2.3$",
            "v1.2.3?",
            "v1.2.3 ",
            "v1.2.3\\",
            "v1.2.3^",
            "v1.2.3:",
            "v1.2.3*",
            "v1.2.3[",
            "v1.2.3~",
            "v1.2.3.",
            "v1..2.3",
            "/v1.2.3",
            "v1.2.3/",
            "release/v1.2.3.lock",
        ] {
            assert!(
                validate_tag(tag).is_err(),
                "GitHub accepted an unsafe tag {tag:?}"
            );
        }
        // A canonical version tag and a multi-segment tag stay accepted.
        assert!(validate_tag("v1.2.3").is_ok());
        assert!(validate_tag("release/v1.2.3").is_ok());
    }
}

/// M003n: the staging payload has exactly one builder.
///
/// Both public entry points and both installer presentations are covered by
/// byte-exact evidence, so a divergence between the presentation-specific
/// work and the shared algorithm fails loudly.
#[cfg(test)]
mod m003n_consolidation_tests {
    use super::*;
    use eggpack_manifest::{ArtifactForm, ArtifactRecord, ReleaseManifest, TargetRecord};

    /// Byte-exact golden for the generated-default staging payload.
    const M003N_GOLDEN_GENERATED_DEFAULT: &str = r#"{"schema_version":1,"product_id":"eggsact","release_id":"1.2.6","source_revision":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","owner":"acme","repository":"widget","tag":"v1.2.3","title":"widget 1.2.3","prerelease":false,"body":"notes","assets":[{"name":"eggsact-1.2.6-aarch64-apple-darwin","path":"eggsact-1.2.6-aarch64-apple-darwin","size":4,"sha256":"230d8358dc8e8890b4c58deeb62912ee2f20357ae92a5cc861b98e68fe31acb5","media_type":"application/octet-stream","kind":"finalized_artifact"},{"name":"eggsact-1.2.6-aarch64-apple-darwin.sha256","path":"eggsact-1.2.6-aarch64-apple-darwin.sha256","size":101,"sha256":"4f071dece3fa37c30e0dd043b1a797ac4ad3a667797416b86021874a38b796a2","media_type":"text/plain","kind":"checksum_sidecar"},{"name":"eggsact-1.2.6-x86_64-unknown-linux-gnu","path":"eggsact-1.2.6-x86_64-unknown-linux-gnu","size":4,"sha256":"230d8358dc8e8890b4c58deeb62912ee2f20357ae92a5cc861b98e68fe31acb5","media_type":"application/octet-stream","kind":"finalized_artifact"},{"name":"eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256","path":"eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256","size":105,"sha256":"c9529680b9d3bff4dc33c13385829307e2d18683c5dd23f0e62075d8bfd8c706","media_type":"text/plain","kind":"checksum_sidecar"},{"name":"install.ps1","path":"install.ps1","size":2409,"sha256":"a58fd2089f7f93d77b49b095be040eb5d1ac0c6d3fcd6d8795a0f37e8b36c00c","media_type":"text/x-powershell","kind":"powershell_installer"},{"name":"install.sh","path":"install.sh","size":2990,"sha256":"d31c315d6a2ada9087f6206437b427765cad3333c5fc1358df3faadfe9fdd8ce","media_type":"text/x-shellscript","kind":"posix_installer"},{"name":"release-manifest.json","path":"release-manifest.json","size":587,"sha256":"6fdc51ab9a646b8b219eeba7b83ced5768ea704d1317dbb47d2fc07bf26dd9dd","media_type":"application/json","kind":"release_manifest"}]}"#;

    /// Byte-exact golden for the product-wrappers staging payload.
    const M003N_GOLDEN_PRODUCT_WRAPPERS: &str = r#"{"schema_version":1,"product_id":"eggsact","release_id":"1.2.6","source_revision":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","owner":"acme","repository":"widget","tag":"v1.2.3","title":"widget 1.2.3","prerelease":false,"body":"notes","assets":[{"name":"eggsact-1.2.6-aarch64-apple-darwin","path":"eggsact-1.2.6-aarch64-apple-darwin","size":4,"sha256":"230d8358dc8e8890b4c58deeb62912ee2f20357ae92a5cc861b98e68fe31acb5","media_type":"application/octet-stream","kind":"finalized_artifact"},{"name":"eggsact-1.2.6-aarch64-apple-darwin.sha256","path":"eggsact-1.2.6-aarch64-apple-darwin.sha256","size":101,"sha256":"4f071dece3fa37c30e0dd043b1a797ac4ad3a667797416b86021874a38b796a2","media_type":"text/plain","kind":"checksum_sidecar"},{"name":"eggsact-1.2.6-x86_64-unknown-linux-gnu","path":"eggsact-1.2.6-x86_64-unknown-linux-gnu","size":4,"sha256":"230d8358dc8e8890b4c58deeb62912ee2f20357ae92a5cc861b98e68fe31acb5","media_type":"application/octet-stream","kind":"finalized_artifact"},{"name":"eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256","path":"eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256","size":105,"sha256":"c9529680b9d3bff4dc33c13385829307e2d18683c5dd23f0e62075d8bfd8c706","media_type":"text/plain","kind":"checksum_sidecar"},{"name":"install-exact.ps1","path":"install-exact.ps1","size":2409,"sha256":"a58fd2089f7f93d77b49b095be040eb5d1ac0c6d3fcd6d8795a0f37e8b36c00c","media_type":"text/x-powershell","kind":"powershell_installer"},{"name":"install-exact.sh","path":"install-exact.sh","size":2990,"sha256":"d31c315d6a2ada9087f6206437b427765cad3333c5fc1358df3faadfe9fdd8ce","media_type":"text/x-shellscript","kind":"posix_installer"},{"name":"install.ps1","path":"install.ps1","size":37,"sha256":"3f078877b9c699b15c410e783e6bb6ca3da1b7881ac673f12ebaf7440adc9c64","media_type":"text/x-powershell","kind":"product_powershell_wrapper"},{"name":"install.sh","path":"install.sh","size":31,"sha256":"61a73587bfb5acdc2e718bfad3797b35f971cfa40d053d187792b07b6e095ffe","media_type":"text/x-shellscript","kind":"product_posix_wrapper"},{"name":"release-manifest.json","path":"release-manifest.json","size":587,"sha256":"6fdc51ab9a646b8b219eeba7b83ced5768ea704d1317dbb47d2fc07bf26dd9dd","media_type":"application/json","kind":"release_manifest"}]}"#;

    fn temp_root(label: &str) -> PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static NEXT: AtomicU64 = AtomicU64::new(0);
        loop {
            let id = NEXT.fetch_add(1, Ordering::Relaxed);
            let path = std::env::temp_dir().join(format!(
                "eggpack-gh-m003n-{label}-{}-{id}",
                std::process::id()
            ));
            match std::fs::create_dir(&path) {
                Ok(()) => return path,
                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
                Err(error) => panic!("create temp: {error}"),
            }
        }
    }

    fn sha_hex(bytes: &[u8]) -> String {
        use sha2::Digest;
        sha2::Sha256::digest(bytes)
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect()
    }

    fn test_policy() -> GitHubDraftPolicyV1 {
        GitHubDraftPolicyV1 {
            schema_version: 1,
            owner: "acme".to_owned(),
            repository: "widget".to_owned(),
            tag: "v1.2.3".to_owned(),
            release_identity_schema_version: None,
            release_identity_mode: None,
            release_id: None,
            source_revision: None,
            title: "widget 1.2.3".to_owned(),
            body: "notes".to_owned(),
            prerelease: false,
            token_env: "GITHUB_TOKEN".to_owned(),
            request_timeout_secs: 30,
            max_metadata_bytes: 1_000_000,
            max_list_pages: 5,
        }
    }

    fn direct_contract() -> DistributionContract {
        DistributionContract::parse_toml_str(include_str!(
            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
        ))
        .unwrap()
    }

    fn direct_manifest(release: &str, source: &str) -> ReleaseManifest {
        let mk = |target: &str| TargetRecord {
            target: target.to_owned(),
            form: ArtifactForm::Direct {
                artifact: ArtifactRecord {
                    name: format!("eggsact-{release}-{target}"),
                    size: 4,
                    sha256: sha_hex(b"body"),
                },
                install: "eggsact".to_owned(),
            },
        };
        ReleaseManifest {
            schema_version: 1,
            product_id: "eggsact".to_owned(),
            release_id: release.to_owned(),
            source_revision: source.to_owned(),
            targets: vec![mk("aarch64-apple-darwin"), mk("x86_64-unknown-linux-gnu")],
            evidence_references: Vec::new(),
        }
    }

    fn write_finalized_root(
        contract: &DistributionContract,
        manifest: &ReleaseManifest,
        root: &Path,
    ) {
        std::fs::create_dir(root).unwrap();
        let mut files: BTreeMap<String, bool> = BTreeMap::new();
        for target in &manifest.targets {
            let expanded = contract
                .expand(&target.target, &manifest.release_id)
                .unwrap();
            match expanded.assets {
                ExpandedAssets::Direct(direct) => {
                    files.insert(direct.asset_file, true);
                    files.insert(direct.sidecar_file, false);
                }
                ExpandedAssets::Bundle(bundle) => {
                    for entry in bundle.entries.into_iter() {
                        files.insert(entry.asset_file, true);
                        files.insert(entry.sidecar_file, false);
                    }
                }
                ExpandedAssets::Archive(archive) => {
                    files.insert(archive.archive_file, true);
                    files.insert(archive.sidecar_file, false);
                }
            }
        }
        for (name, is_artifact) in files {
            if is_artifact {
                std::fs::write(root.join(&name), b"body").unwrap();
            } else {
                let artifact = name.strip_suffix(".sha256").unwrap().to_owned();
                let content = format!("{}  {artifact}\n", sha_hex(b"body"));
                std::fs::write(root.join(&name), content).unwrap();
            }
        }
    }

    fn wrapper_presentation() -> InstallerPresentationV1 {
        InstallerPresentationV1 {
            schema_version: 1,
            mode: InstallerPresentationModeV1::ProductWrappers(ProductWrapperSourcesV1 {
                posix_source: "packaging/install.sh".to_owned(),
                powershell_source: "packaging/install.ps1".to_owned(),
                generated_posix_name: "install-exact.sh".to_owned(),
                generated_powershell_name: "install-exact.ps1".to_owned(),
            }),
        }
    }

    fn write_wrapper_sources(root: &Path, posix: &[u8], powershell: &[u8]) {
        std::fs::create_dir_all(root.join("packaging")).unwrap();
        std::fs::write(root.join("packaging/install.sh"), posix).unwrap();
        std::fs::write(root.join("packaging/install.ps1"), powershell).unwrap();
    }

    /// The staged file inventory of one materialized payload, with the exact
    /// bytes of every staged file.
    fn staged_inventory(staged: &Path) -> BTreeMap<String, Vec<u8>> {
        let mut inventory = BTreeMap::new();
        for entry in std::fs::read_dir(staged).unwrap() {
            let entry = entry.unwrap();
            let name = entry.file_name().to_string_lossy().into_owned();
            let bytes = std::fs::read(entry.path()).unwrap();
            inventory.insert(name, bytes);
        }
        inventory
    }

    /// Materialize the generated-default payload.
    fn materialize_default(
        parent: &Path,
        contract: &DistributionContract,
        manifest: &ReleaseManifest,
        policy: &GitHubDraftPolicyV1,
        install_policy: &BootstrapInstallPolicyV1,
        finalized: &Path,
        label: &str,
    ) -> (StagingPayloadV1, PathBuf) {
        let staged = parent.join(label);
        let payload = prepare_staging_payload(
            contract,
            manifest,
            finalized,
            policy,
            install_policy,
            &staged,
        )
        .unwrap();
        (payload, staged)
    }

    /// Materialize the product-wrappers payload.
    fn materialize_wrappers(
        parent: &Path,
        contract: &DistributionContract,
        manifest: &ReleaseManifest,
        policy: &GitHubDraftPolicyV1,
        install_policy: &BootstrapInstallPolicyV1,
        finalized: &Path,
        label: &str,
    ) -> (StagingPayloadV1, PathBuf) {
        let source_root = parent.join("consumer");
        write_wrapper_sources(
            &source_root,
            b"#!/bin/sh\n# product wrapper v1\n",
            b"# product wrapper v1\r\nWrite-Host hi\r\n",
        );
        let staged = parent.join(label);
        let payload = prepare_staging_payload_with_presentation(
            contract,
            manifest,
            finalized,
            policy,
            install_policy,
            &wrapper_presentation(),
            &source_root,
            &staged,
        )
        .unwrap();
        (payload, staged)
    }

    #[test]
    fn m003n_generated_default_payload_matches_golden() {
        let contract = direct_contract();
        let manifest = direct_manifest("1.2.6", &"a".repeat(40));
        let install_policy = BootstrapInstallPolicyV1::empty();
        let policy = test_policy();
        let parent = temp_root("golden-default");
        let finalized = parent.join("finalized");
        write_finalized_root(&contract, &manifest, &finalized);
        let (payload, staged) = materialize_default(
            &parent,
            &contract,
            &manifest,
            &policy,
            &install_policy,
            &finalized,
            "staging",
        );
        assert_eq!(payload.to_json().unwrap(), M003N_GOLDEN_GENERATED_DEFAULT);
        // The staged files are the golden ones, byte for byte.
        let inventory = staged_inventory(&staged);
        assert_eq!(inventory.len(), 7);
        assert_eq!(
            inventory.get("install.sh").map(|b| b.len()),
            Some(2990),
            "the generated POSIX installer changed size"
        );
        std::fs::remove_dir_all(parent).unwrap();
    }

    #[test]
    fn m003n_product_wrappers_payload_matches_golden() {
        let contract = direct_contract();
        let manifest = direct_manifest("1.2.6", &"a".repeat(40));
        let install_policy = BootstrapInstallPolicyV1::empty();
        let policy = test_policy();
        let parent = temp_root("golden-wrappers");
        let finalized = parent.join("finalized");
        write_finalized_root(&contract, &manifest, &finalized);
        let (payload, staged) = materialize_wrappers(
            &parent,
            &contract,
            &manifest,
            &policy,
            &install_policy,
            &finalized,
            "staging",
        );
        assert_eq!(payload.to_json().unwrap(), M003N_GOLDEN_PRODUCT_WRAPPERS);
        let inventory = staged_inventory(&staged);
        assert_eq!(inventory.len(), 9);
        assert_eq!(inventory.get("install.sh").map(|b| b.len()), Some(31));
        assert_eq!(
            inventory.get("install-exact.sh").map(|b| b.len()),
            Some(2990)
        );
        std::fs::remove_dir_all(parent).unwrap();
    }

    #[test]
    fn m003n_both_staging_entry_points_produce_byte_identical_payloads() {
        let contract = direct_contract();
        let manifest = direct_manifest("1.2.6", &"a".repeat(40));
        let install_policy = BootstrapInstallPolicyV1::empty();
        let policy = test_policy();
        let parent = temp_root("entry-points");
        let finalized = parent.join("finalized");
        write_finalized_root(&contract, &manifest, &finalized);
        let (legacy, legacy_dir) = materialize_default(
            &parent,
            &contract,
            &manifest,
            &policy,
            &install_policy,
            &finalized,
            "legacy",
        );
        let modern_dir = parent.join("modern");
        let modern = prepare_staging_payload_with_presentation(
            &contract,
            &manifest,
            &finalized,
            &policy,
            &install_policy,
            &InstallerPresentationV1::generated_default(),
            &parent,
            &modern_dir,
        )
        .unwrap();
        // The two entry points are one implementation: byte-identical
        // payloads and byte-identical staged files.
        assert_eq!(
            legacy.to_json().unwrap(),
            modern.to_json().unwrap(),
            "the two staging entry points diverged"
        );
        let legacy_files = staged_inventory(&legacy_dir);
        let modern_files = staged_inventory(&modern_dir);
        assert_eq!(
            legacy_files.keys().collect::<Vec<_>>(),
            modern_files.keys().collect::<Vec<_>>(),
            "the two staging entry points staged different files"
        );
        for (name, bytes) in &legacy_files {
            assert_eq!(
                bytes,
                modern_files.get(name).unwrap(),
                "staged bytes differ for {name}"
            );
        }
        std::fs::remove_dir_all(parent).unwrap();
    }

    #[test]
    fn m003n_shared_algorithm_regions_are_identical_across_presentations() {
        let contract = direct_contract();
        let manifest = direct_manifest("1.2.6", &"a".repeat(40));
        let install_policy = BootstrapInstallPolicyV1::empty();
        let policy = test_policy();
        let parent = temp_root("shared-regions");
        let finalized = parent.join("finalized");
        write_finalized_root(&contract, &manifest, &finalized);
        let (default_payload, default_dir) = materialize_default(
            &parent,
            &contract,
            &manifest,
            &policy,
            &install_policy,
            &finalized,
            "default",
        );
        let (wrappers_payload, wrappers_dir) = materialize_wrappers(
            &parent,
            &contract,
            &manifest,
            &policy,
            &install_policy,
            &finalized,
            "wrappers",
        );
        // The payload metadata is presentation-independent.
        assert_eq!(default_payload.product_id, wrappers_payload.product_id);
        assert_eq!(default_payload.release_id, wrappers_payload.release_id);
        assert_eq!(
            default_payload.source_revision,
            wrappers_payload.source_revision
        );
        assert_eq!(default_payload.owner, wrappers_payload.owner);
        assert_eq!(default_payload.repository, wrappers_payload.repository);
        assert_eq!(default_payload.tag, wrappers_payload.tag);
        assert_eq!(default_payload.title, wrappers_payload.title);
        assert_eq!(default_payload.prerelease, wrappers_payload.prerelease);
        assert_eq!(default_payload.body, wrappers_payload.body);
        // Every non-installer asset is identical: the same name, path, size,
        // digest, media type, and kind.
        let shared = |payload: &StagingPayloadV1| {
            payload
                .assets
                .iter()
                .filter(|asset| {
                    !matches!(
                        asset.kind,
                        StagingAssetKind::PosixInstaller
                            | StagingAssetKind::PowershellInstaller
                            | StagingAssetKind::ProductPosixWrapper
                            | StagingAssetKind::ProductPowershellWrapper
                    )
                })
                .map(|asset| {
                    (
                        asset.name.clone(),
                        asset.path.clone(),
                        asset.size,
                        asset.sha256.clone(),
                        asset.media_type.clone(),
                        format!("{:?}", asset.kind),
                    )
                })
                .collect::<Vec<_>>()
        };
        assert_eq!(
            shared(&default_payload),
            shared(&wrappers_payload),
            "the shared inventory regions diverged across presentations"
        );
        // The staged finalized assets and the standalone manifest are the
        // same bytes in both presentations.
        let default_files = staged_inventory(&default_dir);
        let wrappers_files = staged_inventory(&wrappers_dir);
        for (name, bytes) in &default_files {
            if name == "install.sh" || name == "install.ps1" {
                continue;
            }
            assert_eq!(
                bytes,
                wrappers_files.get(name).unwrap(),
                "shared staged bytes differ for {name}"
            );
        }
        std::fs::remove_dir_all(parent).unwrap();
    }
}