polyc-crypto 2026.8.1

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
//! HITL approval payload encoders/decoders and signer.
//!
//! The approval flow persists two event payloads in the conversation eventlog:
//!
//! * `approval_request` — minted when `polyc_agent::run_turn` surfaces a
//!   pending tool call that needs human consent.
//! * `approval_response` — minted by `ApprovalService::Respond` (a human
//!   decision) or, non-interactively, by the `POLYCHROME_APPROVAL_MODE`
//!   machine-approval path (the reviewer-agent auto-review or the blanket
//!   approve-all mode) carrying a signed decision, distinguishable from a human
//!   one only by its signed `reason` (see [`auto_review_reason`] /
//!   [`AUTO_REVIEW_REASON_PREFIX`] / [`APPROVE_ALL_DANGEROUS_REASON`]).
//!
//! The encoders / decoders live in `polyc-crypto` (this crate) rather
//! than the control-plane binary so the harness pod can verify inbound
//! `approval_response` payloads on its own — the harness sits in a sandbox
//! and shouldn't trust the wire blindly.
//!
//! [`verify_signed_receipt`] keeps one frozen canonical per receipt schema
//! version, v1 included, and every version it has ever frozen stays. That is
//! not the legacy shim this repo forbids: a signature covers the exact bytes it
//! was minted over, and those bytes are already in an append-only log. Deleting
//! the v1 reader would migrate nothing — it would leave the deployment unable
//! to verify its own settled payment history. Read the per-version builders as
//! cryptographic verification of history, not as a compatibility fallback, and
//! only ever add to them.

use serde::Serialize;
use serde_json::Value;
use std::collections::HashSet;

use crate::signed::{Envelope, canonical_bytes};
use crate::verify;

pub use crate::signing_role::ApprovalSigner;

/// JSON payload for an `approval_request` event.
///
/// `request_id` is the model's tool-call id — stable for the lifetime of the
/// turn and used by `ApprovalService::Respond` to address the matching
/// response.
/// `sandbox_mode` is the sandbox/permission mode (`POLYCHROME_SANDBOX_MODE`) the
/// harness was running under when it paused this call. The control plane reads it
/// back at respond time and signs it into the response, so a remembered approval
/// is bound to the mode it was granted under.
/// `reason` is the OVERRIDE explanation for why the call is gated — empty for an
/// ordinary gated call, non-empty only for the lethal-trifecta / Rule-of-Two
/// containment override. It is presentation + audit (NOT covered by any
/// signature — the `approval_request` event itself is unsigned; the *response*
/// is what gets signed), so the durable log records WHY a trifecta-gated call
/// was paused, and the edge can render it on the approval card.
/// `missing_capabilities` records the capability shortfall the gate computed
/// when it paused the call (`#595`): the stable kebab-case names of the
/// capabilities the call required but was not granted. Read back at respond
/// time and signed into the response as `covered_capabilities`, so a
/// remembered grant is scoped to exactly what the approver saw it cover.
/// Empty for an ordinary policy/sandbox gate.
/// `preview_json` (`#1496`) is the pre-serialized computed-preview
/// enrichment — opaque at this layer, exactly like `args_json` above — or
/// empty for every call the enrichment doesn't apply to (anything but
/// `routine_create`). Recorded durably here (not just on the live wire
/// response) so the `ListPending` recovery path re-renders the SAME preview a
/// lost-stream card showed, never a re-derivation that could drift.
///
/// This is the one payload in this module still built as a
/// [`serde_json::Value`], so its key order — and its `preview`'s — follows the
/// map's, which `serde_json/preserve_order` decides per build (`#1842`). That
/// is deliberate and safe: an `approval_request` carries no signature, so no
/// verification depends on its bytes, and every reader looks its fields up by
/// key. `preview` is caller-supplied JSON whose own key order belongs to the
/// caller in any case. Nothing here can be frozen, and nothing needs to be —
/// the signed side is the response.
#[must_use]
pub fn request_payload(
    request_id: &str,
    tool_name: &str,
    args_json: &str,
    sandbox_mode: &str,
    reason: &str,
    missing_capabilities: &[String],
    preview_json: &str,
) -> Vec<u8> {
    // Null when there is no preview (the overwhelming common case — every
    // call but `routine_create`), rather than omitting the key: an absent
    // key and an explicit null both decode to "no preview" at
    // `decode_request_preview_json`, so this is a style choice, made for
    // symmetry with the other always-present fields on this payload.
    let preview: Value = if preview_json.is_empty() {
        Value::Null
    } else {
        serde_json::from_str(preview_json).unwrap_or(Value::Null)
    };
    // canonical-allow: an `approval_request` carries no signature (the *response*
    // is what gets signed), so no verification depends on these bytes, and every
    // reader looks its fields up by key. `preview` is caller-supplied JSON whose
    // own key order belongs to the caller in any case — nothing here can be
    // frozen, and nothing needs to be. See the doc comment above.
    serde_json::json!({
        "tool_name": tool_name,
        "args_json": args_json,
        "request_id": request_id,
        "sandbox_mode": sandbox_mode,
        "reason": reason,
        "missing_capabilities": missing_capabilities,
        "preview": preview,
    })
    .to_string()
    .into_bytes()
}

/// The single source for the signed `approval_response` canonical JSON. Both the
/// signing path ([`response_payload`]) and the verifying paths
/// ([`verify_signed_response`], [`verify_wire_response`]) route through this so
/// the covered field set/order cannot drift. Adding/renaming/reordering here is a
/// signed-contract change.
///
/// The signature binds the approval to the exact call identity (`request_id`,
/// `tool_name`, `args_json`) so a re-emitted same-id call with different
/// args/tool cannot inherit it, AND — for a "don't ask again" decision — to
/// `approved_for_session` plus the `caller` the memory is scoped to, so a
/// remembered approval is per-caller and unforgeable. A one-shot approval simply
/// signs `approved_for_session: false`.
///
/// `approver` (`#1025`, RFC 8693's `act`/actor claim, distinct from `caller`'s
/// `sub`/subject) is the identity that actually resolved this decision, when
/// the edge supplied one — NOT necessarily the same persona as `caller` (the
/// paused turn's own beneficiary): an admin approving on someone else's
/// behalf signs a DIFFERENT `approver` than `caller`. Omitted from the
/// canonical entirely when empty (rather than signed as `""`) so every
/// `approval_response` persisted before this field existed — and every one
/// an edge that doesn't yet supply an approver identity signs today — stays
/// byte-identical and continues to verify unchanged; only a genuinely
/// non-empty `approver` changes the signed shape, and that decision is
/// always signed by code that already knows about this field.
///
/// `sandbox_mode` is the sandbox/permission mode (`POLYCHROME_SANDBOX_MODE`) the
/// PAUSED turn ran under, resolved server-side from the request. Binding it means
/// a remembered approval granted under one mode cannot be replayed to auto-
/// approve a later call running under a different (e.g. more-privileged) mode —
/// the harness re-prompts. Empty when no mode was recorded.
///
/// `conversation_id` and `nonce` make the response a SINGLE-USE, conversation-
/// bound capability token (`#370`, closes `#77` bug 3B). `conversation_id` binds
/// the approval to the one conversation it was granted in, so a signed response
/// copied into a different conversation's log fails to verify against that
/// conversation. `nonce` is a per-approval unique value the consumer records on
/// use, so a captured token cannot be re-presented after it has been spent. Both
/// are covered by the signature, so neither can be re-targeted or replayed
/// without invalidating it.
/// `covered_capabilities` (`#595`) records the capability shortfall this
/// approval covered — the missing set the gate computed when it paused the
/// call. Covered by the signature, so the effective session-grant key is
/// (caller, tool, covered capabilities): if the tool's required set later
/// grows, the old grant does not cover the new capability and the gate asks
/// again. Empty for an approval of an ordinary policy/sandbox gate.
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field of the canonical contract
fn response_canonical(
    request_id: &str,
    tool_name: &str,
    args_json: &str,
    modified_args_json: &str,
    approved: bool,
    approved_for_session: bool,
    covered_capabilities: &[String],
    caller: &str,
    approver_id: &str,
    sandbox_mode: &str,
    reason: &str,
    injected_context: &str,
    conversation_id: &str,
    nonce: &str,
) -> Vec<u8> {
    canonical_bytes(&ResponseCanonical {
        body: ResponseBody {
            request_id,
            tool_name,
            args_json,
            modified_args_json,
            approved,
            approved_for_session,
            covered_capabilities,
            caller,
            sandbox_mode,
            reason,
            injected_context,
            conversation_id,
            nonce,
        },
        approver: approver_id,
    })
}

/// The thirteen `approval_response` fields every decision signs, in their
/// frozen order.
///
/// Split out from [`ResponseCanonical`] so the canonical and the persisted
/// payload ([`ResponseFull`]) share one declaration of the body — they place
/// the optional `approver` differently (last in both, but the payload has the
/// two provenance fields in between), and that is the only difference between
/// them.
#[derive(Serialize)]
struct ResponseBody<'a> {
    request_id: &'a str,
    tool_name: &'a str,
    args_json: &'a str,
    modified_args_json: &'a str,
    approved: bool,
    approved_for_session: bool,
    covered_capabilities: &'a [String],
    caller: &'a str,
    sandbox_mode: &'a str,
    reason: &'a str,
    injected_context: &'a str,
    conversation_id: &'a str,
    nonce: &'a str,
}

/// The signed `approval_response` canonical: the body plus the optional
/// `approver`.
///
/// `approver` is skipped entirely when empty rather than signed as `""` (see
/// [`response_canonical`], `#1025`), which keeps every `approval_response`
/// persisted before the field existed byte-identical and still verifiable.
#[derive(Serialize)]
struct ResponseCanonical<'a> {
    #[serde(flatten)]
    body: ResponseBody<'a>,
    #[serde(skip_serializing_if = "str::is_empty")]
    approver: &'a str,
}

/// The persisted `approval_response` payload: the body, the two provenance
/// fields, then the optional `approver`.
///
/// The `approver` trails the signature fields because that is where appending
/// it to the built object always put it, and the order is now the source's
/// rather than a map's (`#1842`).
#[derive(Serialize)]
struct ResponseFull<'a> {
    #[serde(flatten)]
    body: ResponseBody<'a>,
    signed_by: String,
    signature_hex: String,
    #[serde(skip_serializing_if = "str::is_empty")]
    approver: &'a str,
}

/// JSON payload for an `approval_response` event.
///
/// The signature commits to the canonical (unsigned) JSON form: the call
/// identity (`request_id`, `tool_name`, `args_json`), the decision
/// (`approved`), the session scope
/// (`approved_for_session`) and the `caller` it is bound to. `signed_by` and
/// `signature_hex` are populated *after* the signer runs and are NOT covered by
/// the signature.
///
/// Each parameter is a distinct signed field, so they're passed individually
/// rather than wrapped in a struct (the canonical form is the contract).
///
/// `conversation_id` binds the token to the conversation it was granted in and
/// `nonce` is a per-approval unique value (the control plane mints a fresh one
/// per response); together they make the approval a single-use, conversation-
/// bound capability (`#370`). Returns
/// `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field of the canonical contract
pub fn response_payload(
    request_id: &str,
    tool_name: &str,
    args_json: &str,
    modified_args_json: &str,
    approved: bool,
    approved_for_session: bool,
    covered_capabilities: &[String],
    caller: &str,
    approver_id: &str,
    sandbox_mode: &str,
    reason: &str,
    injected_context: &str,
    conversation_id: &str,
    nonce: &str,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    let canonical = response_canonical(
        request_id,
        tool_name,
        args_json,
        modified_args_json,
        approved,
        approved_for_session,
        covered_capabilities,
        caller,
        approver_id,
        sandbox_mode,
        reason,
        injected_context,
        conversation_id,
        nonce,
    );
    let signature = signer.sign(&canonical);
    let pk = signer.public_key_bytes();
    // Same omit-when-empty rule as `response_canonical` (#1025) — keeps the
    // persisted payload byte-identical to before this field existed.
    let full = ResponseFull {
        body: ResponseBody {
            request_id,
            tool_name,
            args_json,
            modified_args_json,
            approved,
            approved_for_session,
            covered_capabilities,
            caller,
            sandbox_mode,
            reason,
            injected_context,
            conversation_id,
            nonce,
        },
        signed_by: crate::hex::lower(&pk),
        signature_hex: crate::hex::lower(&signature),
        approver: approver_id,
    };
    (canonical_bytes(&full), signature, pk)
}

/// Scope names for a signed taint-excision marker (`#590`).
///
/// `cascade` is the sound default: the named positions are excised AND so is
/// every model-authored content event after the earliest of them — the
/// recovery literature shows a model re-derives an injected instruction from
/// its own retained reasoning if only the source is removed. `source-only`
/// excises exactly the named positions: an explicit, human-vouched override
/// for content the person read and judged benign, named in the signed
/// payload so the audit trail shows which posture the human chose.
pub const EXCISION_SCOPE_CASCADE: &str = "cascade";
/// See [`EXCISION_SCOPE_CASCADE`].
pub const EXCISION_SCOPE_SOURCE_ONLY: &str = "source-only";

/// The canonical (signature-covered) form of a `taint_excision` marker.
///
/// Covers the conversation (a marker signed for one conversation cannot be
/// replayed into another), the scope, the named journal positions, and who
/// requested the excision — so a marker can be neither forged, re-targeted,
/// nor widened. `signed_by`/`signature_hex` are appended after signing and
/// are not covered.
fn excision_canonical(
    conversation_id: &str,
    scope: &str,
    positions: &[u64],
    requested_by: &str,
    reason: &str,
) -> Vec<u8> {
    canonical_bytes(&ExcisionCanonical {
        conversation_id,
        scope,
        positions,
        requested_by,
        reason,
    })
}

/// The signed `taint_excision` field set, in its frozen order.
#[derive(Serialize)]
struct ExcisionCanonical<'a> {
    conversation_id: &'a str,
    scope: &'a str,
    positions: &'a [u64],
    requested_by: &'a str,
    reason: &'a str,
}

/// JSON payload for a signed `taint_excision` event (`#590`).
///
/// Returns `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
pub fn excision_payload(
    conversation_id: &str,
    scope: &str,
    positions: &[u64],
    requested_by: &str,
    reason: &str,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        ExcisionCanonical {
            conversation_id,
            scope,
            positions,
            requested_by,
            reason,
        },
        signer.as_signer(),
    )
}

/// The canonical (signature-covered) form of a `grant_replay` audit record
/// (`#594`).
///
/// Binds the conversation and turn the replay happened in, the tool the grant
/// cleared, the [`crate::grant::grant_ref`] of the grant that cleared it, the
/// capability names the grant kept against taint, and the template-coverage hash
/// (#618) the grant matched — so the durable record commits to exactly which
/// grant kept which capabilities on which turn. `signed_by`/`signature_hex` are
/// appended after signing and are not covered.
fn grant_replay_canonical(
    conversation_id: &str,
    turn_id: &str,
    tool: &str,
    grant_ref: &str,
    covered_capabilities: &[String],
    coverage_hash: &str,
) -> Vec<u8> {
    canonical_bytes(&GrantReplayCanonical {
        conversation_id,
        turn_id,
        tool,
        grant_ref,
        covered_capabilities,
        coverage_hash,
    })
}

/// The signed `grant_replay` field set, in its frozen order.
#[derive(Serialize)]
struct GrantReplayCanonical<'a> {
    conversation_id: &'a str,
    turn_id: &'a str,
    tool: &'a str,
    grant_ref: &'a str,
    covered_capabilities: &'a [String],
    coverage_hash: &'a str,
}

/// JSON payload for a signed `grant_replay` audit event (`#594`).
///
/// The durable, trust-tagged record PRD §12 requires that a replayed grant kept
/// a capability taint would have removed — appended by the control plane once per
/// grant-cleared gate (never a `tracing` line). Platform-signed (ed25519, the
/// [`ApprovalSigner`]) so the record is tamper-evident and attributable. The
/// field names match `polychrome.events.v1.GrantReplayEvent`, so the forensics
/// decoder renders it. Returns `(full_payload_bytes, signature_bytes,
/// public_key_bytes)`.
#[must_use]
#[allow(clippy::too_many_arguments)] // each arg is a distinct field of the audit record
pub fn grant_replay_payload(
    conversation_id: &str,
    turn_id: &str,
    tool: &str,
    grant_ref: &str,
    covered_capabilities: &[String],
    coverage_hash: &str,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        GrantReplayCanonical {
            conversation_id,
            turn_id,
            tool,
            grant_ref,
            covered_capabilities,
            coverage_hash,
        },
        signer.as_signer(),
    )
}

/// Verify a persisted `grant_replay` audit payload against its embedded signer
/// (`#594`).
///
/// Rebuilds the canonical from the payload's own fields and checks the embedded
/// ed25519 signature. Returns `true` only when the signature covers the exact
/// record — a tamper to any bound field flips it to `false`. Fail-closed on any
/// malformed field or bad hex.
#[must_use]
pub fn verify_grant_replay(payload: &[u8]) -> bool {
    let Ok(v) = serde_json::from_slice::<serde_json::Value>(payload) else {
        return false;
    };
    let (
        Some(conversation_id),
        Some(turn_id),
        Some(tool),
        Some(grant_ref),
        Some(covered),
        Some(coverage_hash),
        Some(signed_by),
        Some(signature_hex),
    ) = (
        v.get("conversation_id").and_then(Value::as_str),
        v.get("turn_id").and_then(Value::as_str),
        v.get("tool").and_then(Value::as_str),
        v.get("grant_ref").and_then(Value::as_str),
        v.get("covered_capabilities").and_then(Value::as_array),
        v.get("coverage_hash").and_then(Value::as_str),
        v.get("signed_by").and_then(Value::as_str),
        v.get("signature_hex").and_then(Value::as_str),
    )
    else {
        return false;
    };
    let Some(covered_capabilities) = covered
        .iter()
        .map(|c| c.as_str().map(str::to_owned))
        .collect::<Option<Vec<_>>>()
    else {
        return false;
    };
    let (Some(pk), Some(sig)) = (
        crate::hex::decode(signed_by),
        crate::hex::decode(signature_hex),
    ) else {
        return false;
    };
    let canonical = grant_replay_canonical(
        conversation_id,
        turn_id,
        tool,
        grant_ref,
        &covered_capabilities,
        coverage_hash,
    );
    crate::verify(&pk, &canonical, &sig)
}

/// Whether `signer_pk` is a member of the deployment's pinned approval
/// allow-list (`#845`).
///
/// An internally-consistent ed25519 signature proves only that a payload was
/// not altered after it was signed; it says nothing about whether the signer is
/// one the deployment trusts, since anyone can mint a keypair, embed its own
/// public key, and self-sign an arbitrary payload. Every trust-gated verifier
/// therefore checks membership here before honoring a payload. An empty
/// allow-list trusts no one (fail closed). Shared by the grant-replay and
/// approval-response pinned verifiers so the allow-list check cannot drift
/// between them or from [`verify_signed_receipt`]'s.
fn signer_is_trusted(signer_pk: &[u8], trusted_signers: &[Vec<u8>]) -> bool {
    trusted_signers.iter().any(|k| k.as_slice() == signer_pk)
}

/// Verify a persisted `grant_replay` audit payload against a **trusted-signer
/// allow-list** (`#845`).
///
/// Like [`verify_grant_replay`] but additionally rejects any payload whose
/// embedded `signed_by` key is not one of `trusted_signers` — the deployment's
/// pinned approval public key(s), typically the running
/// [`ApprovalSigner::public_key_bytes`], since every `grant_replay` record this
/// control plane persists is self-signed with it. Without this gate an attacker
/// could sign a well-formed record with their own key, embed it, and have the
/// audit trail render it as `valid`. Mirrors [`verify_signed_receipt`]'s
/// allow-list gate. Returns `true` only when the signer is trusted AND the
/// signature covers the exact record; `false` (fail closed) on a malformed
/// payload, an untrusted signer, or a bad signature.
#[must_use]
pub fn verify_grant_replay_pinned(payload: &[u8], trusted_signers: &[Vec<u8>]) -> bool {
    // Gate on the allow-list before the (single-sourced) signature check: an
    // untrusted signer is rejected no matter how internally consistent its
    // signature is.
    let Some(pk) = serde_json::from_slice::<Value>(payload).ok().and_then(|v| {
        v.get("signed_by")
            .and_then(Value::as_str)
            .and_then(crate::hex::decode)
    }) else {
        return false;
    };
    if !signer_is_trusted(&pk, trusted_signers) {
        return false;
    }
    verify_grant_replay(payload)
}

/// A verified `taint_excision` marker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedExcision {
    /// The conversation the marker is bound to.
    pub conversation_id: String,
    /// [`EXCISION_SCOPE_CASCADE`] or [`EXCISION_SCOPE_SOURCE_ONLY`].
    pub scope: String,
    /// The named journal positions.
    pub positions: Vec<u64>,
    /// Who requested the excision (persona id or operator identity).
    pub requested_by: String,
    /// Free-text audit reason.
    pub reason: String,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

impl VerifiedExcision {
    /// Whether this marker's scope is the cascading (sound-default) one.
    #[must_use]
    pub fn is_cascade(&self) -> bool {
        self.scope == EXCISION_SCOPE_CASCADE
    }
}

/// Verify a persisted `taint_excision` payload.
///
/// `None` for a malformed payload, an unknown scope, or a signature that
/// does not verify — the caller ignores the marker and taint stays (fail
/// closed).
#[must_use]
pub fn verify_signed_excision(payload: &[u8]) -> Option<VerifiedExcision> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let scope = v.get("scope")?.as_str()?.to_owned();
    if scope != EXCISION_SCOPE_CASCADE && scope != EXCISION_SCOPE_SOURCE_ONLY {
        return None;
    }
    let positions: Vec<u64> = v
        .get("positions")?
        .as_array()?
        .iter()
        .map(serde_json::Value::as_u64)
        .collect::<Option<Vec<_>>>()?;
    let requested_by = v.get("requested_by")?.as_str()?.to_owned();
    let reason = v.get("reason")?.as_str()?.to_owned();
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    let canonical =
        excision_canonical(&conversation_id, &scope, &positions, &requested_by, &reason);
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedExcision {
            conversation_id,
            scope,
            positions,
            requested_by,
            reason,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// JSON payload for an `approval_deferred` event (`#67` "send back").
///
/// A defer records that the approver bounced the call back without approving or
/// denying it — the audit trail shows the intent, but the pending
/// `approval_request` is NOT resolved (no `approval_response`), so the call stays
/// open. The signature commits to the call identity (`request_id`), the
/// `conversation_id` it was deferred in, and the free-form `reason`; `signed_by`
/// and `signature_hex` are appended after signing and are not covered.
///
/// Returns `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
pub fn deferred_payload(
    request_id: &str,
    conversation_id: &str,
    reason: &str,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        DeferredCanonical {
            request_id,
            conversation_id,
            reason,
        },
        signer.as_signer(),
    )
}

/// The signed `approval_deferred` field set, in its frozen order.
#[derive(Serialize)]
struct DeferredCanonical<'a> {
    request_id: &'a str,
    conversation_id: &'a str,
    reason: &'a str,
}

/// Verify a persisted `approval_deferred` payload (`#67`).
///
/// Returns `Some((request_id, conversation_id, reason))` when the signature
/// checks out against the embedded key, else `None`.
#[must_use]
pub fn verify_deferred(payload: &[u8]) -> Option<(String, String, String)> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let request_id = v.get("request_id")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let reason = v.get("reason")?.as_str()?.to_owned();
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = canonical_bytes(&DeferredCanonical {
        request_id: &request_id,
        conversation_id: &conversation_id,
        reason: &reason,
    });
    verify(&pk, &canonical, &sig).then_some((request_id, conversation_id, reason))
}

/// JSON payload for a dispatch-mutation event (`#67`, #539/#540).
///
/// A signed record that a policy rewrote a call's args (`tool_input_rewrite`),
/// injected context (`tool_context_injection`), or redacted a result
/// (`tool_result_redaction`).
///
/// The signature commits to the event `kind` (so a record can't be re-filed under
/// another mutation kind), the call identity (`tool_call_id`, `tool_name`), the
/// conversation, and the mutation's `before`/`after` (proposed→executed args,
/// or empty→context, or original→redacted result). `signed_by` / `signature_hex`
/// are appended after signing and not covered. Returns
/// `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
#[allow(clippy::too_many_arguments)] // each is a distinct signed field of the canonical contract
pub fn mutation_payload(
    kind: &str,
    tool_call_id: &str,
    tool_name: &str,
    conversation_id: &str,
    before: &str,
    after: &str,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        MutationCanonical {
            kind,
            tool_call_id,
            tool_name,
            conversation_id,
            before,
            after,
        },
        signer.as_signer(),
    )
}

/// The signed dispatch-mutation field set, in its frozen order.
#[derive(Serialize)]
struct MutationCanonical<'a> {
    kind: &'a str,
    tool_call_id: &'a str,
    tool_name: &'a str,
    conversation_id: &'a str,
    before: &'a str,
    after: &'a str,
}

/// Verify a persisted dispatch-mutation payload (`#67`).
///
/// Returns the signed `(kind, tool_call_id, tool_name, conversation_id, before,
/// after)` when the signature checks out against the embedded key, else `None`.
#[must_use]
pub fn verify_mutation(payload: &[u8]) -> Option<(String, String, String, String, String, String)> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let kind = v.get("kind")?.as_str()?.to_owned();
    let tool_call_id = v.get("tool_call_id")?.as_str()?.to_owned();
    let tool_name = v.get("tool_name")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let before = v.get("before")?.as_str()?.to_owned();
    let after = v.get("after")?.as_str()?.to_owned();
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = canonical_bytes(&MutationCanonical {
        kind: &kind,
        tool_call_id: &tool_call_id,
        tool_name: &tool_name,
        conversation_id: &conversation_id,
        before: &before,
        after: &after,
    });
    verify(&pk, &canonical, &sig).then_some((
        kind,
        tool_call_id,
        tool_name,
        conversation_id,
        before,
        after,
    ))
}

/// Reason-string prefix marking an `approval_response` as a reviewer-agent
/// auto-approval (`#377`), as opposed to a human decision.
///
/// The reviewer signs the EXACT same canonical `approval_response` a human
/// would — same [`response_payload`], same signer, same bound identity
/// (`request_id` + `tool_name` + `args_json` + `caller` + `sandbox_mode`),
/// `approved == true`, `approved_for_session == false` — so the wire/signature
/// contract is byte-for-byte identical and every existing verify path accepts
/// it unchanged. The ONLY field distinguishing an auto-approval from a human
/// one is the signed `reason`, which carries this prefix. Because `reason` is
/// covered by the signature (`response_canonical`), the distinction is
/// unforgeable: a compromised forwarder can neither launder an auto-approval as
/// human nor a human decision as auto without invalidating the signature. The
/// event log is therefore auditable for machine-vs-human consent off this one
/// signed field — the guardrail `#377` requires.
pub const AUTO_REVIEW_REASON_PREFIX: &str = "auto-review:";

/// Build the signed `reason` for a reviewer auto-approval at risk `tier`.
///
/// Carries [`AUTO_REVIEW_REASON_PREFIX`] so the audit log can tell it from a
/// human decision; `tier` (e.g. `"low"`) records WHY the classifier deemed the
/// call auto-eligible. The control plane passes the result as the `reason`
/// argument to the SAME [`response_payload`] the human path uses, so no
/// separate signing surface exists.
#[must_use]
pub fn auto_review_reason(tier: &str) -> String {
    format!("{AUTO_REVIEW_REASON_PREFIX}{tier}")
}

/// Whether a signed `reason` marks its `approval_response` as a reviewer
/// auto-approval (`#377`) rather than a human decision.
///
/// The audit distinguisher; it reads the signed `reason` field, so it cannot be
/// spoofed without breaking the signature.
#[must_use]
pub fn is_auto_review_reason(reason: &str) -> bool {
    reason.starts_with(AUTO_REVIEW_REASON_PREFIX)
}

/// Signed `reason` recorded for the blanket `approve-all-dangerous` mode.
///
/// Set by `POLYCHROME_APPROVAL_MODE=approve-all-dangerous` — the legible single
/// approve-all surface that replaced the legacy `POLYCHROME_APPROVE_ALL` flag.
/// Unlike [`auto_review_reason`] this is NOT a risk-classified verdict: it marks
/// an unconditional machine approval, so the audit log can tell a blanket
/// test-rig approval apart from both a human decision and a reviewer
/// auto-approval. Like every other reason it is covered by the signature, so the
/// distinction is unforgeable.
pub const APPROVE_ALL_DANGEROUS_REASON: &str = "approve-all-dangerous: blanket machine approval";

/// A decoded `approval_response` payload after signature verification.
#[derive(Debug, Clone)]
pub struct VerifiedResponse {
    /// The tool-call id this response answers.
    pub request_id: String,
    /// The bound tool name — the approval applies only to this exact call.
    pub tool_name: String,
    /// The bound `args_json` — the model's PROPOSED args, the identity the
    /// approval is bound to. [`Self::authorizes_call`] matches this byte-for-byte,
    /// so a re-emitted call with different args cannot inherit the approval. This
    /// is the args the approver saw, NOT necessarily the args that execute.
    pub args_json: String,
    /// The approver's EDIT to the proposed args — the args to actually execute,
    /// or empty when the approver did not edit (execute `args_json` unchanged).
    /// Signed, so the edit is unforgeable and auditable; the delta from
    /// `args_json` is the recorded mutation. Resolve the effective execution args
    /// with the pure `polyc_agent::resolve_approved_call`.
    pub modified_args_json: String,
    /// Whether the request was approved.
    pub approved: bool,
    /// Whether the approval is remembered for the rest of the session ("don't
    /// ask again"); `false` for a one-shot approval.
    pub approved_for_session: bool,
    /// The capability shortfall this approval covered (`#595`): the stable
    /// kebab-case capability names the gate reported missing when it paused
    /// the call. Covered by the signature, so the effective session-grant key
    /// is (caller, tool, covered capabilities) — a grant recorded against one
    /// covered set never satisfies the same tool after its required set grows.
    /// Empty for an approval of an ordinary policy/sandbox gate.
    pub covered_capabilities: Vec<String>,
    /// The caller identity the (session) approval is scoped to — the paused
    /// turn's own beneficiary (RFC 8693 `sub`/subject), NOT necessarily who
    /// clicked. Set by the trusted control plane and covered by the
    /// signature, so a session grant cannot be re-scoped to a different user.
    pub caller: String,
    /// The identity that actually resolved this decision (`#1025`, RFC 8693
    /// `act`/actor), when the edge supplied one — empty otherwise (no edge
    /// integration yet, or a payload signed before this field existed).
    /// Distinct from `caller`: an admin approving on someone else's behalf
    /// signs a different `approver` than `caller`. For approval-policy
    /// checks and the audit trail ONLY — never fed into `principal_ref` (see
    /// `caller`'s own resume-attribution use in the control plane).
    pub approver: String,
    /// The sandbox/permission mode the paused turn ran under, covered by the
    /// signature so a grant cannot be replayed under a different mode.
    pub sandbox_mode: String,
    /// Free-form human-supplied reason.
    pub reason: String,
    /// Context the approver attached to inject before the tool runs — prepended
    /// as an `internal_only` message ahead of execution, or empty when none.
    /// Signed, so an injected instruction is unforgeable and recorded.
    pub injected_context: String,
    /// The conversation the approval was granted in, covered by the signature so
    /// a token signed for one conversation cannot be replayed into another
    /// (`#370`, closes `#77` bug 3B).
    pub conversation_id: String,
    /// Per-approval unique value, covered by the signature. A consumer records it
    /// on use so the token cannot be re-presented once spent (single-use, `#370`).
    pub nonce: String,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

impl VerifiedResponse {
    /// Whether this verified, approved token authorizes the EXACT call
    /// `(request_id, tool_name, args_json)` — the args-binding (`#370` item 3).
    ///
    /// The signed `args_json` is matched byte-for-byte, so a re-emitted same-id
    /// call with different arguments (or a different tool) is NOT authorized: a
    /// captured approval can never be reused to run a different action. A denial
    /// (`approved == false`) authorizes nothing.
    #[must_use]
    pub fn authorizes_call(&self, request_id: &str, tool_name: &str, args_json: &str) -> bool {
        self.approved
            && self.request_id == request_id
            && self.tool_name == tool_name
            && self.args_json == args_json
    }
}

/// Verify a persisted `approval_response` payload.
///
/// Returns `Some(record)` if the signature checks out against the embedded
/// public key (the caller is responsible for trusting that public key — a key
/// allow-list lives alongside this in production). Returns `None` if the payload
/// is malformed, the hex fields don't decode, or the signature doesn't verify.
#[must_use]
pub fn verify_signed_response(payload: &[u8]) -> Option<VerifiedResponse> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let request_id = v.get("request_id")?.as_str()?.to_owned();
    let tool_name = v.get("tool_name")?.as_str()?.to_owned();
    let args_json = v.get("args_json")?.as_str()?.to_owned();
    let modified_args_json = v.get("modified_args_json")?.as_str()?.to_owned();
    let approved = v.get("approved")?.as_bool()?;
    let approved_for_session = v.get("approved_for_session")?.as_bool()?;
    let covered_capabilities: Vec<String> = v
        .get("covered_capabilities")?
        .as_array()?
        .iter()
        .map(|c| c.as_str().map(str::to_owned))
        .collect::<Option<Vec<_>>>()?;
    let caller = v.get("caller")?.as_str()?.to_owned();
    // #1025: absent on every payload signed before this field existed (and
    // on any signed today with an empty approver — omitted, not `""`, at
    // sign time) — defaults to empty, NOT a decode failure.
    let approver_id = v
        .get("approver")
        .and_then(|x| x.as_str())
        .unwrap_or_default()
        .to_owned();
    let sandbox_mode = v.get("sandbox_mode")?.as_str()?.to_owned();
    let reason = v.get("reason")?.as_str()?.to_owned();
    let injected_context = v.get("injected_context")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let nonce = v.get("nonce")?.as_str()?.to_owned();
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;

    let canonical = response_canonical(
        &request_id,
        &tool_name,
        &args_json,
        &modified_args_json,
        approved,
        approved_for_session,
        &covered_capabilities,
        &caller,
        &approver_id,
        &sandbox_mode,
        &reason,
        &injected_context,
        &conversation_id,
        &nonce,
    );
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedResponse {
            request_id,
            tool_name,
            args_json,
            modified_args_json,
            approved,
            approved_for_session,
            covered_capabilities,
            caller,
            approver: approver_id,
            sandbox_mode,
            reason,
            injected_context,
            conversation_id,
            nonce,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Verify a persisted `approval_response` payload against a **trusted-signer
/// allow-list** (`#845`).
///
/// Like [`verify_signed_response`] but additionally rejects any payload whose
/// embedded `signed_by` key is not one of `trusted_signers` — the deployment's
/// pinned approval public key(s), typically the running
/// [`ApprovalSigner::public_key_bytes`], since every `approval_response` this
/// control plane persists is self-signed with it. Without this gate an attacker
/// could sign a well-formed decision with their own key, embed it, and have it
/// honored as an approval. Mirrors [`verify_signed_receipt`]'s allow-list gate.
/// Returns `None` (fail closed) on a malformed payload, an untrusted signer, or
/// a bad signature.
#[must_use]
pub fn verify_signed_response_pinned(
    payload: &[u8],
    trusted_signers: &[Vec<u8>],
) -> Option<VerifiedResponse> {
    let verified = verify_signed_response(payload)?;
    // Reject an untrusted signer even though its signature is self-consistent:
    // anyone can mint a keypair, embed its public key, and self-sign.
    if !signer_is_trusted(&verified.signer_public_key, trusted_signers) {
        return None;
    }
    Some(verified)
}

/// Verify a persisted `approval_response` as a SINGLE-USE, conversation-bound
/// capability token (`#370`), gated on a **trusted-signer allow-list** (`#845`).
///
/// Returns the verified response only when ALL hold:
/// * the embedded `signed_by` key is a member of `trusted_signers` — the
///   deployment's pinned approval public key(s) (see
///   [`verify_signed_response_pinned`]); an internally-consistent signature over
///   an untrusted key authorizes nothing;
/// * the signature verifies against that key (provenance);
/// * the signed `conversation_id` equals `conversation_id` — a token signed for
///   one conversation is rejected when presented for another (closes `#77`
///   bug 3B);
/// * the signed `nonce` is non-empty AND not already in `consumed` — a token
///   that has been spent (its nonce recorded on a prior use) is rejected.
///
/// The caller binds the token to a specific call by matching the returned
/// [`VerifiedResponse::authorizes_call`], and MUST record the returned
/// [`VerifiedResponse::nonce`] into its `consumed` set before honoring it, so a
/// second presentation of the same token is rejected. An empty nonce is treated
/// as malformed and fails closed (every minted token carries one).
#[must_use]
pub fn verify_capability<S: std::hash::BuildHasher>(
    payload: &[u8],
    conversation_id: &str,
    consumed: &HashSet<String, S>,
    trusted_signers: &[Vec<u8>],
) -> Option<VerifiedResponse> {
    let verified = verify_signed_response_pinned(payload, trusted_signers)?;
    if verified.conversation_id != conversation_id {
        return None;
    }
    if verified.nonce.is_empty() || consumed.contains(&verified.nonce) {
        return None;
    }
    Some(verified)
}

/// Verify a wire-form `approval_response`, binding the approval to its full
/// signed identity `(request_id, tool_name, args_json, approved,
/// approved_for_session, caller, reason)`.
///
/// Used by the harness when it receives `HarnessMessage.approval_responses` over
/// the wire and must confirm provenance AND identity before executing the paused
/// tool or honoring a "don't ask again" grant. The `caller` is covered by the
/// signature, so a compromised control plane cannot re-scope a remembered
/// approval onto a different user. Returns `true` only if `signer_pk_hex +
/// signature_hex` validates against the canonical.
#[must_use]
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field of the canonical contract
pub fn verify_wire_response(
    request_id: &str,
    tool_name: &str,
    args_json: &str,
    modified_args_json: &str,
    approved: bool,
    approved_for_session: bool,
    covered_capabilities: &[String],
    caller: &str,
    approver_id: &str,
    sandbox_mode: &str,
    reason: &str,
    injected_context: &str,
    conversation_id: &str,
    nonce: &str,
    signer_pk_hex: &str,
    signature_hex: &str,
) -> bool {
    let Some(pk) = crate::hex::decode(signer_pk_hex) else {
        return false;
    };
    let Some(sig) = crate::hex::decode(signature_hex) else {
        return false;
    };
    let canonical = response_canonical(
        request_id,
        tool_name,
        args_json,
        modified_args_json,
        approved,
        approved_for_session,
        covered_capabilities,
        caller,
        approver_id,
        sandbox_mode,
        reason,
        injected_context,
        conversation_id,
        nonce,
    );
    verify(&pk, &canonical, &sig)
}

/// Whether an approval response is a session ("don't ask again") grant for
/// `current_caller`.
///
/// True when it is approved, flagged for the session, and bound to a non-empty
/// `caller` equal to the current turn's caller.
///
/// This is the per-USER isolation invariant — user A's remembered approval must
/// never auto-approve user B in a shared conversation. It lives here, in one
/// place, so the harness (which re-verifies signed wire responses) and the
/// control plane (the in-process path) cannot drift on *who* a remembered
/// approval applies to. Callers still gate the TOOL on its idempotency
/// separately ([`crate`] does not know tool policy).
#[must_use]
pub fn is_session_grant_for(
    approved: bool,
    approved_for_session: bool,
    caller: &str,
    current_caller: &str,
) -> bool {
    approved && approved_for_session && !caller.is_empty() && caller == current_caller
}

/// Extract `(request_id, approved)` from an `approval_response` payload.
///
/// Used by replay to find which pending requests have been answered. Skips
/// signature verification on the assumption the caller has already accepted
/// the entry — pair with [`verify_signed_response`] when trust matters.
#[must_use]
pub fn decode_response_minimal(payload: &[u8]) -> Option<(String, bool)> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let request_id = v.get("request_id")?.as_str()?.to_owned();
    let approved = v.get("approved")?.as_bool()?;
    Some((request_id, approved))
}

/// Every decoded field of an `approval_response` payload (unverified).
#[derive(Debug, Clone)]
pub struct DecodedResponse {
    /// Tool-call id this response answers.
    pub request_id: String,
    /// Bound tool name.
    pub tool_name: String,
    /// Bound `args_json` — the model's proposed args (identity binding).
    pub args_json: String,
    /// The approver's edit to the proposed args (empty = unedited).
    pub modified_args_json: String,
    /// Approve / deny decision.
    pub approved: bool,
    /// Whether the approval is remembered for the session ("don't ask again").
    pub approved_for_session: bool,
    /// The capability shortfall this approval covered (`#595`).
    pub covered_capabilities: Vec<String>,
    /// The caller identity the (session) approval is scoped to — the paused
    /// turn's own beneficiary, NOT necessarily who clicked. See `approver`.
    pub caller: String,
    /// The identity that actually resolved this decision (`#1025`), when the
    /// edge supplied one — empty otherwise (no edge integration yet, or a
    /// payload signed before this field existed). Distinct from `caller`.
    pub approver: String,
    /// The sandbox/permission mode the grant was made under.
    pub sandbox_mode: String,
    /// Human-supplied reason.
    pub reason: String,
    /// Context the approver attached to inject before execution (empty = none).
    pub injected_context: String,
    /// The conversation the approval was granted in (`#370` binding).
    pub conversation_id: String,
    /// Per-approval single-use nonce (`#370` binding).
    pub nonce: String,
    /// Signer public key, hex.
    pub signer_pk_hex: String,
    /// Signature, hex.
    pub signature_hex: String,
}

/// Decode every field of an `approval_response` payload without verifying.
///
/// Used by the control plane to forward signed responses onto the harness wire;
/// the harness re-verifies on receipt.
#[must_use]
pub fn decode_response_full(payload: &[u8]) -> Option<DecodedResponse> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    Some(DecodedResponse {
        request_id: v.get("request_id")?.as_str()?.to_owned(),
        tool_name: v.get("tool_name")?.as_str()?.to_owned(),
        args_json: v.get("args_json")?.as_str()?.to_owned(),
        modified_args_json: v.get("modified_args_json")?.as_str()?.to_owned(),
        approved: v.get("approved")?.as_bool()?,
        approved_for_session: v.get("approved_for_session")?.as_bool()?,
        covered_capabilities: v
            .get("covered_capabilities")
            .and_then(Value::as_array)
            .map(|a| {
                a.iter()
                    .filter_map(|c| c.as_str().map(str::to_owned))
                    .collect()
            })
            .unwrap_or_default(),
        caller: v.get("caller")?.as_str()?.to_owned(),
        // #1025: absent on every payload signed before this field existed —
        // defaults to empty, NOT a decode failure (see `response_canonical`).
        approver: v
            .get("approver")
            .and_then(|x| x.as_str())
            .unwrap_or_default()
            .to_owned(),
        sandbox_mode: v.get("sandbox_mode")?.as_str()?.to_owned(),
        reason: v.get("reason")?.as_str()?.to_owned(),
        injected_context: v.get("injected_context")?.as_str()?.to_owned(),
        conversation_id: v.get("conversation_id")?.as_str()?.to_owned(),
        nonce: v.get("nonce")?.as_str()?.to_owned(),
        signer_pk_hex: v.get("signed_by")?.as_str()?.to_owned(),
        signature_hex: v.get("signature_hex")?.as_str()?.to_owned(),
    })
}

/// Current signed `payment_receipt` schema version.
///
/// **v2** makes a settled receipt self-describing: alongside the original
/// settlement facts it covers the event `kind` (direction — without it an
/// inbound payload could be re-filed under the outbound kind, or vice versa,
/// since the stored `Event.kind` is not itself signed), the binding fields
/// (`tool_call_id`, `approval_pos`, `approved_args_hash`), and an opaque
/// `subject` — so an auditor can bind the receipt to the exact approved tool
/// call it answered without walking the log to the separate
/// `outbound_payment_attempt` event. **v3** adds payer attribution
/// (`payer_kind`, `paying_account`) — which account actually paid: a linked
/// wallet or the deployment's own signer — computed at settlement and now
/// carried on the durable receipt instead of only reaching the tool result.
/// **v1** (legacy, no `version` field) signed only the six settlement facts;
/// it still *verifies* for forensics but carries no kind, binding tuple, or
/// payer attribution.
pub const RECEIPT_VERSION: u64 = 3;

// Compile-time tripwire for a `RECEIPT_VERSION` bump. `receipt_payload` signs
// the frozen `ReceiptPayload::canonical_json_v3` *by name*, and `ReceiptSchema`
// resolves each persisted version to its own frozen builder. Raising the
// constant without doing the rest would leave new receipts signing v3 bytes
// while claiming the new version, so make that mismatch fail the build instead
// of shipping. The message lists every site a bump touches: the enum's
// exhaustive matches force (1) and (2), `dead_code` on an unreachable variant
// forces (3), this assert itself catches (4), and (5) is on the bumper.
const _: () = assert!(
    RECEIPT_VERSION == 3,
    "RECEIPT_VERSION changed. A bump is five edits, not one: (1) add \
     ReceiptPayload::canonical_json_v<N> beside the frozen builders; (2) add \
     ReceiptSchema::V<N> and answer number(), covers_binding() — say which \
     fields the new canonical actually covers — and canonical(); (3) give \
     ReceiptSchema::resolve an arm mapping the claimed number to it; (4) \
     repoint receipt_payload at the new builder; (5) in the tests, add a \
     golden v<N> fixture beside GOLDEN_V2_RECEIPT and re-freeze the pinned \
     writer shape, leaving every already-frozen v2 literal untouched"
);

/// The receipt body fields [`receipt_payload`] signs, named at the call site.
///
/// Replaces positional `&str` arguments: with the positional form, two
/// same-typed fields (e.g. `recipient` and `method`) could be swapped at a call
/// site and still compile, silently signing a corrupt receipt. Naming the
/// fields here makes such a swap a compile error.
///
/// The field set, names, and the order they are serialized in
/// [`receipt_payload`] are the signed-payload contract: they must NOT change
/// without a version bump, or previously-persisted receipts stop verifying.
///
/// `kind` and the trailing four fields are **v2** additions: the event kind
/// (direction) plus the binding tuple and an opaque `subject`. Inbound (the
/// server was *paid*) receipts have no approved tool call, so they pass empty
/// strings for the binding tuple and subject; outbound (the control plane
/// *paid* a 402 service) receipts populate them. Both directions sign their
/// `kind`.
#[derive(Debug, Clone, Copy)]
pub struct ReceiptPayload<'a> {
    /// The event kind the payload is stored under (`payment_receipt` for
    /// inbound, `outbound_payment_receipt` for outbound). Signed so a payload
    /// cannot be re-filed under the other direction's kind (v2; empty for
    /// legacy v1).
    pub kind: &'a str,
    /// Chain/transaction reference (e.g. tx id) the receipt settles.
    pub reference: &'a str,
    /// Settled amount as a string, never a float (no drift, no rounding).
    ///
    /// The UNIT is the direction's, not this type's, and the two directions do
    /// not agree: an inbound receipt (`payment_receipt`) carries a decimal
    /// figure in the settlement currency (`"0.01"`), an outbound one
    /// (`outbound_payment_receipt`) carries the settlement token's base units
    /// (`"10000"`, or `""` when the payment proxy could not capture the
    /// charge). Read it through the matching `polyc_payments::amount` reader,
    /// dispatched on [`Self::kind`] — never with a bare parse, and never by
    /// guessing from the string's shape.
    pub amount: &'a str,
    /// Currency / asset label. Follows the same per-direction split as
    /// [`Self::amount`]: the settlement currency symbol inbound, the
    /// settlement token's contract address outbound.
    pub currency: &'a str,
    /// Recipient address.
    pub recipient: &'a str,
    /// Settlement method (e.g. `tempo`).
    pub method: &'a str,
    /// RFC3339 settlement timestamp.
    pub timestamp: &'a str,
    /// The `paid_fetch` tool-call id this payment answered (v2; empty for
    /// inbound and legacy v1).
    pub tool_call_id: &'a str,
    /// Decimal string of the `approval_request` log position the payment
    /// answered (v2; empty for inbound and legacy v1).
    pub approval_pos: &'a str,
    /// sha256 hex of the approved `args_json` — the same idempotency-key
    /// component the `outbound_payment_attempt` marker carries, so a verifier
    /// can cross-check the receipt against the attempt (v2; empty otherwise).
    pub approved_args_hash: &'a str,
    /// Opaque principal the spend is attributed to. Currently the conversation
    /// id; the structured agent/tenant identity is supplied later by the
    /// declarative-catalog identity model. Treat as opaque (v2; empty otherwise).
    pub subject: &'a str,
    /// Which account actually paid: `"linked_wallet"` or `"deployment"` — the
    /// stable vocabulary `PayerKind::as_str` mints (in the payments client
    /// resolver). Explicit unknown (empty string) for v1/v2 receipts and for
    /// inbound receipts, which have no payer concept — never inferred (v3).
    pub payer_kind: &'a str,
    /// The paying account's own address, when known. Empty when the payer is
    /// the deployment's own signer (there is no separate "paying account" to
    /// name beyond the signer itself) or when this build cannot observe it
    /// (v3; empty for v1/v2 and inbound receipts).
    pub paying_account: &'a str,
}

impl ReceiptPayload<'_> {
    /// Frozen **v3** canonical: the v2 field set plus payer attribution
    /// (`payer_kind`, `paying_account`).
    ///
    /// This is the SINGLE source for the signed v3 receipt field set and order:
    /// both the signing path ([`receipt_payload`]) and the verifying path
    /// ([`verify_signed_receipt`]) route their v3 canonical bytes through here,
    /// so the two paths cannot drift. The key set/order is the on-wire signed
    /// contract and must NOT change — a new covered field means a new version
    /// with its own builder beside this one.
    ///
    /// Frozen exactly like [`Self::canonical_json_v2`], and retained for the
    /// same reason: once [`RECEIPT_VERSION`] moves past 3, every receipt
    /// already signed under v3 still *verifies* through this builder. That is
    /// why the `version` key below is the literal `3` rather than
    /// [`RECEIPT_VERSION`] — pinning it to the constant would re-canonicalize
    /// every persisted v3 receipt the day the constant changed, and none of
    /// them would verify again.
    #[must_use]
    const fn canonical_json_v3(&self) -> ReceiptCanonicalV3<'_> {
        ReceiptCanonicalV3 {
            version: 3,
            kind: self.kind,
            reference: self.reference,
            amount: self.amount,
            currency: self.currency,
            recipient: self.recipient,
            method: self.method,
            timestamp: self.timestamp,
            tool_call_id: self.tool_call_id,
            approval_pos: self.approval_pos,
            approved_args_hash: self.approved_args_hash,
            subject: self.subject,
            payer_kind: self.payer_kind,
            paying_account: self.paying_account,
        }
    }

    /// Frozen **v2** canonical: the six settlement facts plus the event
    /// `kind`, the binding tuple, and the opaque `subject`.
    ///
    /// This is the SINGLE source for the signed v2 receipt field set and order:
    /// both the signing path ([`receipt_payload`]) and the verifying path
    /// ([`verify_signed_receipt`]) route their v2 canonical bytes through here,
    /// so the two paths cannot drift. The key set/order is the on-wire signed
    /// contract and must NOT change — a new covered field means a new version
    /// with its own builder beside this one.
    ///
    /// Frozen exactly like [`Self::canonical_json_v1`], and retained for the
    /// same reason: once [`RECEIPT_VERSION`] moves past 2, every receipt
    /// already signed under v2 still *verifies* through this builder. That is
    /// why the `version` key below is the literal `2` rather than
    /// [`RECEIPT_VERSION`] — pinning it to the constant would re-canonicalize
    /// every persisted v2 receipt the day the constant changed, and none of
    /// them would verify again.
    #[must_use]
    const fn canonical_json_v2(&self) -> ReceiptCanonicalV2<'_> {
        ReceiptCanonicalV2 {
            version: 2,
            kind: self.kind,
            reference: self.reference,
            amount: self.amount,
            currency: self.currency,
            recipient: self.recipient,
            method: self.method,
            timestamp: self.timestamp,
            tool_call_id: self.tool_call_id,
            approval_pos: self.approval_pos,
            approved_args_hash: self.approved_args_hash,
            subject: self.subject,
        }
    }

    /// Legacy **v1** canonical (the original six settlement fields, no
    /// `version`). Retained only so receipts persisted before the v2 binding
    /// still *verify* for forensics; new receipts always sign v3.
    #[must_use]
    const fn canonical_json_v1(&self) -> ReceiptCanonicalV1<'_> {
        ReceiptCanonicalV1 {
            reference: self.reference,
            amount: self.amount,
            currency: self.currency,
            recipient: self.recipient,
            method: self.method,
            timestamp: self.timestamp,
        }
    }
}

/// The frozen **v3** receipt field set, in its frozen order.
///
/// `version` is the literal `3`, never [`RECEIPT_VERSION`], for the reason
/// [`ReceiptPayload::canonical_json_v3`] gives: a receipt already in the log was
/// signed over these exact bytes and must keep verifying after the constant
/// moves on.
#[derive(Serialize)]
struct ReceiptCanonicalV3<'a> {
    version: u8,
    kind: &'a str,
    reference: &'a str,
    amount: &'a str,
    currency: &'a str,
    recipient: &'a str,
    method: &'a str,
    timestamp: &'a str,
    tool_call_id: &'a str,
    approval_pos: &'a str,
    approved_args_hash: &'a str,
    subject: &'a str,
    payer_kind: &'a str,
    paying_account: &'a str,
}

/// The frozen **v2** receipt field set, in its frozen order.
///
/// `version` is the literal `2`, never [`RECEIPT_VERSION`], for the reason
/// [`ReceiptPayload::canonical_json_v2`] gives: a receipt already in the log was
/// signed over these exact bytes and must keep verifying after the constant
/// moves on.
#[derive(Serialize)]
struct ReceiptCanonicalV2<'a> {
    version: u8,
    kind: &'a str,
    reference: &'a str,
    amount: &'a str,
    currency: &'a str,
    recipient: &'a str,
    method: &'a str,
    timestamp: &'a str,
    tool_call_id: &'a str,
    approval_pos: &'a str,
    approved_args_hash: &'a str,
    subject: &'a str,
}

/// The frozen **v1** receipt field set (the six settlement facts, no
/// `version`), in its frozen order.
#[derive(Serialize)]
struct ReceiptCanonicalV1<'a> {
    reference: &'a str,
    amount: &'a str,
    currency: &'a str,
    recipient: &'a str,
    method: &'a str,
    timestamp: &'a str,
}

/// JSON payload for a `payment_receipt` event.
///
/// Mirrors [`response_payload`] exactly: the signature commits to the
/// canonical (unsigned) JSON form of the receipt body
/// (`reference`, `amount`, `currency`, `recipient`, `method`, `timestamp`).
/// `signed_by` and `signature_hex` are populated *after* the signer runs and
/// are NOT covered by the signature itself. Tampering with any body field
/// invalidates the signature.
///
/// The fields arrive as a single named [`ReceiptPayload`] (rather than six
/// positional strings) so a call site cannot silently swap two same-typed
/// fields; the serialized key set/order is unchanged and remains the signed
/// contract.
///
/// Returns `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
pub fn receipt_payload(
    fields: &ReceiptPayload<'_>,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    // New receipts always sign the current version's frozen canonical, named
    // here rather than looked up, so a `RECEIPT_VERSION` bump has to repoint
    // this line deliberately (the tripwire beside the constant enforces it).
    //
    // The full payload is the canonical body plus the two signature fields,
    // which are NOT covered by the signature. `Envelope` flattens the same
    // single-source canonical struct, so the body field set still lives only in
    // `ReceiptPayload::canonical_json_v3`.
    Envelope::seal(fields.canonical_json_v3(), signer.as_signer())
}

/// A decoded `payment_receipt` payload after signature verification.
#[derive(Debug, Clone)]
pub struct VerifiedReceipt {
    /// Chain/transaction reference (e.g. tx id) the receipt settles.
    pub reference: String,
    /// Settled amount as a string, never a float (no drift, no rounding).
    ///
    /// Carries whichever unit its direction stores — a decimal figure in the
    /// settlement currency for an inbound `payment_receipt`, the settlement
    /// token's base units for an outbound `outbound_payment_receipt` (empty
    /// when the proxy could not capture the charge). Every reader of this
    /// field dispatches on the direction it read the receipt under and uses
    /// the matching `polyc_payments::amount` reader; a bare `parse` here is
    /// the #1739 bug class, which silently dropped every inbound charge.
    pub amount: String,
    /// Currency / asset label — the settlement currency symbol inbound, the
    /// settlement token's contract address outbound.
    pub currency: String,
    /// Recipient address.
    pub recipient: String,
    /// Settlement method (e.g. `tempo`).
    pub method: String,
    /// RFC3339 settlement timestamp.
    pub timestamp: String,
    /// Schema version (`1` = legacy settlement-only, `2` = kind + binding
    /// tuple present).
    pub version: u64,
    /// The signed event kind (`payment_receipt` or `outbound_payment_receipt`).
    /// Callers should check it matches the kind the event was stored under —
    /// the stored kind itself is not signed (v2; empty for v1).
    pub kind: String,
    /// The `paid_fetch` tool-call id this payment answered (v2; empty for v1).
    pub tool_call_id: String,
    /// Decimal string of the `approval_request` log position (v2; empty for v1).
    pub approval_pos: String,
    /// sha256 hex of the approved `args_json` (v2; empty for v1).
    pub approved_args_hash: String,
    /// Opaque principal the spend is attributed to (v2; empty for v1).
    pub subject: String,
    /// Which account actually paid: `"linked_wallet"` or `"deployment"`,
    /// explicit unknown (empty) when this build cannot say so — never
    /// inferred (v3; empty for v1/v2).
    pub payer_kind: String,
    /// The paying account's own address, when known (v3; empty for v1/v2, for
    /// a deployment-signer payer, or when unobservable).
    pub paying_account: String,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// A receipt schema version this build has frozen a canonical for.
///
/// A version's canonical freezes the instant the first receipt is signed under
/// it: those bytes are already in an append-only log and no later edit can
/// reach them. So this enum only ever *gains* variants — bumping
/// [`RECEIPT_VERSION`] adds one and never replaces one, and nothing on the read
/// path consults the current version to decide what a persisted receipt means.
///
/// An enum rather than a table of function pointers keyed on `u64` because
/// every question a version has to answer is answered by an exhaustive
/// `match self`: [`Self::number`], [`Self::covers_binding`], and
/// [`Self::canonical`] each fail to compile until a new variant says what
/// number it writes, which fields its canonical covers, and how it builds
/// them. A variant no [`Self::resolve`] arm can produce is dead code. The
/// closed variant set is also what makes the fail-closed rule structural: there
/// is no `V1` an explicit `version: 1` can resolve to (see [`Self::resolve`]),
/// so no future edit to a numeric guard can hand a claimed version to the v1
/// canonical.
#[derive(Debug, Clone, Copy)]
enum ReceiptSchema {
    /// Legacy: the six settlement facts, signed with no `version` key at all.
    V1,
    /// Adds the event `kind`, the binding tuple, and the opaque `subject`, and
    /// covers its own `version` key.
    V2,
    /// Adds payer attribution (`payer_kind`, `paying_account`) on top of V2.
    V3,
}

impl ReceiptSchema {
    /// The frozen schema a persisted receipt's `version` field names, or `None`
    /// when this build has frozen no canonical for it.
    ///
    /// A legacy receipt carries no `version` key; absence — and ONLY absence —
    /// means [`Self::V1`]. A *present* key must name a version whose canonical
    /// actually covers that key, which is why an explicit `1` resolves to
    /// nothing: the v1 canonical does not cover `version`, so admitting one
    /// would let a valid v1 signature verify while the output echoed an
    /// unsigned, writer-chosen version. There is no arm to relax here — a
    /// claimed `1` is unreachable by construction, not by a numeric guard.
    ///
    /// Keyed on literal version numbers, never on [`RECEIPT_VERSION`]: a
    /// receipt signed under any frozen version keeps verifying after the
    /// current version moves on.
    #[must_use]
    fn resolve(claimed: Option<&Value>) -> Option<Self> {
        let Some(claimed) = claimed else {
            return Some(Self::V1);
        };
        // Every non-integer (a string, a float, `null`, a negative number, an
        // array, an object) and every version this build has not frozen is
        // refused outright — never verified against a guessed canonical.
        match claimed.as_u64() {
            Some(2) => Some(Self::V2),
            Some(3) => Some(Self::V3),
            _ => None,
        }
    }

    /// The version number a receipt signed under this schema reports.
    #[must_use]
    const fn number(self) -> u64 {
        match self {
            Self::V1 => 1,
            Self::V2 => 2,
            Self::V3 => 3,
        }
    }

    /// Whether this schema's canonical covers the event `kind`, the binding
    /// tuple, and the `subject`.
    ///
    /// Field extraction is per-version for the same reason the canonical is:
    /// reading a field the signature does not cover would echo an unsigned
    /// value out of [`verify_signed_receipt`]. A schema that covers a
    /// *different* subset than v2 does not belong behind this boolean — give it
    /// its own accessor and its own extraction branch (see
    /// [`Self::covers_payer`] for v3's addition).
    #[must_use]
    const fn covers_binding(self) -> bool {
        match self {
            Self::V1 => false,
            Self::V2 | Self::V3 => true,
        }
    }

    /// Whether this schema's canonical covers payer attribution (`payer_kind`,
    /// `paying_account`).
    ///
    /// A separate accessor from [`Self::covers_binding`] rather than folded
    /// into it: v3 covers a strictly larger field set than v2, but the two
    /// booleans answer different questions, and a future schema could cover
    /// binding without payer (or vice versa) — collapsing them into one flag
    /// would stop being able to say which.
    #[must_use]
    const fn covers_payer(self) -> bool {
        match self {
            Self::V1 | Self::V2 => false,
            Self::V3 => true,
        }
    }

    /// The frozen canonical (unsigned) JSON bytes a receipt under this schema
    /// is signed over and verified against.
    #[must_use]
    fn canonical(self, fields: &ReceiptPayload<'_>) -> Vec<u8> {
        match self {
            Self::V1 => canonical_bytes(&fields.canonical_json_v1()),
            Self::V2 => canonical_bytes(&fields.canonical_json_v2()),
            Self::V3 => canonical_bytes(&fields.canonical_json_v3()),
        }
    }
}

/// Verify a persisted `payment_receipt`/`outbound_payment_receipt` payload
/// against a **trusted-signer allow-list**.
///
/// Returns `Some(record)` only if the signature checks out against the
/// embedded public key AND that key is a member of `trusted_signers`. An
/// internally-consistent signature over an *unknown* key proves the payload
/// was not tampered with after signing — it proves nothing about whether the
/// signer should be trusted; anyone can mint a fresh keypair, embed its own
/// public key, and sign an arbitrary settlement, so a caller MUST supply the
/// deployment's own set of trusted signers here (typically the deployment's
/// [`ApprovalSigner::public_key_bytes`], since receipts are self-signed by
/// this same control plane) rather than treating "verifies" as "trustworthy".
///
/// Every receipt is checked against the frozen canonical of the version it was
/// signed under, never against the current [`RECEIPT_VERSION`]: a v1 receipt
/// (no `version` key) and a v2 one both keep verifying, whatever the constant
/// reads today. A claimed version this build has frozen no canonical for —
/// including an explicit `1`, which the v1 canonical does not cover — is
/// refused outright rather than checked against a guessed canonical.
///
/// Returns `None` if the payload is malformed, the hex fields don't decode,
/// the embedded key is not in `trusted_signers`, the claimed version resolves
/// to no frozen canonical, or the signature doesn't verify.
#[must_use]
pub fn verify_signed_receipt(
    payload: &[u8],
    trusted_signers: &[Vec<u8>],
) -> Option<VerifiedReceipt> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let reference = v.get("reference")?.as_str()?.to_owned();
    let amount = v.get("amount")?.as_str()?.to_owned();
    let currency = v.get("currency")?.as_str()?.to_owned();
    let recipient = v.get("recipient")?.as_str()?.to_owned();
    let method = v.get("method")?.as_str()?.to_owned();
    let timestamp = v.get("timestamp")?.as_str()?.to_owned();
    let signed_by_hex = v.get("signed_by")?.as_str()?;
    let signature_hex = v.get("signature_hex")?.as_str()?;
    let pk = crate::hex::decode(signed_by_hex)?;
    let sig = crate::hex::decode(signature_hex)?;
    // Reject an unknown signer before doing any further work (including the
    // signature check below): a key that is not on the allow-list is not
    // trusted no matter how internally consistent its signature is — anyone
    // can mint a keypair and self-sign an arbitrary receipt.
    if !signer_is_trusted(&pk, trusted_signers) {
        return None;
    }
    // Resolve the claimed version to a schema this build has frozen — before
    // any versioned field is read, and never against `RECEIPT_VERSION`. A
    // version with no frozen canonical is refused outright rather than verified
    // against a guessed one; `ReceiptSchema::resolve` documents which claims
    // resolve and why an explicit `1` is not one of them.
    let schema = ReceiptSchema::resolve(v.get("version"))?;
    let (kind, tool_call_id, approval_pos, approved_args_hash, subject) = if schema.covers_binding()
    {
        (
            v.get("kind")?.as_str()?.to_owned(),
            v.get("tool_call_id")?.as_str()?.to_owned(),
            v.get("approval_pos")?.as_str()?.to_owned(),
            v.get("approved_args_hash")?.as_str()?.to_owned(),
            v.get("subject")?.as_str()?.to_owned(),
        )
    } else {
        // v1 signed the six settlement facts and nothing else, so it reports
        // nothing else: an uncovered field read off the payload would leave
        // `verify_signed_receipt` echoing a value no signature vouches for.
        (
            String::new(),
            String::new(),
            String::new(),
            String::new(),
            String::new(),
        )
    };
    let (payer_kind, paying_account) = if schema.covers_payer() {
        (
            v.get("payer_kind")?.as_str()?.to_owned(),
            v.get("paying_account")?.as_str()?.to_owned(),
        )
    } else {
        // v1/v2 signed no payer attribution at all, so a v1/v2 receipt reports
        // payer as explicit unknown — never inferred from other fields — for
        // the same reason the binding tuple falls back above.
        (String::new(), String::new())
    };
    // Rebuild the canonical bytes via the SAME single source the signer used,
    // so the verify path can never check a different field set/order.
    let fields = ReceiptPayload {
        kind: &kind,
        reference: &reference,
        amount: &amount,
        currency: &currency,
        recipient: &recipient,
        method: &method,
        timestamp: &timestamp,
        tool_call_id: &tool_call_id,
        approval_pos: &approval_pos,
        approved_args_hash: &approved_args_hash,
        subject: &subject,
        payer_kind: &payer_kind,
        paying_account: &paying_account,
    };
    let canonical = schema.canonical(&fields);
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedReceipt {
            reference,
            amount,
            currency,
            recipient,
            method,
            timestamp,
            version: schema.number(),
            kind,
            tool_call_id,
            approval_pos,
            approved_args_hash,
            subject,
            payer_kind,
            paying_account,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// The `payment_refusal` field set [`refusal_payload`] signs, named at the call site.
///
/// Mirrors [`ReceiptPayload`]'s reasoning (`#2090`, INV-W5): a positional
/// argument list of same-typed `&str`s invites a silent field swap at the
/// call site, so every field is named here instead.
///
/// Unlike a receipt, a refusal has exactly one schema version — this event
/// kind ships new, with no prior persisted history to keep verifying, so
/// there is no v1/v2 split to carry.
#[derive(Debug, Clone, Copy)]
pub struct RefusalPayload<'a> {
    /// The event kind the payload is stored under (always
    /// `polyc_proto::kinds::PAYMENT_REFUSAL`). Signed so a payload cannot be
    /// re-filed under a different kind, mirroring [`ReceiptPayload::kind`].
    pub kind: &'a str,
    /// The stable, machine-readable reason tag (e.g. `"over_spend_cap"`) —
    /// one of the tags [`crate`]'s callers mint via an exhaustive match over
    /// `polyc_payments::proxy::RejectReason`, or `"unknown"` for a reason
    /// this build has no tag for. Never the free-text `Display` rendering.
    pub reason: &'a str,
    /// A non-secret diagnostic detail for the reason — the wrapped error's
    /// own `Display` text (e.g. the SSRF-guard host, the mandate failure).
    /// Never signer-key or credential material.
    pub reason_detail: &'a str,
    /// The destination host the fetch would have paid, when the reject site
    /// had a host to name (empty otherwise).
    pub merchant_host: &'a str,
    /// The base-unit amount the call requested, as a decimal string, for a
    /// reason that carries one (`over_spend_cap`, `over_budget`); empty for
    /// every other reason.
    pub requested_base_units: &'a str,
    /// The base-unit amount the cap/budget actually permitted, as a decimal
    /// string, for a reason that carries one; empty for every other reason.
    pub permitted_base_units: &'a str,
    /// The `paid_fetch` tool-call id the refused attempt answered.
    pub tool_call_id: &'a str,
    /// Opaque principal the refused attempt is attributed to — the same
    /// status [`ReceiptPayload::subject`] carries.
    pub subject: &'a str,
    /// Decimal string of the unix-seconds clock value at the moment the
    /// reject site recorded the refusal — the `payments` sibling field to
    /// [`ReceiptPayload::timestamp`], but unix-seconds rather than RFC3339:
    /// the recording seam already carries the turn's dispatch-time
    /// `now_unix` (no fresh wall-clock read needed), so this reuses that
    /// value verbatim rather than reformatting it. Without this, a blocked
    /// row has no time field at all and cannot be placed on a ledger
    /// alongside settled receipts.
    pub timestamp: &'a str,
}

impl RefusalPayload<'_> {
    /// The frozen `payment_refusal` canonical: every field, in this struct's
    /// declaration order — the single source both [`refusal_payload`] (the
    /// signing path) and [`verify_signed_refusal`] (the verifying path)
    /// route their canonical bytes through, so the two paths cannot drift.
    #[must_use]
    const fn canonical(&self) -> RefusalCanonical<'_> {
        RefusalCanonical {
            kind: self.kind,
            reason: self.reason,
            reason_detail: self.reason_detail,
            merchant_host: self.merchant_host,
            requested_base_units: self.requested_base_units,
            permitted_base_units: self.permitted_base_units,
            tool_call_id: self.tool_call_id,
            subject: self.subject,
            timestamp: self.timestamp,
        }
    }
}

/// The frozen `payment_refusal` field set, in its frozen order — see
/// [`RefusalPayload::canonical`].
#[derive(Serialize)]
struct RefusalCanonical<'a> {
    kind: &'a str,
    reason: &'a str,
    reason_detail: &'a str,
    merchant_host: &'a str,
    requested_base_units: &'a str,
    permitted_base_units: &'a str,
    tool_call_id: &'a str,
    subject: &'a str,
    timestamp: &'a str,
}

/// JSON payload for a `payment_refusal` event (`#2090`, INV-W5).
///
/// Mirrors [`receipt_payload`]: the signature commits to the canonical
/// (unsigned) JSON form of `RefusalPayload::canonical`; `signed_by` and
/// `signature_hex` are appended after signing and are not covered by the
/// signature. Tampering with any field invalidates the signature.
///
/// Returns `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
pub fn refusal_payload(
    fields: &RefusalPayload<'_>,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(fields.canonical(), signer.as_signer())
}

/// A decoded `payment_refusal` payload after signature verification.
#[derive(Debug, Clone)]
pub struct VerifiedRefusal {
    /// The signed event kind (always `payment_refusal`). Callers should
    /// check it matches the kind the event was stored under, mirroring
    /// [`VerifiedReceipt::kind`].
    pub kind: String,
    /// The stable, machine-readable reason tag.
    pub reason: String,
    /// Non-secret diagnostic detail for the reason.
    pub reason_detail: String,
    /// The destination host the fetch would have paid, or empty.
    pub merchant_host: String,
    /// Requested base-unit amount as a decimal string, or empty.
    pub requested_base_units: String,
    /// Permitted base-unit amount as a decimal string, or empty.
    pub permitted_base_units: String,
    /// The `paid_fetch` tool-call id the refused attempt answered.
    pub tool_call_id: String,
    /// Opaque principal the refused attempt is attributed to.
    pub subject: String,
    /// Decimal string of the unix-seconds clock value at the moment the
    /// reject site recorded the refusal.
    pub timestamp: String,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted `payment_refusal` payload against a **trusted-signer allow-list**.
///
/// The exact same trust posture [`verify_signed_receipt`] documents (an
/// internally-consistent signature over an unknown key proves no tampering,
/// and nothing about trust, so `trusted_signers` must be supplied).
///
/// Returns `None` if the payload is malformed, a field is missing, the hex
/// fields don't decode, the embedded key is not in `trusted_signers`, or the
/// signature doesn't verify. Never panics — a structurally malformed payload
/// (INV-W5b) is exactly the `None` case, not a decode error a caller must
/// handle separately.
#[must_use]
pub fn verify_signed_refusal(
    payload: &[u8],
    trusted_signers: &[Vec<u8>],
) -> Option<VerifiedRefusal> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let kind = v.get("kind")?.as_str()?.to_owned();
    let reason = v.get("reason")?.as_str()?.to_owned();
    let reason_detail = v.get("reason_detail")?.as_str()?.to_owned();
    let merchant_host = v.get("merchant_host")?.as_str()?.to_owned();
    let requested_base_units = v.get("requested_base_units")?.as_str()?.to_owned();
    let permitted_base_units = v.get("permitted_base_units")?.as_str()?.to_owned();
    let tool_call_id = v.get("tool_call_id")?.as_str()?.to_owned();
    let subject = v.get("subject")?.as_str()?.to_owned();
    let timestamp = v.get("timestamp")?.as_str()?.to_owned();
    let signed_by_hex = v.get("signed_by")?.as_str()?;
    let signature_hex = v.get("signature_hex")?.as_str()?;
    let pk = crate::hex::decode(signed_by_hex)?;
    let sig = crate::hex::decode(signature_hex)?;
    if !signer_is_trusted(&pk, trusted_signers) {
        return None;
    }
    let fields = RefusalPayload {
        kind: &kind,
        reason: &reason,
        reason_detail: &reason_detail,
        merchant_host: &merchant_host,
        requested_base_units: &requested_base_units,
        permitted_base_units: &permitted_base_units,
        tool_call_id: &tool_call_id,
        subject: &subject,
        timestamp: &timestamp,
    };
    let canonical = canonical_bytes(&fields.canonical());
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedRefusal {
            kind,
            reason,
            reason_detail,
            merchant_host,
            requested_base_units,
            permitted_base_units,
            tool_call_id,
            subject,
            timestamp,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// The `wallet_link_lifecycle` field set [`wallet_link_lifecycle_payload`]
/// signs, named at the call site (`#2123`).
///
/// Mirrors [`RefusalPayload`]'s reasoning: a positional argument list of
/// same-typed `&str`s invites a silent field swap, so every field is named
/// here instead. One schema version, like [`RefusalPayload`] — this event
/// kind ships new, with no prior persisted history to keep verifying.
#[derive(Debug, Clone, Copy)]
pub struct WalletLinkLifecyclePayload<'a> {
    /// The event kind the payload is stored under (always
    /// `polyc_proto::kinds::WALLET_LINK_LIFECYCLE`).
    pub kind: &'a str,
    /// Which ceremony transition this event records: `"linked"`,
    /// `"renewed"` (limit/expiry updated by `complete_update`), or
    /// `"revoked"` — each minted by its own success-arm call site in
    /// `crates/control-plane/src/wallet_link.rs`'s `complete`/
    /// `complete_revoke`/`complete_update`, never a caller-chosen string.
    pub transition: &'a str,
    /// Opaque principal the ceremony is attributed to — the same status
    /// [`RefusalPayload::subject`] carries.
    pub subject: &'a str,
    /// The linked wallet's on-chain address.
    pub wallet_address: &'a str,
    /// Settlement-token contract (hex) the ceremony's spend cap applies to.
    pub currency: &'a str,
    /// Decimal string of the chain id the ceremony ran on.
    pub chain_id: &'a str,
    /// The spend cap in the settlement token's base units, as a decimal
    /// string; empty for `"revoked"` (no cap to report on a dead link).
    pub limit_base_units: &'a str,
    /// Human-readable spend cap; empty for `"revoked"`.
    pub limit_human: &'a str,
    /// Decimal string of the spend cap's reset period in seconds; empty for
    /// `"renewed"` (TIP-1011's `updateSpendingLimit` cannot change the
    /// period — see `crate::wallet_link::PERIOD_UNCHANGED_NOTICE` in the
    /// control plane) and for `"revoked"`.
    pub period_secs: &'a str,
    /// Decimal string of the unix-seconds authorization expiry; empty for
    /// `"renewed"` (the expiry is unchanged, not re-attested — TIP-1011's
    /// `updateSpendingLimit` never touches it) and for `"revoked"` (no
    /// expiry survives a dead link).
    pub expiry_unix: &'a str,
    /// Comma-joined recipient allowlist (TIP-1011); empty means any
    /// recipient.
    pub recipients: &'a str,
    /// The conversation the ceremony was minted and redeemed in — also the
    /// journal partition (`conv-{conversation_id}`) this event is appended
    /// to.
    pub conversation_id: &'a str,
    /// Decimal string of the unix-**seconds** clock value at the moment the
    /// ceremony handler recorded the transition — the
    /// `payment_refusal.timestamp` sibling, divided from a millisecond clock
    /// exactly once at the recording seam.
    pub timestamp: &'a str,
}

impl WalletLinkLifecyclePayload<'_> {
    /// The frozen `wallet_link_lifecycle` canonical: every field, in this
    /// struct's declaration order — the single source both
    /// [`wallet_link_lifecycle_payload`] (the signing path) and
    /// [`verify_signed_wallet_link_lifecycle`] (the verifying path) route
    /// their canonical bytes through, so the two paths cannot drift.
    #[must_use]
    const fn canonical(&self) -> WalletLinkLifecycleCanonical<'_> {
        WalletLinkLifecycleCanonical {
            kind: self.kind,
            transition: self.transition,
            subject: self.subject,
            wallet_address: self.wallet_address,
            currency: self.currency,
            chain_id: self.chain_id,
            limit_base_units: self.limit_base_units,
            limit_human: self.limit_human,
            period_secs: self.period_secs,
            expiry_unix: self.expiry_unix,
            recipients: self.recipients,
            conversation_id: self.conversation_id,
            timestamp: self.timestamp,
        }
    }
}

/// The frozen `wallet_link_lifecycle` field set, in its frozen order — see
/// [`WalletLinkLifecyclePayload::canonical`].
#[derive(Serialize)]
struct WalletLinkLifecycleCanonical<'a> {
    kind: &'a str,
    transition: &'a str,
    subject: &'a str,
    wallet_address: &'a str,
    currency: &'a str,
    chain_id: &'a str,
    limit_base_units: &'a str,
    limit_human: &'a str,
    period_secs: &'a str,
    expiry_unix: &'a str,
    recipients: &'a str,
    conversation_id: &'a str,
    timestamp: &'a str,
}

/// JSON payload for a `wallet_link_lifecycle` event (`#2123`).
///
/// Mirrors [`refusal_payload`]: the signature commits to the canonical
/// (unsigned) JSON form of `WalletLinkLifecyclePayload::canonical`;
/// `signed_by` and `signature_hex` are appended after signing and are not
/// covered by the signature. Tampering with any field invalidates the
/// signature.
///
/// Returns `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
pub fn wallet_link_lifecycle_payload(
    fields: &WalletLinkLifecyclePayload<'_>,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(fields.canonical(), signer.as_signer())
}

/// A decoded `wallet_link_lifecycle` payload after signature verification.
#[derive(Debug, Clone)]
pub struct VerifiedWalletLinkLifecycle {
    /// The signed event kind (always `wallet_link_lifecycle`).
    pub kind: String,
    /// Which transition this event records: `"linked"`, `"renewed"`, or
    /// `"revoked"` — carried through verbatim, with no known-tag allowlist
    /// gating verification (mirrors INV-W5b: an unrecognized transition tag
    /// still verifies; classifying it is a read-side projection concern).
    pub transition: String,
    /// Opaque principal the ceremony is attributed to.
    pub subject: String,
    /// The linked wallet's on-chain address.
    pub wallet_address: String,
    /// Settlement-token contract (hex).
    pub currency: String,
    /// Decimal string of the chain id.
    pub chain_id: String,
    /// Decimal string of the spend cap in base units, or empty.
    pub limit_base_units: String,
    /// Human-readable spend cap, or empty.
    pub limit_human: String,
    /// Decimal string of the reset period in seconds, or empty.
    pub period_secs: String,
    /// Decimal string of the unix-seconds authorization expiry, or empty.
    pub expiry_unix: String,
    /// Comma-joined recipient allowlist, or empty (any recipient).
    pub recipients: String,
    /// The minting conversation id.
    pub conversation_id: String,
    /// Decimal string of the unix-seconds clock value the ceremony handler
    /// recorded the transition at.
    pub timestamp: String,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted `wallet_link_lifecycle` payload against a
/// **trusted-signer allow-list** (`#2123`).
///
/// The exact same trust posture [`verify_signed_refusal`] documents: an
/// internally-consistent signature over an unknown key proves no tampering,
/// and nothing about trust, so `trusted_signers` must be supplied.
///
/// Returns `None` if the payload is malformed, a field is missing, the hex
/// fields don't decode, the embedded key is not in `trusted_signers`, or the
/// signature doesn't verify. Never panics.
#[must_use]
pub fn verify_signed_wallet_link_lifecycle(
    payload: &[u8],
    trusted_signers: &[Vec<u8>],
) -> Option<VerifiedWalletLinkLifecycle> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let kind = v.get("kind")?.as_str()?.to_owned();
    let transition = v.get("transition")?.as_str()?.to_owned();
    let subject = v.get("subject")?.as_str()?.to_owned();
    let wallet_address = v.get("wallet_address")?.as_str()?.to_owned();
    let currency = v.get("currency")?.as_str()?.to_owned();
    let chain_id = v.get("chain_id")?.as_str()?.to_owned();
    let limit_base_units = v.get("limit_base_units")?.as_str()?.to_owned();
    let limit_human = v.get("limit_human")?.as_str()?.to_owned();
    let period_secs = v.get("period_secs")?.as_str()?.to_owned();
    let expiry_unix = v.get("expiry_unix")?.as_str()?.to_owned();
    let recipients = v.get("recipients")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let timestamp = v.get("timestamp")?.as_str()?.to_owned();
    let signed_by_hex = v.get("signed_by")?.as_str()?;
    let signature_hex = v.get("signature_hex")?.as_str()?;
    let pk = crate::hex::decode(signed_by_hex)?;
    let sig = crate::hex::decode(signature_hex)?;
    if !signer_is_trusted(&pk, trusted_signers) {
        return None;
    }
    let fields = WalletLinkLifecyclePayload {
        kind: &kind,
        transition: &transition,
        subject: &subject,
        wallet_address: &wallet_address,
        currency: &currency,
        chain_id: &chain_id,
        limit_base_units: &limit_base_units,
        limit_human: &limit_human,
        period_secs: &period_secs,
        expiry_unix: &expiry_unix,
        recipients: &recipients,
        conversation_id: &conversation_id,
        timestamp: &timestamp,
    };
    let canonical = canonical_bytes(&fields.canonical());
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedWalletLinkLifecycle {
            kind,
            transition,
            subject,
            wallet_address,
            currency,
            chain_id,
            limit_base_units,
            limit_human,
            period_secs,
            expiry_unix,
            recipients,
            conversation_id,
            timestamp,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// TTL for a minted `resolve_token` (`#787`).
///
/// Generous enough that a human has time to see and act on the approval card
/// (which can sit in a Slack/Telegram thread for hours), short enough that a
/// token captured off a stale card cannot resolve the request indefinitely.
/// Independent of the underlying approval's own lifetime — a request that
/// outlives the TTL simply needs the control plane to re-mint (a fresh
/// `ListPending` call re-renders the card with a fresh token).
pub const RESOLVE_TOKEN_TTL_MS: u64 = 24 * 60 * 60 * 1000;

/// The canonical (signature-covered) form of a `resolve_token` (`#787`).
///
/// Binds the token to the exact `(request_id, conversation_id)` pair it was
/// minted for and the time it was minted, so it cannot be replayed against a
/// different request, a different conversation, or presented once its TTL has
/// elapsed.
fn resolve_token_canonical(request_id: &str, conversation_id: &str, minted_at_ms: u64) -> Vec<u8> {
    canonical_bytes(&ResolveTokenCanonical {
        request_id,
        conversation_id,
        minted_at_ms,
    })
}

/// The signed `resolve_token` field set, in its frozen order.
#[derive(Serialize)]
struct ResolveTokenCanonical<'a> {
    request_id: &'a str,
    conversation_id: &'a str,
    minted_at_ms: u64,
}

/// A minted `resolve_token`: the canonical body plus its signature.
///
/// The only signed payload in this module with no `signed_by`: the token is
/// verified against the control plane's own key, supplied by the caller of
/// [`verify_resolve_token`], never one carried on the token itself.
#[derive(Serialize)]
struct ResolveToken<'a> {
    #[serde(flatten)]
    body: ResolveTokenCanonical<'a>,
    signature_hex: String,
}

/// Mint a short-lived, signed `resolve_token` (`#787`) scoped to one
/// `(request_id, conversation_id)` pair.
///
/// This is the capability `ApprovalService.Respond` requires alongside the
/// plain `request_id`/`conversation_id` it already checks: minted by the
/// control plane at the moment it hands a pending approval to an edge for
/// rendering (`AgentEnd.pending_approvals`, `ListPendingReply.pending`), it is
/// opaque to — and unforgeable by — anything downstream of that mint point,
/// including a compromised harness pod (the harness never holds the signing
/// key and never sees the minted token; it only proposes the tool call the
/// token later authorizes resolving). `minted_at_ms` is the caller's wall
/// clock at mint time; pass a real timestamp in production, an injected one in
/// tests.
///
/// Returns the token as a lowercase-hex opaque string, safe to carry on any
/// wire surface (a button value, a proto field) alongside `request_id`.
#[must_use]
pub fn mint_resolve_token(
    request_id: &str,
    conversation_id: &str,
    minted_at_ms: u64,
    signer: &ApprovalSigner,
) -> String {
    let canonical = resolve_token_canonical(request_id, conversation_id, minted_at_ms);
    let signature = signer.sign(&canonical);
    let full = ResolveToken {
        body: ResolveTokenCanonical {
            request_id,
            conversation_id,
            minted_at_ms,
        },
        signature_hex: crate::hex::lower(&signature),
    };
    crate::hex::lower(&canonical_bytes(&full))
}

/// Verify a `resolve_token` minted by [`mint_resolve_token`] against the
/// `(request_id, conversation_id)` a `Respond` call presents it for.
///
/// Returns `true` only when ALL hold: the token decodes, its embedded
/// signature verifies against `signer`'s public key, its bound `request_id`
/// and `conversation_id` equal the ones supplied, and `now_ms - minted_at_ms`
/// is within [`RESOLVE_TOKEN_TTL_MS`] (a token minted in the future, by clock
/// skew beyond the TTL, also fails — fail closed rather than trust an
/// out-of-bounds clock). Fails closed on any malformed field.
#[must_use]
pub fn verify_resolve_token(
    token: &str,
    request_id: &str,
    conversation_id: &str,
    now_ms: u64,
    signer: &ApprovalSigner,
) -> bool {
    let Some(bytes) = crate::hex::decode(token) else {
        return false;
    };
    let Ok(v) = serde_json::from_slice::<Value>(&bytes) else {
        return false;
    };
    let (
        Some(bound_request_id),
        Some(bound_conversation_id),
        Some(minted_at_ms),
        Some(signature_hex),
    ) = (
        v.get("request_id").and_then(Value::as_str),
        v.get("conversation_id").and_then(Value::as_str),
        v.get("minted_at_ms").and_then(Value::as_u64),
        v.get("signature_hex").and_then(Value::as_str),
    )
    else {
        return false;
    };
    if bound_request_id != request_id || bound_conversation_id != conversation_id {
        return false;
    }
    let elapsed = now_ms.abs_diff(minted_at_ms);
    if elapsed > RESOLVE_TOKEN_TTL_MS {
        return false;
    }
    let Some(sig) = crate::hex::decode(signature_hex) else {
        return false;
    };
    let canonical = resolve_token_canonical(bound_request_id, bound_conversation_id, minted_at_ms);
    verify(&signer.public_key_bytes(), &canonical, &sig)
}

/// The canonical (signature-covered) form of an `admin_model_change` audit
/// record (`#787`).
///
/// Covers who made the change (the authenticated bearer principal), what the
/// selection moved from and to, and when — so the durable record cannot be
/// forged or re-attributed to a different operator without invalidating the
/// signature. `signed_by`/`signature_hex` are appended after signing and are
/// not covered.
fn admin_model_change_canonical(
    principal: &str,
    previous_provider: &str,
    previous_model: &str,
    new_provider: &str,
    new_model: &str,
    changed_at_ms: u64,
) -> Vec<u8> {
    canonical_bytes(&AdminModelChangeCanonical {
        principal,
        previous_provider,
        previous_model,
        new_provider,
        new_model,
        changed_at_ms,
    })
}

/// The signed `admin_model_change` field set, in its frozen order.
#[derive(Serialize)]
struct AdminModelChangeCanonical<'a> {
    principal: &'a str,
    previous_provider: &'a str,
    previous_model: &'a str,
    new_provider: &'a str,
    new_model: &'a str,
    changed_at_ms: u64,
}

/// JSON payload for a signed `admin_model_change` audit event (`#787`).
///
/// The durable, tamper-evident record that the live `provider/model`
/// selection changed, written on every successful `POST /admin/model` — the
/// same posture `#590`/`#594`/`#623` established for other admin-signed
/// actions. Returns `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field of the canonical contract
pub fn admin_model_change_payload(
    principal: &str,
    previous_provider: &str,
    previous_model: &str,
    new_provider: &str,
    new_model: &str,
    changed_at_ms: u64,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        AdminModelChangeCanonical {
            principal,
            previous_provider,
            previous_model,
            new_provider,
            new_model,
            changed_at_ms,
        },
        signer.as_signer(),
    )
}

/// A verified `admin_model_change` audit record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedAdminModelChange {
    /// The authenticated bearer principal that made the change.
    pub principal: String,
    /// Provider before the change (may be empty — deferred to harness default).
    pub previous_provider: String,
    /// Model before the change.
    pub previous_model: String,
    /// Provider after the change.
    pub new_provider: String,
    /// Model after the change.
    pub new_model: String,
    /// Unix ms the change was applied.
    pub changed_at_ms: u64,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted `admin_model_change` payload.
///
/// `None` for a malformed payload or a signature that does not verify — the
/// caller treats the record as untrusted (fail closed).
#[must_use]
pub fn verify_admin_model_change(payload: &[u8]) -> Option<VerifiedAdminModelChange> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let principal = v.get("principal")?.as_str()?.to_owned();
    let previous_provider = v.get("previous_provider")?.as_str()?.to_owned();
    let previous_model = v.get("previous_model")?.as_str()?.to_owned();
    let new_provider = v.get("new_provider")?.as_str()?.to_owned();
    let new_model = v.get("new_model")?.as_str()?.to_owned();
    let changed_at_ms = v.get("changed_at_ms")?.as_u64()?;
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = admin_model_change_canonical(
        &principal,
        &previous_provider,
        &previous_model,
        &new_provider,
        &new_model,
        changed_at_ms,
    );
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedAdminModelChange {
            principal,
            previous_provider,
            previous_model,
            new_provider,
            new_model,
            changed_at_ms,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// One key's lifecycle move within a credential mutation
/// (`docs/design/credential-store.md`).
///
/// Carries the key id and the two lifecycle states it moved between, and
/// nothing else. A salt, a digest, or a public key must never reach an audit
/// record (INV-C3), so this type has nowhere to put one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialKeyTransition {
    /// The key that moved.
    pub kid: String,
    /// The state it moved from (`"absent"` for a key that did not exist).
    pub from: String,
    /// The state it moved to.
    pub to: String,
}

/// The canonical (signature-covered) form of a credential-mutation audit
/// record (`docs/design/credential-store.md`, INV-C6).
///
/// Covers which mutation ran, who ran it, which record and key it named, and
/// every key lifecycle transition it caused — so a signed enrollment cannot
/// be replayed as a revocation, nor re-attributed to a different admin,
/// without invalidating the signature. `signed_by`/`signature_hex` are
/// appended after signing and are not covered.
fn credential_change_canonical(
    change: &str,
    principal: &str,
    edge_id: &str,
    kid: &str,
    grants: &str,
    transitions: &[CredentialKeyTransition],
    changed_at_ms: u64,
) -> Vec<u8> {
    canonical_bytes(&credential_change_fields(
        change,
        principal,
        edge_id,
        kid,
        grants,
        transitions,
        changed_at_ms,
    ))
}

/// The signed credential-mutation field set, in its frozen order.
///
/// The only canonical in this module that nests an object, and so the only one
/// where the ordering hazard `#1842` describes applied at two levels: the
/// `transitions` elements are ordered by [`CredentialTransition`]'s own field
/// declaration, not by a map.
#[derive(Serialize)]
struct CredentialChangeCanonical<'a> {
    change: &'a str,
    principal: &'a str,
    edge_id: &'a str,
    kid: &'a str,
    grants: &'a str,
    transitions: Vec<CredentialTransition<'a>>,
    changed_at_ms: u64,
}

/// One `transitions` element of a [`CredentialChangeCanonical`], in its frozen
/// order.
#[derive(Serialize)]
struct CredentialTransition<'a> {
    kid: &'a str,
    from: &'a str,
    to: &'a str,
}

/// Build the credential-mutation canonical struct.
///
/// Shared by [`credential_change_canonical`] and
/// [`credential_change_payload`], which would otherwise each map the
/// transitions into their serialized form and could drift.
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field of the canonical contract
fn credential_change_fields<'a>(
    change: &'a str,
    principal: &'a str,
    edge_id: &'a str,
    kid: &'a str,
    grants: &'a str,
    transitions: &'a [CredentialKeyTransition],
    changed_at_ms: u64,
) -> CredentialChangeCanonical<'a> {
    CredentialChangeCanonical {
        change,
        principal,
        edge_id,
        kid,
        grants,
        transitions: transitions
            .iter()
            .map(|t| CredentialTransition {
                kid: &t.kid,
                from: &t.from,
                to: &t.to,
            })
            .collect(),
        changed_at_ms,
    }
}

/// JSON payload for a signed credential-mutation audit event
/// (`docs/design/credential-store.md`).
///
/// The durable, tamper-evident record that an admin enrolled, rotated, or
/// revoked a credential, appended to the `admin-audit` partition on every
/// mutation. `change` is the event kind
/// (`polyc_proto::kinds::CREDENTIAL_ENROLLED` and its three siblings), which
/// is signature-covered so one kind's record cannot be presented as
/// another's. `grants` is what the record may be used for after the change,
/// also signature-covered: an admin credential and a chat edge move through
/// the same verbs, so an audit line that omitted it could not tell them
/// apart.
///
/// Unlike [`admin_model_change_payload`], whose append is best-effort, a
/// failed append of this record fails the mutation that produced it: for a
/// credential change the audit line is load-bearing.
///
/// Returns `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field of the canonical contract
pub fn credential_change_payload(
    change: &str,
    principal: &str,
    edge_id: &str,
    kid: &str,
    grants: &str,
    transitions: &[CredentialKeyTransition],
    changed_at_ms: u64,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        credential_change_fields(
            change,
            principal,
            edge_id,
            kid,
            grants,
            transitions,
            changed_at_ms,
        ),
        signer.as_signer(),
    )
}

/// A verified credential-mutation audit record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedCredentialChange {
    /// Which mutation ran (the event kind).
    pub change: String,
    /// The authenticated admin principal that ran it.
    pub principal: String,
    /// The record that changed.
    pub edge_id: String,
    /// The key the mutation named (empty for a whole-record revocation).
    pub kid: String,
    /// What the record grants AFTER the mutation — `"edge"`, `"admin"`,
    /// `"edge, admin"`, or `"none"`.
    ///
    /// Signature-covered, and the reason it exists: an admin credential and
    /// a chat edge are the same record shape and the same verbs, so without
    /// this an audit trail cannot tell "someone enrolled a chat edge" from
    /// "someone granted themselves control of this deployment".
    pub grants: String,
    /// Every key lifecycle transition the mutation caused.
    pub transitions: Vec<CredentialKeyTransition>,
    /// Unix ms the mutation was applied.
    pub changed_at_ms: u64,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted credential-mutation payload.
///
/// `None` for a malformed payload or a signature that does not verify — the
/// caller treats the record as untrusted (fail closed).
///
/// # Records written before `grants` existed
///
/// They return `None` here, indistinguishable from a forgery. `grants` is a
/// required field of the canonical form, so a payload without it does not
/// verify — deliberately, because loosening the check to tolerate an absent
/// field would let a forged record claim the same absence and be believed.
/// The credential audit family has no non-test reader yet, so nothing
/// regresses today; a deployment that already wrote credential audit lines
/// keeps them as bytes in the log and loses only the ability to verify them
/// through this function.
#[must_use]
pub fn verify_credential_change(payload: &[u8]) -> Option<VerifiedCredentialChange> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let change = v.get("change")?.as_str()?.to_owned();
    let principal = v.get("principal")?.as_str()?.to_owned();
    let edge_id = v.get("edge_id")?.as_str()?.to_owned();
    let kid = v.get("kid")?.as_str()?.to_owned();
    let grants = v.get("grants")?.as_str()?.to_owned();
    let mut transitions = Vec::new();
    for item in v.get("transitions")?.as_array()? {
        transitions.push(CredentialKeyTransition {
            kid: item.get("kid")?.as_str()?.to_owned(),
            from: item.get("from")?.as_str()?.to_owned(),
            to: item.get("to")?.as_str()?.to_owned(),
        });
    }
    let changed_at_ms = v.get("changed_at_ms")?.as_u64()?;
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = credential_change_canonical(
        &change,
        &principal,
        &edge_id,
        &kid,
        &grants,
        &transitions,
        changed_at_ms,
    );
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedCredentialChange {
            change,
            principal,
            edge_id,
            kid,
            grants,
            transitions,
            changed_at_ms,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Canonical bytes signed for a `routine_created` audit event (`#1497`).
fn routine_created_canonical(
    routine: &str,
    creator_persona: &str,
    conversation_id: &str,
    tool_call_id: &str,
    args_hash: &str,
    created_at_ms: u64,
) -> Vec<u8> {
    canonical_bytes(&RoutineCreatedCanonical {
        routine,
        creator_persona,
        conversation_id,
        tool_call_id,
        args_hash,
        created_at_ms,
    })
}

/// The signed `routine_created` field set, in its frozen order.
#[derive(Serialize)]
struct RoutineCreatedCanonical<'a> {
    routine: &'a str,
    creator_persona: &'a str,
    conversation_id: &'a str,
    tool_call_id: &'a str,
    args_hash: &'a str,
    created_at_ms: u64,
}

/// JSON payload for a signed `routine_created` audit event.
///
/// `#1497`, INV-RL6: who created the routine, from which conversation, and
/// when. Mirrors [`admin_model_change_payload`]'s shape — the same
/// control-plane-authored-audit-record pattern, a distinct kind. #1495 adds
/// the sibling `routine_paused`/`routine_resumed`/`routine_deleted` payloads
/// on this same construction.
///
/// `tool_call_id` (`#1638`) is the harness's id for the tool call this event
/// audits, and `args_hash` is the sha256 hex of that call's approved
/// `args_json` (mirrors `harness_dialer::approved_args_hash`) — together the
/// cross-replay idempotency key `routine_nav`'s dedup check
/// (`find_completed_mutation`) looks up before ever touching the CR, so an
/// orphan-recovery replay of the same dispatch is a no-op rather than a
/// second signed event and a duplicate routine, and the SAME `tool_call_id`
/// carrying different args never returns a stale acknowledgement.
///
/// Returns `(payload_bytes, signature, signer_public_key)`.
#[must_use]
pub fn routine_created_payload(
    routine: &str,
    creator_persona: &str,
    conversation_id: &str,
    tool_call_id: &str,
    args_hash: &str,
    created_at_ms: u64,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        RoutineCreatedCanonical {
            routine,
            creator_persona,
            conversation_id,
            tool_call_id,
            args_hash,
            created_at_ms,
        },
        signer.as_signer(),
    )
}

/// A verified `routine_created` audit record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedRoutineCreated {
    /// The created routine's CR name.
    pub routine: String,
    /// The persona id that created it.
    pub creator_persona: String,
    /// The originating conversation id.
    pub conversation_id: String,
    /// The harness tool-call id this event audits (`#1638`).
    pub tool_call_id: String,
    /// sha256 hex of the approved `args_json` (`#1638`).
    pub args_hash: String,
    /// Unix ms the CR was written.
    pub created_at_ms: u64,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted `routine_created` payload.
///
/// `None` for a malformed payload or a signature that does not verify — the
/// caller treats the record as untrusted (fail closed).
#[must_use]
pub fn verify_routine_created(payload: &[u8]) -> Option<VerifiedRoutineCreated> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let routine = v.get("routine")?.as_str()?.to_owned();
    let creator_persona = v.get("creator_persona")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let tool_call_id = v.get("tool_call_id")?.as_str()?.to_owned();
    let args_hash = v.get("args_hash")?.as_str()?.to_owned();
    let created_at_ms = v.get("created_at_ms")?.as_u64()?;
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = routine_created_canonical(
        &routine,
        &creator_persona,
        &conversation_id,
        &tool_call_id,
        &args_hash,
        created_at_ms,
    );
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedRoutineCreated {
            routine,
            creator_persona,
            conversation_id,
            tool_call_id,
            args_hash,
            created_at_ms,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Canonical bytes signed for a `routine_paused` audit event (`#1495`).
fn routine_paused_canonical(
    routine: &str,
    actor_persona: &str,
    conversation_id: &str,
    tool_call_id: &str,
    args_hash: &str,
    paused_at_ms: u64,
    reason: Option<&str>,
) -> Vec<u8> {
    canonical_bytes(&RoutinePausedCanonical {
        routine,
        actor_persona,
        conversation_id,
        tool_call_id,
        args_hash,
        paused_at_ms,
        reason,
    })
}

/// The signed `routine_paused` field set, in its frozen order.
///
/// `reason` is signed as an explicit `null` when the pauser gave none — the
/// key is always present, so the absent case is covered by the signature the
/// same way a present one is.
#[derive(Serialize)]
struct RoutinePausedCanonical<'a> {
    routine: &'a str,
    actor_persona: &'a str,
    conversation_id: &'a str,
    tool_call_id: &'a str,
    args_hash: &'a str,
    paused_at_ms: u64,
    reason: Option<&'a str>,
}

/// JSON payload for a signed `routine_paused` audit event.
///
/// `#1495`, INV-RL6: who paused the routine, from which conversation, when,
/// and (if given) why. Mirrors [`routine_created_payload`]'s shape — the
/// same control-plane-authored-audit-record pattern, a distinct kind. Pause
/// takes effect immediately with no confirmation (INV-RL2 does not apply to
/// pause/resume — see the invariants doc) but still leaves exactly one
/// signed event. `args_hash` (`#1638`) mirrors `routine_created_payload`'s
/// own field — see its doc.
///
/// Returns `(payload_bytes, signature, signer_public_key)`.
#[must_use]
#[allow(clippy::too_many_arguments)] // one distinct signed field per line, mirrors routine_created_payload
pub fn routine_paused_payload(
    routine: &str,
    actor_persona: &str,
    conversation_id: &str,
    tool_call_id: &str,
    args_hash: &str,
    paused_at_ms: u64,
    reason: Option<&str>,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        RoutinePausedCanonical {
            routine,
            actor_persona,
            conversation_id,
            tool_call_id,
            args_hash,
            paused_at_ms,
            reason,
        },
        signer.as_signer(),
    )
}

/// A verified `routine_paused` audit record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedRoutinePaused {
    /// The paused routine's CR name.
    pub routine: String,
    /// The persona id that paused it.
    pub actor_persona: String,
    /// The originating conversation id.
    pub conversation_id: String,
    /// The harness tool-call id this event audits (`#1638`).
    pub tool_call_id: String,
    /// sha256 hex of the approved `args_json` (`#1638`).
    pub args_hash: String,
    /// Unix ms the pause was recorded.
    pub paused_at_ms: u64,
    /// Why the routine was paused, if the pauser gave one.
    pub reason: Option<String>,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted `routine_paused` payload.
///
/// `None` for a malformed payload or a signature that does not verify — the
/// caller treats the record as untrusted (fail closed).
#[must_use]
pub fn verify_routine_paused(payload: &[u8]) -> Option<VerifiedRoutinePaused> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let routine = v.get("routine")?.as_str()?.to_owned();
    let actor_persona = v.get("actor_persona")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let tool_call_id = v.get("tool_call_id")?.as_str()?.to_owned();
    let args_hash = v.get("args_hash")?.as_str()?.to_owned();
    let paused_at_ms = v.get("paused_at_ms")?.as_u64()?;
    let reason = v.get("reason").and_then(|r| r.as_str()).map(str::to_owned);
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = routine_paused_canonical(
        &routine,
        &actor_persona,
        &conversation_id,
        &tool_call_id,
        &args_hash,
        paused_at_ms,
        reason.as_deref(),
    );
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedRoutinePaused {
            routine,
            actor_persona,
            conversation_id,
            tool_call_id,
            args_hash,
            paused_at_ms,
            reason,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Canonical bytes signed for a `routine_resumed` audit event (`#1495`).
fn routine_resumed_canonical(
    routine: &str,
    actor_persona: &str,
    conversation_id: &str,
    tool_call_id: &str,
    args_hash: &str,
    resumed_at_ms: u64,
) -> Vec<u8> {
    canonical_bytes(&RoutineResumedCanonical {
        routine,
        actor_persona,
        conversation_id,
        tool_call_id,
        args_hash,
        resumed_at_ms,
    })
}

/// The signed `routine_resumed` field set, in its frozen order.
#[derive(Serialize)]
struct RoutineResumedCanonical<'a> {
    routine: &'a str,
    actor_persona: &'a str,
    conversation_id: &'a str,
    tool_call_id: &'a str,
    args_hash: &'a str,
    resumed_at_ms: u64,
}

/// JSON payload for a signed `routine_resumed` audit event.
///
/// `#1495`, INV-RL6: the un-pause sibling of [`routine_paused_payload`] —
/// also immediate, no confirmation. `args_hash` (`#1638`) mirrors
/// [`routine_created_payload`]'s own field — see its doc.
///
/// Returns `(payload_bytes, signature, signer_public_key)`.
#[must_use]
pub fn routine_resumed_payload(
    routine: &str,
    actor_persona: &str,
    conversation_id: &str,
    tool_call_id: &str,
    args_hash: &str,
    resumed_at_ms: u64,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        RoutineResumedCanonical {
            routine,
            actor_persona,
            conversation_id,
            tool_call_id,
            args_hash,
            resumed_at_ms,
        },
        signer.as_signer(),
    )
}

/// A verified `routine_resumed` audit record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedRoutineResumed {
    /// The resumed routine's CR name.
    pub routine: String,
    /// The persona id that resumed it.
    pub actor_persona: String,
    /// The originating conversation id.
    pub conversation_id: String,
    /// The harness tool-call id this event audits (`#1638`).
    pub tool_call_id: String,
    /// sha256 hex of the approved `args_json` (`#1638`).
    pub args_hash: String,
    /// Unix ms the resume was recorded.
    pub resumed_at_ms: u64,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted `routine_resumed` payload.
///
/// `None` for a malformed payload or a signature that does not verify — the
/// caller treats the record as untrusted (fail closed).
#[must_use]
pub fn verify_routine_resumed(payload: &[u8]) -> Option<VerifiedRoutineResumed> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let routine = v.get("routine")?.as_str()?.to_owned();
    let actor_persona = v.get("actor_persona")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let tool_call_id = v.get("tool_call_id")?.as_str()?.to_owned();
    let args_hash = v.get("args_hash")?.as_str()?.to_owned();
    let resumed_at_ms = v.get("resumed_at_ms")?.as_u64()?;
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = routine_resumed_canonical(
        &routine,
        &actor_persona,
        &conversation_id,
        &tool_call_id,
        &args_hash,
        resumed_at_ms,
    );
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedRoutineResumed {
            routine,
            actor_persona,
            conversation_id,
            tool_call_id,
            args_hash,
            resumed_at_ms,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Canonical bytes signed for a `routine_deleted` audit event (`#1495`).
fn routine_deleted_canonical(
    routine: &str,
    actor_persona: &str,
    conversation_id: &str,
    tool_call_id: &str,
    args_hash: &str,
    deleted_at_ms: u64,
) -> Vec<u8> {
    canonical_bytes(&RoutineDeletedCanonical {
        routine,
        actor_persona,
        conversation_id,
        tool_call_id,
        args_hash,
        deleted_at_ms,
    })
}

/// The signed `routine_deleted` field set, in its frozen order.
#[derive(Serialize)]
struct RoutineDeletedCanonical<'a> {
    routine: &'a str,
    actor_persona: &'a str,
    conversation_id: &'a str,
    tool_call_id: &'a str,
    args_hash: &'a str,
    deleted_at_ms: u64,
}

/// JSON payload for a signed `routine_deleted` audit event.
///
/// `#1495`, INV-RL2/RL6: who deleted the routine, from which conversation,
/// and when. Unlike pause/resume, only ever minted once a human has approved
/// the mid-turn confirmation for this delete. `args_hash` (`#1638`) mirrors
/// [`routine_created_payload`]'s own field — see its doc.
///
/// Returns `(payload_bytes, signature, signer_public_key)`.
#[must_use]
pub fn routine_deleted_payload(
    routine: &str,
    actor_persona: &str,
    conversation_id: &str,
    tool_call_id: &str,
    args_hash: &str,
    deleted_at_ms: u64,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        RoutineDeletedCanonical {
            routine,
            actor_persona,
            conversation_id,
            tool_call_id,
            args_hash,
            deleted_at_ms,
        },
        signer.as_signer(),
    )
}

/// A verified `routine_deleted` audit record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedRoutineDeleted {
    /// The deleted routine's CR name.
    pub routine: String,
    /// The persona id that deleted it.
    pub actor_persona: String,
    /// The originating conversation id.
    pub conversation_id: String,
    /// The harness tool-call id this event audits (`#1638`).
    pub tool_call_id: String,
    /// sha256 hex of the approved `args_json` (`#1638`).
    pub args_hash: String,
    /// Unix ms the deletion was recorded.
    pub deleted_at_ms: u64,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted `routine_deleted` payload.
///
/// `None` for a malformed payload or a signature that does not verify — the
/// caller treats the record as untrusted (fail closed).
#[must_use]
pub fn verify_routine_deleted(payload: &[u8]) -> Option<VerifiedRoutineDeleted> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let routine = v.get("routine")?.as_str()?.to_owned();
    let actor_persona = v.get("actor_persona")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let tool_call_id = v.get("tool_call_id")?.as_str()?.to_owned();
    let args_hash = v.get("args_hash")?.as_str()?.to_owned();
    let deleted_at_ms = v.get("deleted_at_ms")?.as_u64()?;
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = routine_deleted_canonical(
        &routine,
        &actor_persona,
        &conversation_id,
        &tool_call_id,
        &args_hash,
        deleted_at_ms,
    );
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedRoutineDeleted {
            routine,
            actor_persona,
            conversation_id,
            tool_call_id,
            args_hash,
            deleted_at_ms,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Canonical bytes signed for a `routine_scope_changed` audit event (`#1806`).
fn routine_scope_changed_canonical(
    routine: &str,
    actor_persona: &str,
    conversation_id: &str,
    tool_call_id: &str,
    args_hash: &str,
    scope: &str,
    changed_at_ms: u64,
) -> Vec<u8> {
    canonical_bytes(&RoutineScopeChangedCanonical {
        routine,
        actor_persona,
        conversation_id,
        tool_call_id,
        args_hash,
        scope,
        changed_at_ms,
    })
}

/// The signed `routine_scope_changed` field set, in its frozen order.
#[derive(Serialize)]
struct RoutineScopeChangedCanonical<'a> {
    routine: &'a str,
    actor_persona: &'a str,
    conversation_id: &'a str,
    tool_call_id: &'a str,
    args_hash: &'a str,
    scope: &'a str,
    changed_at_ms: u64,
}

/// JSON payload for a signed `routine_scope_changed` audit event.
///
/// `#1806`, INV-RL6: who flipped the routine's sharing, to which value, from
/// which conversation, and when. Mirrors [`routine_paused_payload`]'s shape
/// — the same control-plane-authored-audit-record pattern, a distinct kind.
/// Unlike pause/resume/delete, only ever minted for the routine's OWNER: an
/// admin who is not the owner is refused before this is ever called (see
/// `crate::approval::ApprovalSigner`'s caller, `routine_nav::execute_scope`,
/// which mirrors `execute_fire`'s INV-RL11 owner-only gate rather than the
/// mutation trio's owner-or-admin one). `args_hash` (`#1638`) mirrors
/// [`routine_created_payload`]'s own field — see its doc.
///
/// Returns `(payload_bytes, signature, signer_public_key)`.
#[must_use]
#[allow(clippy::too_many_arguments)] // one distinct signed field per line, mirrors routine_created_payload
pub fn routine_scope_changed_payload(
    routine: &str,
    actor_persona: &str,
    conversation_id: &str,
    tool_call_id: &str,
    args_hash: &str,
    scope: &str,
    changed_at_ms: u64,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        RoutineScopeChangedCanonical {
            routine,
            actor_persona,
            conversation_id,
            tool_call_id,
            args_hash,
            scope,
            changed_at_ms,
        },
        signer.as_signer(),
    )
}

/// A verified `routine_scope_changed` audit record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedRoutineScopeChanged {
    /// The routine's CR name.
    pub routine: String,
    /// The persona id that flipped its scope — always the routine's owner.
    pub actor_persona: String,
    /// The originating conversation id.
    pub conversation_id: String,
    /// The harness tool-call id this event audits (`#1638`).
    pub tool_call_id: String,
    /// sha256 hex of the approved `args_json` (`#1638`).
    pub args_hash: String,
    /// The scope the routine was set to (`"public"` or `"private"`).
    pub scope: String,
    /// Unix ms the flip was recorded.
    pub changed_at_ms: u64,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted `routine_scope_changed` payload.
///
/// `None` for a malformed payload or a signature that does not verify — the
/// caller treats the record as untrusted (fail closed).
#[must_use]
pub fn verify_routine_scope_changed(payload: &[u8]) -> Option<VerifiedRoutineScopeChanged> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let routine = v.get("routine")?.as_str()?.to_owned();
    let actor_persona = v.get("actor_persona")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let tool_call_id = v.get("tool_call_id")?.as_str()?.to_owned();
    let args_hash = v.get("args_hash")?.as_str()?.to_owned();
    let scope = v.get("scope")?.as_str()?.to_owned();
    let changed_at_ms = v.get("changed_at_ms")?.as_u64()?;
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = routine_scope_changed_canonical(
        &routine,
        &actor_persona,
        &conversation_id,
        &tool_call_id,
        &args_hash,
        &scope,
        changed_at_ms,
    );
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedRoutineScopeChanged {
            routine,
            actor_persona,
            conversation_id,
            tool_call_id,
            args_hash,
            scope,
            changed_at_ms,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Extract `request_id` from an `approval_request` payload.
#[must_use]
pub fn decode_request_id(payload: &[u8]) -> Option<String> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    Some(v.get("request_id")?.as_str()?.to_owned())
}

/// Extract `(request_id, tool_name, args_json)` from an `approval_request`
/// payload — the fields a v2 `approval_response` must sign to bind the approval
/// to the request identity.
#[must_use]
pub fn decode_request_fields(payload: &[u8]) -> Option<(String, String, String)> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    Some((
        v.get("request_id")?.as_str()?.to_owned(),
        v.get("tool_name")?.as_str()?.to_owned(),
        v.get("args_json")?.as_str()?.to_owned(),
    ))
}

/// Extract the `sandbox_mode` an `approval_request` was emitted under.
///
/// The mode the harness was running when it paused the call. Separate from
/// [`decode_request_fields`] so its many callers keep their tuple shape; the
/// control plane signs this into the response so a remembered approval is
/// bound to the mode it was granted under. Empty/absent → `""`.
#[must_use]
pub fn decode_request_sandbox_mode(payload: &[u8]) -> String {
    serde_json::from_slice::<Value>(payload)
        .ok()
        .and_then(|v| {
            v.get("sandbox_mode")
                .and_then(Value::as_str)
                .map(str::to_owned)
        })
        .unwrap_or_default()
}

/// Extract the override `reason` an `approval_request` carried.
///
/// Non-empty only for the lethal-trifecta / Rule-of-Two containment override;
/// empty/absent → `""` (an ordinary gated call, or a record written before the
/// field existed). Used by the edge to render the gate's explanation and by
/// forensics to show why a trifecta-gated call was paused.
#[must_use]
pub fn decode_request_reason(payload: &[u8]) -> String {
    serde_json::from_slice::<Value>(payload)
        .ok()
        .and_then(|v| v.get("reason").and_then(Value::as_str).map(str::to_owned))
        .unwrap_or_default()
}

/// Extract the `missing_capabilities` recorded on an `approval_request`
/// payload (`#595`) — the capability shortfall the gate computed when it
/// paused the call.
///
/// Read back at respond time and signed into the response as its
/// `covered_capabilities`. Absent or malformed decodes to empty: the grant
/// then covers nothing beyond the ordinary gate, the narrow direction.
#[must_use]
pub fn decode_request_missing_capabilities(payload: &[u8]) -> Vec<String> {
    serde_json::from_slice::<Value>(payload)
        .ok()
        .and_then(|v| {
            v.get("missing_capabilities")
                .and_then(Value::as_array)
                .map(|a| {
                    a.iter()
                        .filter_map(|c| c.as_str().map(str::to_owned))
                        .collect()
                })
        })
        .unwrap_or_default()
}

/// Extract the computed-preview enrichment (`#1496`) an `approval_request` carried.
///
/// Returns the raw (re-serialized) JSON — `None` for an absent or
/// explicit-`null` `preview` key (a call the enrichment doesn't apply to, or
/// a record written before this field existed). The caller (`polyc-control-
/// plane`) owns the typed shape; this layer stays opaque to it, exactly like
/// [`decode_request_fields`]'s `args_json`.
#[must_use]
pub fn decode_request_preview_json(payload: &[u8]) -> Option<String> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let preview = v.get("preview")?;
    if preview.is_null() {
        None
    } else {
        Some(preview.to_string())
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;

    // #784: an `ApprovalSigner` built from real key material (the shape a
    // secret-store load produces) signs a genuine, verifiable
    // `approval_response`, and a signature minted under the well-known
    // deterministic `from_seed(1)` key does NOT verify against it — proving
    // the loaded key is a distinct, non-derivable key, not the forgeable
    // default.
    #[test]
    fn loaded_key_signature_verifies_and_from_seed_signature_does_not() {
        // Stand-in for key bytes read back from a secret store (any 32 bytes
        // are a valid ed25519 private key — no seed-derivation involved).
        let key_bytes = [42u8; 32];
        let loaded = ApprovalSigner::from_key_bytes(&key_bytes).expect("valid key material");
        let forged = ApprovalSigner::from_seed(1);
        assert_ne!(
            loaded.public_key_bytes(),
            forged.public_key_bytes(),
            "a loaded key must not collide with the public, deterministic seed-1 key"
        );

        let (payload, _sig, _pk) = response_payload(
            "req-1",
            "web_fetch",
            r#"{"url":"https://a"}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "",
            "",
            "conv-1",
            "nonce-1",
            &loaded,
        );
        let verified = verify_signed_response(&payload).expect("verifies under the loaded key");
        assert_eq!(verified.signer_public_key, loaded.public_key_bytes());

        // The exact same payload, signed under `from_seed(1)` and stamped
        // with the LOADED key's public key (impersonation attempt), fails —
        // the seed-1 signature does not verify against the loaded key.
        let (forged_payload, _sig, _pk) = response_payload(
            "req-1",
            "web_fetch",
            r#"{"url":"https://a"}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "",
            "",
            "conv-1",
            "nonce-1",
            &forged,
        );
        let mut v: serde_json::Value = serde_json::from_slice(&forged_payload).unwrap();
        v["signed_by"] = serde_json::json!(crate::hex::lower(&loaded.public_key_bytes()));
        assert!(
            verify_signed_response(v.to_string().as_bytes()).is_none(),
            "a from_seed(1) signature must not verify against the loaded key"
        );
    }

    // #594: a grant_replay audit record round-trips through verification and any
    // tamper to a bound field flips verification to false.
    #[test]
    fn grant_replay_audit_is_signed_and_tamper_evident() {
        let signer = ApprovalSigner::from_seed(9);
        let covered = vec!["arbitrary-egress".to_owned()];
        let (payload, _sig, _pk) = grant_replay_payload(
            "conv-1",
            "turn-7",
            "post_summary",
            "deadbeef",
            &covered,
            "sha256:template-abc",
            &signer,
        );
        assert!(verify_grant_replay(&payload), "the genuine record verifies");
        // Tampering any bound field breaks the signature.
        for (field, val) in [
            ("conversation_id", serde_json::json!("conv-EVIL")),
            ("turn_id", serde_json::json!("turn-8")),
            ("tool", serde_json::json!("exfiltrate")),
            ("grant_ref", serde_json::json!("cafe")),
            (
                "covered_capabilities",
                serde_json::json!(["arbitrary-egress", "mutate-external"]),
            ),
            ("coverage_hash", serde_json::json!("sha256:other")),
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = val;
            assert!(
                !verify_grant_replay(v.to_string().as_bytes()),
                "tampered {field} must fail verification"
            );
        }
        assert!(!verify_grant_replay(b"not json"));
    }

    // #595: the covered capability set is part of the signed contract — it
    // round-trips through verification and cannot be widened after signing.
    #[test]
    fn covered_capabilities_are_signed_and_tamper_evident() {
        let signer = ApprovalSigner::from_seed(42);
        let covered = vec!["arbitrary-egress".to_owned()];
        let (payload, _sig, _pk) = response_payload(
            "req-1",
            "web_fetch",
            r#"{"url":"https://a"}"#,
            "",
            true,
            true,
            &covered,
            "slack:T1:U9",
            "",
            "workspace-write",
            "",
            "",
            "conv-1",
            "nonce-1",
            &signer,
        );
        let verified = verify_signed_response(&payload).expect("verifies untampered");
        assert_eq!(verified.covered_capabilities, covered);

        // Widening the covered set after signing invalidates the signature.
        let mut v: serde_json::Value = serde_json::from_slice(&payload).unwrap();
        v["covered_capabilities"] = serde_json::json!(["arbitrary-egress", "mutate-external"]);
        assert!(
            verify_signed_response(v.to_string().as_bytes()).is_none(),
            "a tampered covered set must fail verification"
        );
        // So does shrinking it to hide what a grant covered.
        let mut v: serde_json::Value = serde_json::from_slice(&payload).unwrap();
        v["covered_capabilities"] = serde_json::json!([]);
        assert!(verify_signed_response(v.to_string().as_bytes()).is_none());
    }

    // #595: the request records the gate's capability shortfall and decodes
    // it back for the respond path; absent decodes empty (covers nothing).
    #[test]
    fn request_missing_capabilities_round_trip() {
        let missing = vec!["arbitrary-egress".to_owned(), "mutate-external".to_owned()];
        let bytes = request_payload("call-1", "web_fetch", "{}", "", "", &missing, "");
        assert_eq!(decode_request_missing_capabilities(&bytes), missing);
        let bare = request_payload("call-2", "grep", "{}", "", "", &[], "");
        assert_eq!(
            decode_request_missing_capabilities(&bare),
            Vec::<String>::new()
        );
        assert_eq!(
            decode_request_missing_capabilities(b"{\"nope\":1}"),
            Vec::<String>::new()
        );
    }

    // #590: excision markers round-trip and are tamper-evident on every
    // covered field — widening positions, flipping scope, or re-targeting
    // the conversation all fail verification (taint stays, fail closed).
    #[test]
    fn signed_excision_round_trips_and_is_tamper_evident() {
        let signer = ApprovalSigner::from_seed(11);
        let (payload, _sig, _pk) = excision_payload(
            "conv-1",
            EXCISION_SCOPE_CASCADE,
            &[17, 23],
            "persona-9",
            "poisoned fetch",
            &signer,
        );
        let v = verify_signed_excision(&payload).expect("verifies untampered");
        assert_eq!(v.conversation_id, "conv-1");
        assert!(v.is_cascade());
        assert_eq!(v.positions, vec![17, 23]);
        assert_eq!(v.requested_by, "persona-9");

        for (field, value) in [
            ("positions", serde_json::json!([17, 23, 40])),
            ("scope", serde_json::json!(EXCISION_SCOPE_SOURCE_ONLY)),
            ("conversation_id", serde_json::json!("conv-2")),
            ("requested_by", serde_json::json!("someone-else")),
        ] {
            let mut t: serde_json::Value = serde_json::from_slice(&payload).unwrap();
            t[field] = value;
            assert!(
                verify_signed_excision(t.to_string().as_bytes()).is_none(),
                "tampered {field} must fail verification"
            );
        }
        // An unknown scope is refused even before the signature check.
        let mut t: serde_json::Value = serde_json::from_slice(&payload).unwrap();
        t["scope"] = serde_json::json!("everything");
        assert!(verify_signed_excision(t.to_string().as_bytes()).is_none());
        // Garbage is refused.
        assert!(verify_signed_excision(b"not json").is_none());
    }

    #[test]
    fn signed_response_round_trips() {
        let signer = ApprovalSigner::from_seed(42);
        // A one-shot approval: approved_for_session = false.
        let (payload, _sig, _pk) = response_payload(
            "req-1",
            "rm",
            r#"{"path":"/etc"}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "looks fine",
            "",
            "conv-1",
            "nonce-1",
            &signer,
        );
        let verified =
            verify_signed_response(&payload).expect("signature verifies on untampered payload");
        assert!(verified.approved);
        assert_eq!(verified.reason, "looks fine");
        assert_eq!(verified.request_id, "req-1");
        assert_eq!(verified.tool_name, "rm");
        assert_eq!(verified.args_json, r#"{"path":"/etc"}"#);
        assert_eq!(verified.caller, "slack:T1:U9");
        assert_eq!(verified.conversation_id, "conv-1");
        assert_eq!(verified.nonce, "nonce-1");
        assert!(verified.approved);
        // A one-shot approval carries no session scope.
        assert!(!verified.approved_for_session);
    }

    /// #1025 backward compatibility: a payload signed BEFORE the `approver`
    /// field existed (no `approver` key at all, not merely an empty one)
    /// must still decode and verify byte-for-byte identically — every
    /// `approval_response` ever persisted was signed this way, and they are
    /// re-verified on every replay.
    ///
    /// The pre-#1025 shape is a checked-in literal
    /// ([`PRE_APPROVER_RESPONSE_PAYLOAD`]). It used to be recomputed inline
    /// with a `json!` call, because `Value::to_string()`'s key order depended
    /// on `serde_json`'s `preserve_order` feature and so flipped with whatever
    /// else the build graph pulled in (`#345`) — which made a literal fixture
    /// unstable. `#1842` removed that dependence: the canonical is now a struct
    /// serialized in declaration order, identical under every build selection,
    /// so the literal is stable and pins the bytes a deployment actually has in
    /// its log instead of merely agreeing with the implementation.
    /// An `approval_response` persisted before `approver` existed (`#1025`),
    /// signed by `ApprovalSigner::from_seed(42)` over the thirteen fields that
    /// preceded it. Checked in, never regenerated.
    const PRE_APPROVER_RESPONSE_PAYLOAD: &str = r#"{"request_id":"req-1","tool_name":"tool.name","args_json":"{\"a\":1}","modified_args_json":"","approved":true,"approved_for_session":true,"covered_capabilities":["cap.a","cap.b"],"caller":"persona-caller","sandbox_mode":"sandboxed","reason":"looks fine","injected_context":"","conversation_id":"conv-1","nonce":"nonce-1","signed_by":"78eda21ba04a15e2000fe8810fe3e56741d23bb9ae44aa9d5bb21b76675ff34b","signature_hex":"59ffe281c9b866b703eb77ef8a1aff15d96aacf07a3529ae25afb11798317247b7e387343f4fc3e73dccb0b6d4cfac503ca1de8abcefae32fbdce7959f4d490f"}"#;

    #[test]
    fn pre_approver_field_payload_still_verifies_unchanged() {
        let signer = ApprovalSigner::from_seed(42);
        let (request_id, tool_name, args_json, modified_args_json) =
            ("req-1", "tool.name", r#"{"a":1}"#, "");
        let (approved, approved_for_session) = (true, true);
        let covered_capabilities = ["cap.a".to_owned(), "cap.b".to_owned()];
        let caller = "persona-caller";
        let sandbox_mode = "sandboxed";
        let reason = "looks fine";
        let injected_context = "";
        let conversation_id = "conv-1";
        let nonce = "nonce-1";

        // The exact pre-#1025 payload — the 13 fields `response_canonical` /
        // `response_payload` signed before `approver` existed — checked in as
        // literal bytes rather than recomputed here (`#1842`). It used to be
        // rebuilt with a `serde_json::json!` call so "both sides agree under
        // whatever key ordering is in effect for this build", which quietly
        // made the test agree with the implementation under either ordering
        // instead of pinning the one a deployment actually persisted. Signed by
        // `ApprovalSigner::from_seed(42)`; never regenerate it.
        let pre_approver_payload = PRE_APPROVER_RESPONSE_PAYLOAD.as_bytes();
        let expected_pk = signer.public_key_bytes();
        let expected_sig = crate::hex::decode(
            serde_json::from_slice::<Value>(pre_approver_payload)
                .expect("the frozen payload is valid JSON")["signature_hex"]
                .as_str()
                .expect("the frozen payload carries a signature"),
        )
        .expect("the frozen signature is valid hex");

        let verified = verify_signed_response(pre_approver_payload)
            .expect("a pre-#1025 payload must still verify");
        assert_eq!(verified.request_id, request_id);
        assert_eq!(verified.caller, caller);
        assert_eq!(
            verified.approver, "",
            "no approver field existed on this payload — decodes to empty, not an error"
        );

        // Re-signing the SAME inputs with today's code (empty approver) must
        // reproduce byte-identical output — the additive field is omitted
        // from the canonical entirely when empty, not merely defaulted.
        let (regenerated, sig, pk) = response_payload(
            request_id,
            tool_name,
            args_json,
            modified_args_json,
            approved,
            approved_for_session,
            &covered_capabilities,
            caller,
            "",
            sandbox_mode,
            reason,
            injected_context,
            conversation_id,
            nonce,
            &signer,
        );
        assert_eq!(
            regenerated, pre_approver_payload,
            "an empty approver must produce byte-identical canonical/payload to before #1025"
        );
        assert_eq!(
            sig, expected_sig,
            "an empty approver must sign byte-identically to before #1025"
        );
        assert_eq!(pk, expected_pk, "public key must be unchanged");
    }

    #[test]
    fn session_response_round_trips_with_caller_binding() {
        let signer = ApprovalSigner::from_seed(42);
        let (payload, _sig, _pk) = response_payload(
            "req-1",
            "grep",
            r#"{"pattern":"x"}"#,
            "",
            true,
            true,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "remember it",
            "",
            "conv-1",
            "nonce-1",
            &signer,
        );
        let verified = verify_signed_response(&payload).expect("session signature verifies");
        assert!(verified.approved);
        assert!(verified.approved_for_session, "carries session scope");
        assert_eq!(verified.caller, "slack:T1:U9");
        assert_eq!(verified.tool_name, "grep");
        assert!(verified.approved);
    }

    #[test]
    fn tampered_session_or_caller_fails_verification() {
        let signer = ApprovalSigner::from_seed(42);
        let (payload, _sig, _pk) = response_payload(
            "req-1",
            "grep",
            "{}",
            "",
            true,
            true,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "ok",
            "",
            "conv-1",
            "nonce-1",
            &signer,
        );
        // Every signed field is covered: re-scoping the memory to another user,
        // flipping the session flag, swapping the tool, re-targeting the
        // conversation, or re-rolling the nonce must all fail.
        for (field, val) in [
            ("caller", Value::String("slack:T1:ATTACKER".to_owned())),
            ("approved_for_session", Value::Bool(false)),
            ("tool_name", Value::String("rm".to_owned())),
            ("approved", Value::Bool(false)),
            ("args_json", Value::String("EVIL".to_owned())),
            // The approver's edit and injected context are signed too: forging
            // either — swapping in different execution args, or a different
            // injected instruction — must invalidate the signature.
            (
                "modified_args_json",
                Value::String(r#"{"path":"/EVIL"}"#.to_owned()),
            ),
            ("injected_context", Value::String("do EVIL".to_owned())),
            (
                "sandbox_mode",
                Value::String("danger-full-access".to_owned()),
            ),
            ("conversation_id", Value::String("conv-OTHER".to_owned())),
            ("nonce", Value::String("nonce-OTHER".to_owned())),
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = val;
            assert!(
                verify_signed_response(&v.to_string().into_bytes()).is_none(),
                "tampering with {field} must fail verification"
            );
        }
    }

    /// #67 gate A: an approver can approve with EDITED args. The signed response
    /// carries both the model's PROPOSED args (`args_json`, the identity binding)
    /// and the approver's EDIT (`modified_args_json`, what executes). Both are
    /// covered by the signature. Crucially, the identity binding
    /// ([`VerifiedResponse::authorizes_call`]) still matches the PROPOSED args —
    /// so a model that re-emits a different call on resume cannot inherit the
    /// approval — while the edit is a separate signed field the executor
    /// substitutes. The pure resolver (`polyc_agent::resolve_approved_call`) owns
    /// the "empty edit ⇒ run proposed" defaulting; here we only pin the crypto
    /// contract: both fields round-trip, and identity binds the proposed args.
    #[test]
    fn edited_response_binds_proposed_and_carries_modified() {
        let signer = ApprovalSigner::from_seed(7);
        let proposed = r#"{"path":"/etc/shadow"}"#;
        let edited = r#"{"path":"/etc/hostname"}"#;
        let (payload, _sig, _pk) = response_payload(
            "call-1",
            "read_file",
            proposed,
            edited,
            true,
            false,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "narrowed the path",
            "",
            "conv-1",
            "nonce-1",
            &signer,
        );
        let v = verify_signed_response(&payload).expect("edited approval verifies");
        assert_eq!(v.args_json, proposed, "identity binds the proposed args");
        assert_eq!(
            v.modified_args_json, edited,
            "the edit is carried and signed"
        );
        // Identity binding is against the PROPOSED args — this is what the model
        // must re-present on resume; the edit is not part of the identity.
        assert!(
            v.authorizes_call("call-1", "read_file", proposed),
            "the exact proposed call is authorized"
        );
        assert!(
            !v.authorizes_call("call-1", "read_file", edited),
            "the edited args are NOT the identity — authorizes_call binds proposed"
        );
    }

    /// #67 gate A: an unedited approval carries an empty `modified_args_json` and
    /// still authorizes exactly the proposed call — behaviourally identical to the
    /// pre-#67 approve path, so the common case is unchanged.
    #[test]
    fn unedited_response_carries_empty_edit() {
        let signer = ApprovalSigner::from_seed(7);
        let proposed = r#"{"path":"/tmp/x"}"#;
        let (payload, _sig, _pk) = response_payload(
            "call-1",
            "read_file",
            proposed,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "ok",
            "",
            "conv-1",
            "nonce-1",
            &signer,
        );
        let v = verify_signed_response(&payload).expect("verifies");
        assert!(v.modified_args_json.is_empty(), "no edit ⇒ empty");
        assert!(v.injected_context.is_empty(), "no injected context ⇒ empty");
        assert!(v.authorizes_call("call-1", "read_file", proposed));
    }

    /// #67 gate A: an approver can attach context to inject before the tool runs.
    /// The injected context is a signed field that round-trips.
    #[test]
    fn injected_context_round_trips_and_is_signed() {
        let signer = ApprovalSigner::from_seed(7);
        let (payload, _sig, _pk) = response_payload(
            "call-1",
            "shell",
            r#"{"cmd":"ls"}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "ok",
            "only touch files under src/",
            "conv-1",
            "nonce-1",
            &signer,
        );
        let v = verify_signed_response(&payload).expect("verifies");
        assert_eq!(v.injected_context, "only touch files under src/");
    }

    /// #67 (#539/#540): a dispatch-mutation record round-trips and verifies;
    /// tampering with any covered field — including the kind — fails.
    #[test]
    fn mutation_round_trips_and_tamper_fails() {
        let signer = ApprovalSigner::from_seed(7);
        let (payload, _s, _p) = mutation_payload(
            "tool_input_rewrite",
            "call-1",
            "shell",
            "conv-1",
            r#"{"cmd":"rm -rf /"}"#,
            r#"{"cmd":"rm /tmp/x"}"#,
            &signer,
        );
        assert_eq!(
            verify_mutation(&payload).map(|t| (t.0, t.4, t.5)),
            Some((
                "tool_input_rewrite".to_owned(),
                r#"{"cmd":"rm -rf /"}"#.to_owned(),
                r#"{"cmd":"rm /tmp/x"}"#.to_owned()
            ))
        );
        for field in [
            "kind",
            "tool_call_id",
            "tool_name",
            "conversation_id",
            "before",
            "after",
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = Value::String("EVIL".to_owned());
            assert!(
                verify_mutation(&v.to_string().into_bytes()).is_none(),
                "tampering with {field} must fail"
            );
        }
    }

    /// #67 (#538): a deferred "send back" round-trips and verifies; tampering
    /// with any covered field fails.
    #[test]
    fn deferred_round_trips_and_tamper_fails() {
        let signer = ApprovalSigner::from_seed(7);
        let (payload, _sig, _pk) = deferred_payload("call-1", "conv-1", "need more info", &signer);
        assert_eq!(
            verify_deferred(&payload),
            Some((
                "call-1".to_owned(),
                "conv-1".to_owned(),
                "need more info".to_owned()
            ))
        );
        for field in ["request_id", "conversation_id", "reason"] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = Value::String("EVIL".to_owned());
            assert!(
                verify_deferred(&v.to_string().into_bytes()).is_none(),
                "tampering with {field} must fail"
            );
        }
    }

    #[test]
    fn wire_verification_round_trips_and_binds_session_and_caller() {
        let signer = ApprovalSigner::from_seed(7);
        let (payload, _sig, _pk) = response_payload(
            "req-x",
            "grep",
            r#"{"p":"x"}"#,
            "",
            true,
            true,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "go",
            "",
            "conv-7",
            "nonce-7",
            &signer,
        );
        let d = decode_response_full(&payload).expect("decoded payload");
        // decode_response_full surfaces every signed field.
        assert!(d.approved_for_session);
        assert_eq!(d.caller, "slack:T1:U9");
        assert_eq!(d.sandbox_mode, "workspace-write");
        assert_eq!(d.conversation_id, "conv-7");
        assert_eq!(d.nonce, "nonce-7");
        assert!(verify_wire_response(
            &d.request_id,
            &d.tool_name,
            &d.args_json,
            "",
            d.approved,
            d.approved_for_session,
            &[],
            &d.caller,
            &d.approver,
            &d.sandbox_mode,
            &d.reason,
            "",
            &d.conversation_id,
            &d.nonce,
            &d.signer_pk_hex,
            &d.signature_hex
        ));
        // Re-scoping the remembered grant to a different caller over the wire
        // must fail — the caller is covered by the signature.
        assert!(!verify_wire_response(
            &d.request_id,
            &d.tool_name,
            &d.args_json,
            "",
            d.approved,
            d.approved_for_session,
            &[],
            "slack:T1:ATTACKER",
            &d.approver,
            &d.sandbox_mode,
            &d.reason,
            "",
            &d.conversation_id,
            &d.nonce,
            &d.signer_pk_hex,
            &d.signature_hex
        ));
        // Tampering with the bound args over the wire invalidates the sig.
        assert!(!verify_wire_response(
            &d.request_id,
            &d.tool_name,
            r#"{"p":"EVIL"}"#,
            "",
            d.approved,
            d.approved_for_session,
            &[],
            &d.caller,
            &d.approver,
            &d.sandbox_mode,
            &d.reason,
            "",
            &d.conversation_id,
            &d.nonce,
            &d.signer_pk_hex,
            &d.signature_hex
        ));
        // Replaying the token into a DIFFERENT conversation over the wire must
        // fail — `conversation_id` is covered by the signature (#370, #77 3B).
        assert!(!verify_wire_response(
            &d.request_id,
            &d.tool_name,
            &d.args_json,
            "",
            d.approved,
            d.approved_for_session,
            &[],
            &d.caller,
            &d.approver,
            &d.sandbox_mode,
            &d.reason,
            "",
            "conv-OTHER",
            &d.nonce,
            &d.signer_pk_hex,
            &d.signature_hex
        ));
    }

    /// #1025: `approver` is a distinct fact from `caller`, recoverable from a
    /// signed response and covered by the signature — the same-person and
    /// different-person (admin-approves-for-someone-else) cases both round-trip
    /// correctly, and the two identities are never conflated.
    #[test]
    fn approver_is_recoverable_and_distinct_from_caller() {
        let signer = ApprovalSigner::from_seed(3);

        // Same-person: the caller approving their own paused turn signs an
        // approver equal to caller. Distinguishable by field, still equal by
        // value — this is the common case, not a degenerate one.
        let (self_approved, ..) = response_payload(
            "req-1",
            "grep",
            r#"{"q":"x"}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "slack:T1:U9",
            "workspace-write",
            "self-approved",
            "",
            "conv-1",
            "nonce-1",
            &signer,
        );
        let self_decoded = decode_response_full(&self_approved).expect("decodes");
        assert_eq!(self_decoded.caller, "slack:T1:U9");
        assert_eq!(self_decoded.approver, "slack:T1:U9");
        let self_verified = verify_signed_response(&self_approved).expect("verifies");
        assert_eq!(self_verified.caller, self_verified.approver);

        // Different-person: an admin approves on behalf of the turn's own
        // beneficiary. `caller` stays the beneficiary (principal_ref's own
        // resume-attribution source, per the sibling #1024 fix); `approver` is
        // the admin — a genuinely different persona, both recoverable and
        // distinguishable from the same signed record.
        let (admin_approved, ..) = response_payload(
            "req-2",
            "rm",
            r#"{"path":"/tmp/x"}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:BENEFICIARY",
            "slack:T1:ADMIN",
            "workspace-write",
            "approved on your behalf",
            "",
            "conv-2",
            "nonce-2",
            &signer,
        );
        let admin_decoded = decode_response_full(&admin_approved).expect("decodes");
        assert_eq!(admin_decoded.caller, "slack:T1:BENEFICIARY");
        assert_eq!(admin_decoded.approver, "slack:T1:ADMIN");
        assert_ne!(
            admin_decoded.caller, admin_decoded.approver,
            "admin-approves-for-someone-else must decode two DISTINCT identities"
        );
        let admin_verified = verify_signed_response(&admin_approved).expect("verifies");
        assert_eq!(admin_verified.caller, "slack:T1:BENEFICIARY");
        assert_eq!(admin_verified.approver, "slack:T1:ADMIN");

        // Tampering with the signed approver (re-scoping the policy/audit fact
        // to a different identity post-signing) invalidates the signature —
        // it is covered exactly like `caller`.
        let mut v: serde_json::Value = serde_json::from_slice(&admin_approved).unwrap();
        v["approver"] = serde_json::json!("slack:T1:ATTACKER");
        assert!(
            verify_signed_response(v.to_string().as_bytes()).is_none(),
            "a tampered approver must fail verification"
        );
    }

    /// `#377` core invariant: a reviewer auto-approval signs a payload that is
    /// BYTE-IDENTICAL to the one a human signs for the same decision, yet is
    /// distinguishable in the audit log by its signed `reason`.
    ///
    /// There is a single signing function ([`response_payload`]); the reviewer
    /// path is just that function with `approved == true`,
    /// `approved_for_session == false`, and an auto-review `reason`. We pin two
    /// properties:
    ///   1. With every argument INCLUDING the reason held equal, the auto and
    ///      human calls produce identical bytes + signature — proving the auto
    ///      path adds no hidden field and shares the human signing contract
    ///      exactly (guards against a future forked auto-signer).
    ///   2. With the auto-review reason, the response still verifies, still
    ///      carries `approved && !approved_for_session`, and is flagged by
    ///      [`is_auto_review_reason`] while a human reason is not — so the event
    ///      log can tell machine from human consent off the signed field alone.
    ///   3. Substitution resistance: flipping ANY one bound field — the tool, the
    ///      args, the beneficiary caller, or the request id — changes both the
    ///      canonical bytes AND the signature, so a forged or substituted
    ///      approval (signed for one call, replayed to authorize another) cannot
    ///      match. Without this, (1)'s byte-identical property would be vacuous.
    #[test]
    fn auto_review_signs_byte_identical_canonical_and_is_distinguishable() {
        let signer = ApprovalSigner::from_seed(7);
        let (rid, tool, args, caller, mode, conv, nonce) = (
            "req-9",
            "file_read",
            r#"{"path":"a.txt"}"#,
            "slack:T1:U9",
            "read-only",
            "conv-9",
            "nonce-9",
        );

        // (1) Same decision + same reason via the one signing path ⇒ identical
        // bytes regardless of which side "produced" it. The reviewer is not a
        // separate signer; it cannot diverge structurally from the human path.
        let shared_reason = auto_review_reason("low");
        let human_like = response_payload(
            rid,
            tool,
            args,
            "",
            true,
            false,
            &[],
            caller,
            "",
            mode,
            &shared_reason,
            "",
            conv,
            nonce,
            &signer,
        );
        let reviewer = response_payload(
            rid,
            tool,
            args,
            "",
            true,
            false,
            &[],
            caller,
            "",
            mode,
            &shared_reason,
            "",
            conv,
            nonce,
            &signer,
        );
        assert_eq!(human_like.0, reviewer.0, "auto path must be byte-identical");
        assert_eq!(human_like.1, reviewer.1, "signature must be identical");

        // (2) The auto-review response verifies and is an approve-once decision.
        let verified = verify_signed_response(&reviewer.0).expect("auto-review verifies");
        assert!(verified.approved);
        assert!(
            !verified.approved_for_session,
            "a machine decision is never remembered per-caller"
        );
        assert!(
            is_auto_review_reason(&verified.reason),
            "the signed reason marks this as an auto-approval"
        );

        // A genuine human approval over the same call is NOT flagged as auto —
        // the distinguisher reads the signed reason, so it is unforgeable.
        let (human_payload, _s, _p) = response_payload(
            rid,
            tool,
            args,
            "",
            true,
            false,
            &[],
            caller,
            "",
            mode,
            "looks fine",
            "",
            conv,
            nonce,
            &signer,
        );
        let human = verify_signed_response(&human_payload).expect("human verifies");
        assert!(!is_auto_review_reason(&human.reason));

        // The two payloads differ ONLY in the reason field — every bound
        // identity / decision / scope field is byte-equal, which is what makes
        // the auto path indistinguishable from a human one except by reason.
        let a: Value = serde_json::from_slice(&reviewer.0).unwrap();
        let h: Value = serde_json::from_slice(&human_payload).unwrap();
        for field in [
            "request_id",
            "tool_name",
            "args_json",
            "modified_args_json",
            "approved",
            "approved_for_session",
            "caller",
            "sandbox_mode",
            "injected_context",
            "conversation_id",
            "nonce",
        ] {
            assert_eq!(a[field], h[field], "{field} must match the human payload");
        }
        assert_ne!(a["reason"], h["reason"], "reason is the sole distinguisher");

        // (3) Substitution resistance: each variant holds every input equal to
        // `reviewer` and flips exactly ONE bound field. A different tool / args /
        // caller / request_id / conversation / nonce must change BOTH the
        // canonical bytes and the signature — so an approval signed for
        // `(req-9, file_read, a.txt, U9, conv-9, nonce-9)` can never be replayed to
        // authorize a write, a different path, a different beneficiary, a
        // different CONVERSATION (#370, #77 3B), or re-presented under a new nonce.
        // This is what makes (1)'s "byte-identical for identical inputs" a
        // security property and not just determinism.
        let base = &reviewer.0;
        let base_sig = &reviewer.1;
        for (label, variant) in [
            (
                "tool",
                response_payload(
                    rid,
                    "file_write",
                    args,
                    "",
                    true,
                    false,
                    &[],
                    caller,
                    "",
                    mode,
                    &shared_reason,
                    "",
                    conv,
                    nonce,
                    &signer,
                ),
            ),
            (
                "args",
                response_payload(
                    rid,
                    tool,
                    r#"{"path":"b.txt"}"#,
                    "",
                    true,
                    false,
                    &[],
                    caller,
                    "",
                    mode,
                    &shared_reason,
                    "",
                    conv,
                    nonce,
                    &signer,
                ),
            ),
            (
                "caller",
                response_payload(
                    rid,
                    tool,
                    args,
                    "",
                    true,
                    false,
                    &[],
                    "slack:T1:UEVIL",
                    "",
                    mode,
                    &shared_reason,
                    "",
                    conv,
                    nonce,
                    &signer,
                ),
            ),
            (
                "request_id",
                response_payload(
                    "req-OTHER",
                    tool,
                    args,
                    "",
                    true,
                    false,
                    &[],
                    caller,
                    "",
                    mode,
                    &shared_reason,
                    "",
                    conv,
                    nonce,
                    &signer,
                ),
            ),
            (
                "conversation_id",
                response_payload(
                    rid,
                    tool,
                    args,
                    "",
                    true,
                    false,
                    &[],
                    caller,
                    "",
                    mode,
                    &shared_reason,
                    "",
                    "conv-OTHER",
                    nonce,
                    &signer,
                ),
            ),
            (
                "nonce",
                response_payload(
                    rid,
                    tool,
                    args,
                    "",
                    true,
                    false,
                    &[],
                    caller,
                    "",
                    mode,
                    &shared_reason,
                    "",
                    conv,
                    "nonce-OTHER",
                    &signer,
                ),
            ),
        ] {
            assert_ne!(
                &variant.0, base,
                "{label}: a different {label} must change the canonical bytes"
            );
            assert_ne!(
                &variant.1, base_sig,
                "{label}: a different {label} must change the signature"
            );
        }
    }

    /// `#370` (a): a capability token signed for one conversation is REJECTED
    /// when presented for another. The `conversation_id` is covered by the
    /// signature, so it cannot be re-targeted without invalidating it; the
    /// consume gate ([`verify_capability`]) refuses any token whose signed
    /// conversation does not match the one it is being consumed in. Closes `#77`
    /// bug 3B (one signed response valid across conversations sharing a
    /// `request_id`).
    #[test]
    fn capability_rejected_across_conversations() {
        let signer = ApprovalSigner::from_seed(11);
        let (payload, _sig, _pk) = response_payload(
            "call-0",
            "delete_file",
            r#"{"path":"/etc/hosts"}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "ok",
            "",
            "conv-A",
            "nonce-A",
            &signer,
        );
        let consumed = HashSet::new();
        // Same conversation, fresh nonce ⇒ honored.
        assert!(
            verify_capability(&payload, "conv-A", &consumed, &[signer.public_key_bytes()])
                .is_some(),
            "a token must verify in the conversation it was signed for"
        );
        // Different conversation ⇒ rejected, even though request_id/tool/args
        // are byte-identical (the #77 3B replay).
        assert!(
            verify_capability(&payload, "conv-B", &consumed, &[signer.public_key_bytes()])
                .is_none(),
            "a token signed for conv-A must be rejected when consumed in conv-B"
        );
    }

    /// `#370` (b): a single-use token is REJECTED on a second presentation. The
    /// consumer records the token's `nonce` after honoring it; a re-presentation
    /// of the SAME signed bytes (a captured/replayed token) is then refused.
    #[test]
    fn capability_is_single_use() {
        let signer = ApprovalSigner::from_seed(11);
        let (payload, _sig, _pk) = response_payload(
            "call-0",
            "delete_file",
            r#"{"path":"/etc/hosts"}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "ok",
            "",
            "conv-A",
            "nonce-A",
            &signer,
        );
        let mut consumed = HashSet::new();
        // First presentation is honored and yields the bound nonce.
        let v = verify_capability(&payload, "conv-A", &consumed, &[signer.public_key_bytes()])
            .expect("first use honored");
        assert_eq!(v.nonce, "nonce-A");
        consumed.insert(v.nonce.clone());
        // Second presentation of the same token is rejected — single-use.
        assert!(
            verify_capability(&payload, "conv-A", &consumed, &[signer.public_key_bytes()])
                .is_none(),
            "a spent token must be rejected on re-presentation"
        );
    }

    /// `#370` (c)/(d): the token is ARGS-BOUND. A verified, approved token
    /// authorizes ONLY the exact `(request_id, tool_name, args_json)` it was
    /// signed for; a call with different args (a captured approval reused with a
    /// new payload) is NOT authorized, while the matching call IS.
    #[test]
    fn capability_authorizes_only_matching_args() {
        let signer = ApprovalSigner::from_seed(11);
        let (payload, _sig, _pk) = response_payload(
            "call-0",
            "delete_file",
            r#"{"path":"/tmp/scratch"}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "ok",
            "",
            "conv-A",
            "nonce-A",
            &signer,
        );
        let consumed = HashSet::new();
        let v = verify_capability(&payload, "conv-A", &consumed, &[signer.public_key_bytes()])
            .expect("verifies in conv-A");
        // (c) different args ⇒ NOT authorized.
        assert!(
            !v.authorizes_call("call-0", "delete_file", r#"{"path":"/etc/hosts"}"#),
            "a token must not authorize a call with different args"
        );
        // …nor a different tool with the same id.
        assert!(
            !v.authorizes_call("call-0", "shell", r#"{"path":"/tmp/scratch"}"#),
            "a token must not authorize a different tool"
        );
        // (d) the exact signed call ⇒ authorized (happy path).
        assert!(
            v.authorizes_call("call-0", "delete_file", r#"{"path":"/tmp/scratch"}"#),
            "the exact signed call must be authorized"
        );
    }

    /// A denial never authorizes a call, regardless of identity match.
    #[test]
    fn denied_capability_authorizes_nothing() {
        let signer = ApprovalSigner::from_seed(11);
        let (payload, _sig, _pk) = response_payload(
            "call-0",
            "delete_file",
            "{}",
            "",
            false,
            false,
            &[],
            "slack:T1:U9",
            "",
            "workspace-write",
            "deny",
            "",
            "conv-A",
            "nonce-A",
            &signer,
        );
        let consumed = HashSet::new();
        let v = verify_capability(&payload, "conv-A", &consumed, &[signer.public_key_bytes()])
            .expect("verifies");
        assert!(!v.approved);
        assert!(
            !v.authorizes_call("call-0", "delete_file", "{}"),
            "a denied token authorizes nothing even on an exact identity match"
        );
    }

    #[test]
    fn request_payload_round_trips_id() {
        let bytes = request_payload(
            "call-7",
            "rm",
            r#"{"path":"/etc"}"#,
            "workspace-write",
            "",
            &[],
            "",
        );
        assert_eq!(decode_request_id(&bytes).as_deref(), Some("call-7"));
        // An ordinary gated call carries no override reason.
        assert_eq!(decode_request_reason(&bytes), "");
    }

    #[test]
    fn request_payload_carries_override_reason() {
        // The lethal-trifecta override reason rides the durable approval_request
        // so the signed log records WHY a trifecta-gated call was paused.
        let reason = "lethal-trifecta / Rule-of-Two: untrusted content is in context";
        let bytes = request_payload(
            "call-9",
            "web_fetch",
            r#"{"url":"https://x"}"#,
            "",
            reason,
            &[],
            "",
        );
        assert_eq!(decode_request_reason(&bytes), reason);
        // The existing scalar fields still decode unchanged.
        assert_eq!(decode_request_id(&bytes).as_deref(), Some("call-9"));
        assert_eq!(
            decode_request_fields(&bytes),
            Some((
                "call-9".to_owned(),
                "web_fetch".to_owned(),
                r#"{"url":"https://x"}"#.to_owned()
            ))
        );
    }

    // #1496: the computed-preview enrichment round-trips through the durable
    // `approval_request` payload, so `ListPending` recovery can re-render the
    // same preview a lost-stream card showed.
    #[test]
    fn request_preview_json_round_trips() {
        let preview =
            r#"{"prompt_text":"hi","next_fires":[],"zone_name":"UTC","zone_is_fallback":true}"#;
        let bytes = request_payload("call-10", "routine_create", "{}", "", "", &[], preview);
        let decoded = decode_request_preview_json(&bytes).expect("preview present");
        // Compare parsed values, not raw bytes: `preview_json` is re-serialized
        // through `serde_json::Value`, which is free to reorder keys.
        let expected: Value = serde_json::from_str(preview).unwrap();
        let actual: Value = serde_json::from_str(&decoded).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn request_preview_json_is_absent_when_empty_or_missing() {
        let bytes = request_payload("call-11", "grep", "{}", "", "", &[], "");
        assert_eq!(decode_request_preview_json(&bytes), None);
        assert_eq!(decode_request_preview_json(b"{\"nope\":1}"), None);
    }

    /// Golden test: `receipt_payload` must produce the EXACT **v3** signed-payload
    /// bytes — `version` + the six settlement facts + the four binding fields +
    /// the two payer-attribution fields, in that order — plus the two uncovered
    /// signature fields. We recompute the expected canonical+full JSON inline
    /// and assert the struct form is byte-identical, pinning the v3 key set,
    /// order, and signature so a future edit cannot silently reorder, rename,
    /// or swap a covered field. The expectation is a literal string: the key
    /// order is part of what this test pins, and `#1842` made it stable to
    /// pin. It used to be recomputed with a `json!` call, because `serde_json`
    /// feature unification (`preserve_order`) flipped key order per build
    /// selection — but a recomputed expectation agrees with the implementation
    /// under either ordering, which pins the field set and nothing else.
    ///
    /// The `version` below is the frozen literal `3`, not `RECEIPT_VERSION`:
    /// this test pins what the *writer* emits, and mirroring the constant would
    /// leave it passing while silently pinning v4. A bump re-freezes it against
    /// the new version — the already-signed v2 bytes are preserved by
    /// `frozen_v2_receipts_survive_a_later_version_bump`.
    #[test]
    fn receipt_payload_pins_v3_canonical_shape() {
        let signer = ApprovalSigner::from_seed(99);
        let (reference, amount, currency, recipient, method, timestamp) = (
            "tx-abc",
            "0.01",
            "USDC",
            "0xrecipient",
            "tempo",
            "2026-06-02T00:00:00Z",
        );
        let (kind, tool_call_id, approval_pos, approved_args_hash, subject) = (
            "outbound_payment_receipt",
            "call-1",
            "42",
            "abcd1234",
            "conv-xyz",
        );
        let (payer_kind, paying_account) = ("linked_wallet", "0xpayer");

        // The exact v3 JSON the implementation must build, written out here as
        // a literal. `3` is a frozen literal, not `RECEIPT_VERSION`: mirroring
        // the constant would let this test keep passing while pinning v4 the
        // day the constant moved, which is exactly the drift it exists to
        // catch. The key ORDER is likewise pinned by this string rather than
        // recomputed with a `json!` call (`#1842`) — a recomputed expectation
        // agrees with the implementation under whatever ordering the build
        // resolves, which is the opposite of pinning anything.
        let expected_canonical = r#"{"version":3,"kind":"outbound_payment_receipt","reference":"tx-abc","amount":"0.01","currency":"USDC","recipient":"0xrecipient","method":"tempo","timestamp":"2026-06-02T00:00:00Z","tool_call_id":"call-1","approval_pos":"42","approved_args_hash":"abcd1234","subject":"conv-xyz","payer_kind":"linked_wallet","paying_account":"0xpayer"}"#;
        let expected_sig = signer.sign(expected_canonical.as_bytes());
        let expected_pk = signer.public_key_bytes();
        let expected_full = format!(
            r#"{{{expected_body},"signed_by":"{pk}","signature_hex":"{sig}"}}"#,
            expected_body = expected_canonical
                .trim_start_matches('{')
                .trim_end_matches('}'),
            pk = crate::hex::lower(&expected_pk),
            sig = crate::hex::lower(&expected_sig),
        );

        let (payload, sig, pk) = receipt_payload(
            &ReceiptPayload {
                kind,
                reference,
                amount,
                currency,
                recipient,
                method,
                timestamp,
                tool_call_id,
                approval_pos,
                approved_args_hash,
                subject,
                payer_kind,
                paying_account,
            },
            &signer,
        );

        assert_eq!(
            String::from_utf8(payload).unwrap(),
            expected_full,
            "v3 receipt payload must be byte-identical to the pinned v3 shape"
        );
        assert_eq!(
            sig, expected_sig,
            "signature must match the pinned v3 shape"
        );
        assert_eq!(pk, expected_pk, "public key must be unchanged");
    }

    /// Single-source guard: both the signing path (`receipt_payload`) and the
    /// verifying path (`verify_signed_receipt`) MUST derive their canonical
    /// signed JSON from the one [`ReceiptPayload::canonical_json_v3`] builder,
    /// so the signed field set/order cannot drift between sign and verify.
    ///
    /// We assert the canonical bytes the signer commits to are exactly the
    /// bytes `canonical_json_v3` produces for the same fields, and that a receipt
    /// reconstructed from `VerifiedReceipt` (the verify path's owned form)
    /// yields the identical canonical bytes. If a future edit added a field to
    /// one json! block but not the other, those bytes would differ and this
    /// (plus the round-trip) would fail.
    #[test]
    fn receipt_sign_and_verify_share_one_canonical_source() {
        let signer = ApprovalSigner::from_seed(99);
        let trusted = vec![signer.public_key_bytes()];
        let fields = ReceiptPayload {
            kind: "outbound_payment_receipt",
            reference: "tx-abc",
            amount: "0.01",
            currency: "USDC",
            recipient: "0xrecipient",
            method: "tempo",
            timestamp: "2026-06-02T00:00:00Z",
            tool_call_id: "call-1",
            approval_pos: "42",
            approved_args_hash: "abcd1234",
            subject: "conv-xyz",
            payer_kind: "linked_wallet",
            paying_account: "0xpayer",
        };

        // The signed bytes the producer commits to.
        let signed_bytes = canonical_bytes(&fields.canonical_json_v3());
        let expected_sig = signer.sign(&signed_bytes);
        let (_payload, sig, _pk) = receipt_payload(&fields, &signer);
        assert_eq!(
            sig, expected_sig,
            "receipt_payload must sign exactly ReceiptPayload::canonical_json_v3"
        );

        // The verify path reconstructs the same canonical bytes from its owned
        // form before checking the signature.
        let (payload, _sig, _pk) = receipt_payload(&fields, &signer);
        let verified = verify_signed_receipt(&payload, &trusted).expect("verifies");
        let verified_fields = ReceiptPayload {
            kind: &verified.kind,
            reference: &verified.reference,
            amount: &verified.amount,
            currency: &verified.currency,
            recipient: &verified.recipient,
            method: &verified.method,
            timestamp: &verified.timestamp,
            tool_call_id: &verified.tool_call_id,
            approval_pos: &verified.approval_pos,
            approved_args_hash: &verified.approved_args_hash,
            subject: &verified.subject,
            payer_kind: &verified.payer_kind,
            paying_account: &verified.paying_account,
        };
        let verified_canonical = canonical_bytes(&verified_fields.canonical_json_v3());
        assert_eq!(
            verified_canonical, signed_bytes,
            "verify path must derive canonical JSON from the same single source"
        );
    }

    #[test]
    fn crypto_receipt_payload_signs_and_verifies() {
        let signer = ApprovalSigner::from_seed(99);
        let trusted = vec![signer.public_key_bytes()];
        let (payload, _sig, _pk) = receipt_payload(
            &ReceiptPayload {
                kind: "outbound_payment_receipt",
                reference: "tx-abc",
                amount: "0.01",
                currency: "USDC",
                recipient: "0xrecipient",
                method: "tempo",
                timestamp: "2026-06-02T00:00:00Z",
                tool_call_id: "call-1",
                approval_pos: "42",
                approved_args_hash: "abcd1234",
                subject: "conv-xyz",
                payer_kind: "linked_wallet",
                paying_account: "0xpayer",
            },
            &signer,
        );
        let verified = verify_signed_receipt(&payload, &trusted)
            .expect("signature verifies on untampered receipt");
        assert_eq!(verified.reference, "tx-abc");
        assert_eq!(verified.amount, "0.01");
        assert_eq!(verified.currency, "USDC");
        assert_eq!(verified.recipient, "0xrecipient");
        assert_eq!(verified.method, "tempo");
        assert_eq!(verified.timestamp, "2026-06-02T00:00:00Z");
        // The v2 kind + binding tuple + opaque subject round-trip and are
        // covered by the signature.
        assert_eq!(verified.version, RECEIPT_VERSION);
        assert_eq!(verified.kind, "outbound_payment_receipt");
        assert_eq!(verified.tool_call_id, "call-1");
        assert_eq!(verified.approval_pos, "42");
        assert_eq!(verified.approved_args_hash, "abcd1234");
        assert_eq!(verified.subject, "conv-xyz");
        // The v3 payer attribution round-trips too.
        assert_eq!(verified.payer_kind, "linked_wallet");
        assert_eq!(verified.paying_account, "0xpayer");
    }

    #[test]
    fn tampered_receipt_fails_verification() {
        let signer = ApprovalSigner::from_seed(99);
        let trusted = vec![signer.public_key_bytes()];
        let (payload, _sig, _pk) = receipt_payload(
            &ReceiptPayload {
                kind: "outbound_payment_receipt",
                reference: "tx-abc",
                amount: "0.01",
                currency: "USDC",
                recipient: "0xrecipient",
                method: "tempo",
                timestamp: "2026-06-02T00:00:00Z",
                tool_call_id: "call-1",
                approval_pos: "42",
                approved_args_hash: "abcd1234",
                subject: "conv-xyz",
                payer_kind: "linked_wallet",
                paying_account: "0xpayer",
            },
            &signer,
        );
        // Tamper with a covered field (amount).
        let mut v: Value = serde_json::from_slice(&payload).unwrap();
        v["amount"] = Value::String("9999.00".to_owned());
        let tampered = v.to_string().into_bytes();
        assert!(verify_signed_receipt(&tampered, &trusted).is_none());
    }

    #[test]
    fn tampered_receipt_binding_field_fails_verification() {
        let signer = ApprovalSigner::from_seed(99);
        let trusted = vec![signer.public_key_bytes()];
        let (payload, _sig, _pk) = receipt_payload(
            &ReceiptPayload {
                kind: "outbound_payment_receipt",
                reference: "tx-abc",
                amount: "0.01",
                currency: "USDC",
                recipient: "0xrecipient",
                method: "tempo",
                timestamp: "2026-06-02T00:00:00Z",
                tool_call_id: "call-1",
                approval_pos: "42",
                approved_args_hash: "abcd1234",
                subject: "conv-xyz",
                payer_kind: "linked_wallet",
                paying_account: "0xpayer",
            },
            &signer,
        );
        // Re-pointing the receipt at a different approval position invalidates
        // the signature — the binding tuple is covered, not advisory.
        let mut v: Value = serde_json::from_slice(&payload).unwrap();
        v["approval_pos"] = Value::String("7".to_owned());
        let tampered = v.to_string().into_bytes();
        assert!(verify_signed_receipt(&tampered, &trusted).is_none());

        // Re-filing the payload under the other direction's kind likewise
        // fails — the signed `kind` is what makes direction trustworthy
        // independent of the (unsigned) stored event kind.
        let mut v: Value = serde_json::from_slice(&payload).unwrap();
        v["kind"] = Value::String("payment_receipt".to_owned());
        let refiled = v.to_string().into_bytes();
        assert!(verify_signed_receipt(&refiled, &trusted).is_none());

        // Re-attributing the payer likewise fails — payer attribution is
        // covered, not advisory: an attacker cannot rewrite "the deployment
        // paid" into "the linked wallet paid" (or vice versa) on an
        // already-signed receipt.
        let mut v: Value = serde_json::from_slice(&payload).unwrap();
        v["payer_kind"] = Value::String("deployment".to_owned());
        let repayered = v.to_string().into_bytes();
        assert!(verify_signed_receipt(&repayered, &trusted).is_none());
    }

    /// The acceptance gate (issue #806): a receipt signed by a key that is
    /// NOT on the trusted-signer allow-list must fail verification, even
    /// though its signature is perfectly self-consistent — proving the
    /// allow-list, not mere signature validity, gates trust. The SAME
    /// receipt verifies once its signer is added to the allow-list.
    #[test]
    fn receipt_from_non_allowlisted_signer_is_rejected() {
        let trusted_signer = ApprovalSigner::from_seed(99);
        let attacker_signer = ApprovalSigner::from_seed(31337);
        let fields = ReceiptPayload {
            kind: "outbound_payment_receipt",
            reference: "tx-forged",
            amount: "100.00",
            currency: "USDC",
            recipient: "0xattacker",
            method: "tempo",
            timestamp: "2026-06-02T00:00:00Z",
            tool_call_id: "call-1",
            approval_pos: "42",
            approved_args_hash: "abcd1234",
            subject: "conv-xyz",
            payer_kind: "linked_wallet",
            paying_account: "0xpayer",
        };
        // The attacker signs a fully self-consistent receipt with THEIR OWN
        // key (not a forged signature over the trusted signer's key).
        let (payload, _sig, _pk) = receipt_payload(&fields, &attacker_signer);

        // An allow-list that does not include the attacker's key rejects it,
        // no matter how internally consistent the signature is.
        let trusted = vec![trusted_signer.public_key_bytes()];
        assert!(
            verify_signed_receipt(&payload, &trusted).is_none(),
            "a receipt signed by a non-allow-listed key must not verify"
        );

        // The IDENTICAL payload verifies once the attacker's key is
        // allow-listed (proves the rejection above was the allow-list, not
        // some other defect).
        let trusted_plus_attacker = vec![
            trusted_signer.public_key_bytes(),
            attacker_signer.public_key_bytes(),
        ];
        assert!(
            verify_signed_receipt(&payload, &trusted_plus_attacker).is_some(),
            "the same receipt must verify once its signer is allow-listed"
        );

        // An empty allow-list rejects every signer, including the deployment's
        // own — fail closed, never fail open on a misconfigured (empty) list.
        assert!(verify_signed_receipt(&payload, &[]).is_none());
    }

    /// The acceptance gate (issue #845): a `grant_replay` audit record signed by
    /// a key that is NOT on the trusted-signer allow-list must fail
    /// verification, even though its signature is perfectly self-consistent —
    /// the allow-list, not mere signature validity, gates trust. The SAME record
    /// verifies once its signer is allow-listed. Mirrors
    /// [`receipt_from_non_allowlisted_signer_is_rejected`].
    #[test]
    fn grant_replay_from_non_allowlisted_signer_is_rejected() {
        let trusted_signer = ApprovalSigner::from_seed(99);
        let attacker_signer = ApprovalSigner::from_seed(31337);
        let covered = vec!["arbitrary-egress".to_owned()];
        // The attacker signs a fully self-consistent record with THEIR OWN key.
        let (payload, _sig, _pk) = grant_replay_payload(
            "conv-1",
            "turn-7",
            "post_summary",
            "deadbeef",
            &covered,
            "sha256:template-abc",
            &attacker_signer,
        );

        // The unpinned verifier accepts it (signature is internally consistent) —
        // exactly the forgery surface this issue closes.
        assert!(
            verify_grant_replay(&payload),
            "the unpinned verifier trusts any self-consistent signature"
        );

        // An allow-list that does not include the attacker's key rejects it.
        let trusted = vec![trusted_signer.public_key_bytes()];
        assert!(
            !verify_grant_replay_pinned(&payload, &trusted),
            "a grant_replay signed by a non-allow-listed key must not verify"
        );

        // The IDENTICAL payload verifies once the attacker's key is allow-listed
        // (proves the rejection was the allow-list, not some other defect).
        let trusted_plus_attacker = vec![
            trusted_signer.public_key_bytes(),
            attacker_signer.public_key_bytes(),
        ];
        assert!(
            verify_grant_replay_pinned(&payload, &trusted_plus_attacker),
            "the same record must verify once its signer is allow-listed"
        );

        // An empty allow-list rejects every signer — fail closed.
        assert!(!verify_grant_replay_pinned(&payload, &[]));
    }

    /// The acceptance gate (issue #845): an `approval_response` signed by a key
    /// that is NOT on the trusted-signer allow-list must fail verification via
    /// both [`verify_signed_response_pinned`] and the single-use
    /// [`verify_capability`] gate, even though its signature is self-consistent.
    /// The SAME response verifies once its signer is allow-listed. Mirrors
    /// [`receipt_from_non_allowlisted_signer_is_rejected`].
    #[test]
    fn signed_response_from_non_allowlisted_signer_is_rejected() {
        let trusted_signer = ApprovalSigner::from_seed(99);
        let attacker_signer = ApprovalSigner::from_seed(31337);
        // The attacker self-signs a fully consistent approval with their key.
        let (payload, _sig, _pk) = response_payload(
            "call-0",
            "delete_file",
            r#"{"path":"/etc/hosts"}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "slack:T1:U9",
            "workspace-write",
            "ok",
            "",
            "conv-A",
            "nonce-A",
            &attacker_signer,
        );

        // The unpinned verifier accepts it — the forgery surface this closes.
        assert!(
            verify_signed_response(&payload).is_some(),
            "the unpinned verifier trusts any self-consistent signature"
        );

        // Pinned to a legit allow-list that excludes the attacker ⇒ rejected,
        // both as a bare response and through the capability consume gate.
        let trusted = vec![trusted_signer.public_key_bytes()];
        let consumed = HashSet::new();
        assert!(
            verify_signed_response_pinned(&payload, &trusted).is_none(),
            "an approval_response signed by a non-allow-listed key must not verify"
        );
        assert!(
            verify_capability(&payload, "conv-A", &consumed, &trusted).is_none(),
            "the capability gate must reject a non-allow-listed signer"
        );

        // The IDENTICAL payload verifies once the attacker's key is allow-listed.
        let trusted_plus_attacker = vec![
            trusted_signer.public_key_bytes(),
            attacker_signer.public_key_bytes(),
        ];
        assert!(
            verify_signed_response_pinned(&payload, &trusted_plus_attacker).is_some(),
            "the same response must verify once its signer is allow-listed"
        );
        assert!(
            verify_capability(&payload, "conv-A", &consumed, &trusted_plus_attacker).is_some(),
            "the capability gate honors an allow-listed signer"
        );

        // An empty allow-list rejects every signer — fail closed.
        assert!(verify_signed_response_pinned(&payload, &[]).is_none());
        assert!(verify_capability(&payload, "conv-A", &consumed, &[]).is_none());
    }

    /// A receipt persisted before the v2 binding (no `version`, six fields only)
    /// must still verify for forensics, surfacing as `version == 1` with empty
    /// binding fields. Mirrors the legacy approval-response path.
    #[test]
    fn legacy_v1_receipt_still_verifies() {
        let signer = ApprovalSigner::from_seed(99);
        let trusted = vec![signer.public_key_bytes()];
        let verified = verify_signed_receipt(GOLDEN_V1_RECEIPT.as_bytes(), &trusted)
            .expect("a valid v1 receipt still verifies");
        assert_eq!(verified.version, 1);
        assert_eq!(verified.reference, "tx-old");
        assert!(verified.kind.is_empty());
        assert!(verified.tool_call_id.is_empty());
        assert!(verified.approval_pos.is_empty());
        assert!(verified.subject.is_empty());
        // A pre-payer receipt reports payer as explicit unknown, never
        // inferred.
        assert!(verified.payer_kind.is_empty());
        assert!(verified.paying_account.is_empty());
    }

    /// Injecting a `version` key into a validly-signed legacy receipt must not
    /// verify: the v1 canonical does not cover `version`, so dispatching the
    /// claimed version to the v1 canonical would let the signature check pass
    /// while `VerifiedReceipt.version` echoed an unsigned, writer-chosen value.
    /// Absence — and only absence — reads as v1; every present `version` has to
    /// name a frozen version whose canonical covers the key, which no v1-signed
    /// body can.
    #[test]
    fn injected_version_on_v1_signed_receipt_fails() {
        let signer = ApprovalSigner::from_seed(99);
        let trusted = vec![signer.public_key_bytes()];
        let full: Value =
            serde_json::from_str(GOLDEN_V1_RECEIPT).expect("the frozen v1 receipt is valid JSON");

        // A claimed future version, `0`, an explicit `1`, the current version
        // spelled as a float or a string, `null`, and a negative number are all
        // refused outright (fail closed) — never verified against a guessed
        // canonical. `2` itself is absent from this list only because a
        // v1-signed body relabelled `2` cannot satisfy the v2 canonical
        // anyway; the shape of the refusal is what is pinned here.
        for injected in [
            Value::from(7_u64),
            Value::from(0_u64),
            Value::from(1_u64),
            Value::from(2.0_f64),
            Value::String("2".to_owned()),
            Value::Null,
            Value::from(-1_i64),
        ] {
            let mut tampered = full.clone();
            tampered["version"] = injected;
            assert!(
                verify_signed_receipt(&tampered.to_string().into_bytes(), &trusted).is_none(),
                "a writer-chosen version key must never verify"
            );
        }
        // Sanity: without the injected key the same payload verifies as v1.
        assert!(verify_signed_receipt(GOLDEN_V1_RECEIPT.as_bytes(), &trusted).is_some());
    }

    /// A `payment_receipt` persisted before the v2 binding existed: the six
    /// settlement facts, no `version` key, signed by
    /// `ApprovalSigner::from_seed(99)` over the frozen v1 canonical. Checked
    /// in, never regenerated — the deployment's settled history is what this
    /// pins.
    const GOLDEN_V1_RECEIPT: &str = r#"{"reference":"tx-old","amount":"0.02","currency":"USDC","recipient":"0xr","method":"tempo","timestamp":"2026-06-01T00:00:00Z","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"0b2d980be185a6154d34da71e1ab6226d6dfc65bcd331fcf87b1b190765c4734301a3adececb1f2a80cf38007bc37d61dd4768eed4460a8326032b026a043407"}"#;

    /// A `payment_receipt` signed under **v2**, checked in as literal bytes
    /// rather than minted at test time.
    ///
    /// Signed by `ApprovalSigner::from_seed(99)` over the v2 canonical of the
    /// fields [`golden_v2_receipt_fields`] names. Nothing in this string is
    /// derived from `RECEIPT_VERSION`, which is the entire point: it is a
    /// receipt out of the past, and the day the constant moves it must keep
    /// verifying byte for byte. Never regenerate it — regenerating it is the
    /// bug it exists to catch.
    ///
    /// One literal, not two (`#1842`). It used to be a pair — one under sorted
    /// keys, one under insertion order — selected by probing which ordering the
    /// build's `serde_json::Map` happened to use, because the canonical was a
    /// [`serde_json::Value`] and its bytes therefore depended on whether
    /// anything in the build graph enabled `preserve_order`. These are the
    /// insertion-order bytes: the ones every deployment has actually signed and
    /// persisted, since the control plane and the harness both resolve that
    /// feature. Now that the canonical is a struct serialized in declaration
    /// order, every build produces exactly these bytes, so the sorted-key
    /// literal named a form nothing has ever signed or can now produce, and it
    /// is gone.
    const GOLDEN_V2_RECEIPT: &str = r#"{"version":2,"kind":"outbound_payment_receipt","reference":"tx-frozen-v2","amount":"10000","currency":"0xToken","recipient":"0xrecipient","method":"tempo","timestamp":"2026-06-02T00:00:00Z","tool_call_id":"call-frozen","approval_pos":"42","approved_args_hash":"abcd1234","subject":"conv-frozen","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"4f73999b3885188a976c4a2da45c0fc5b6917102fd5a17a10efbea7c9dc9c13216602de44b52388f6811d07ad3a9225288528828f05d436e8c1d3241e472c809"}"#;

    /// The exact fields [`GOLDEN_V2_RECEIPT`] was signed over. v2 does not
    /// cover payer attribution, so `payer_kind`/`paying_account` are `""` —
    /// present in the struct (every `ReceiptPayload` construction site names
    /// them) but not part of what this fixture's signature covers.
    const fn golden_v2_receipt_fields() -> ReceiptPayload<'static> {
        ReceiptPayload {
            kind: "outbound_payment_receipt",
            reference: "tx-frozen-v2",
            amount: "10000",
            currency: "0xToken",
            recipient: "0xrecipient",
            method: "tempo",
            timestamp: "2026-06-02T00:00:00Z",
            tool_call_id: "call-frozen",
            approval_pos: "42",
            approved_args_hash: "abcd1234",
            subject: "conv-frozen",
            payer_kind: "",
            paying_account: "",
        }
    }

    /// Bumping `RECEIPT_VERSION` must not orphan the receipts already signed
    /// under the outgoing version.
    ///
    /// The receipt under test is a *literal*, signed under v2 and checked in —
    /// not one minted here by `receipt_payload`, which by design signs whatever
    /// the current version is. That distinction is the test: on the day someone
    /// raises `RECEIPT_VERSION` to 3, a minted "v2" payload silently becomes a
    /// v3 payload and stops exercising anything, while this literal keeps being
    /// exactly what a deployment has sitting in its log. It must still verify,
    /// binding tuple intact, with `version` reading 2 — not the current
    /// constant. If it ever stops, every fold that filters on verification has
    /// just dropped the deployment's entire settled v2 history.
    #[test]
    fn frozen_v2_receipts_survive_a_later_version_bump() {
        let signer = ApprovalSigner::from_seed(99);
        let trusted = vec![signer.public_key_bytes()];

        let verified = verify_signed_receipt(GOLDEN_V2_RECEIPT.as_bytes(), &trusted)
            .expect("the frozen v2 canonical must keep verifying receipts already signed under it");

        // Deliberately `2`, never `RECEIPT_VERSION`: the receipt reports the
        // version it was signed under, whatever this build's current one is.
        assert_eq!(verified.version, 2);
        assert_eq!(verified.reference, "tx-frozen-v2");
        assert_eq!(verified.amount, "10000");
        assert_eq!(verified.currency, "0xToken");
        assert_eq!(verified.recipient, "0xrecipient");
        assert_eq!(verified.method, "tempo");
        assert_eq!(verified.timestamp, "2026-06-02T00:00:00Z");
        // The v2 binding tuple survives the round trip; a canonical that had
        // drifted would fail the signature check above, not merely blank these.
        assert_eq!(verified.kind, "outbound_payment_receipt");
        assert_eq!(verified.tool_call_id, "call-frozen");
        assert_eq!(verified.approval_pos, "42");
        assert_eq!(verified.approved_args_hash, "abcd1234");
        assert_eq!(verified.subject, "conv-frozen");
        // v2 signed no payer attribution at all, so it reports payer as
        // explicit unknown — never inferred.
        assert!(verified.payer_kind.is_empty());
        assert!(verified.paying_account.is_empty());
        assert_eq!(verified.signer_public_key, signer.public_key_bytes());

        // Fail-closed is untouched by the freeze: relabel that same signed body
        // with a version this build has frozen no canonical for and it is
        // refused outright rather than checked against a guessed one. `3` is
        // no longer in this list — it is now a frozen version in its own
        // right (v3, payer attribution).
        let mut relabelled: Value = serde_json::from_str(GOLDEN_V2_RECEIPT).unwrap();
        for unknown in [Value::from(4_u64), Value::from(5_u64)] {
            relabelled["version"] = unknown;
            assert!(
                verify_signed_receipt(&relabelled.to_string().into_bytes(), &trusted).is_none(),
                "a version with no frozen canonical must never be guessed at"
            );
        }
    }

    /// A `payment_receipt` signed under **v3** (payer attribution), checked in
    /// as literal bytes rather than minted at test time. Mirrors
    /// [`GOLDEN_V2_RECEIPT`]'s reasoning exactly, one version later.
    const GOLDEN_V3_RECEIPT: &str = r#"{"version":3,"kind":"outbound_payment_receipt","reference":"tx-frozen-v3","amount":"10000","currency":"0xToken","recipient":"0xrecipient","method":"tempo","timestamp":"2026-06-02T00:00:00Z","tool_call_id":"call-frozen","approval_pos":"42","approved_args_hash":"abcd1234","subject":"conv-frozen","payer_kind":"linked_wallet","paying_account":"0xpayer-frozen","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"0f5b4e37955044f7ae10ed1e9a57872200ddfc80d9d24a9a2958b9bb0dbe9a0fe6317cba772807a3797beaef84072a17317c2a220d3ba367077547b4dd77520f"}"#;

    /// The exact fields [`GOLDEN_V3_RECEIPT`] was signed over.
    const fn golden_v3_receipt_fields() -> ReceiptPayload<'static> {
        ReceiptPayload {
            kind: "outbound_payment_receipt",
            reference: "tx-frozen-v3",
            amount: "10000",
            currency: "0xToken",
            recipient: "0xrecipient",
            method: "tempo",
            timestamp: "2026-06-02T00:00:00Z",
            tool_call_id: "call-frozen",
            approval_pos: "42",
            approved_args_hash: "abcd1234",
            subject: "conv-frozen",
            payer_kind: "linked_wallet",
            paying_account: "0xpayer-frozen",
        }
    }

    /// Bumping `RECEIPT_VERSION` again must not orphan the receipts already
    /// signed under v3. Mirrors [`frozen_v2_receipts_survive_a_later_version_bump`].
    #[test]
    fn frozen_v3_receipts_survive_a_later_version_bump() {
        let signer = ApprovalSigner::from_seed(99);
        let trusted = vec![signer.public_key_bytes()];

        let verified = verify_signed_receipt(GOLDEN_V3_RECEIPT.as_bytes(), &trusted)
            .expect("the frozen v3 canonical must keep verifying receipts already signed under it");

        assert_eq!(verified.version, 3);
        assert_eq!(verified.reference, "tx-frozen-v3");
        assert_eq!(verified.kind, "outbound_payment_receipt");
        assert_eq!(verified.tool_call_id, "call-frozen");
        assert_eq!(verified.approval_pos, "42");
        assert_eq!(verified.approved_args_hash, "abcd1234");
        assert_eq!(verified.subject, "conv-frozen");
        assert_eq!(verified.payer_kind, "linked_wallet");
        assert_eq!(verified.paying_account, "0xpayer-frozen");
        assert_eq!(verified.signer_public_key, signer.public_key_bytes());
    }

    /// The frozen v2 fixture is a genuine product of the frozen v2 canonical,
    /// not a hand-typed string: rebuilding its canonical bytes from
    /// [`golden_v2_receipt_fields`] and re-signing reproduces it exactly. Uses
    /// [`ReceiptSchema::V2`] directly (not [`receipt_payload`], which always
    /// signs the *current* version) so this assertion stays pinned to v2 no
    /// matter how many times `RECEIPT_VERSION` moves on.
    #[test]
    fn the_frozen_v2_fixture_reproduces_via_its_own_canonical() {
        let signer = ApprovalSigner::from_seed(99);
        let fields = golden_v2_receipt_fields();
        let canonical = ReceiptSchema::V2.canonical(&fields);
        let sig = signer.sign(&canonical);
        let full = format!(
            r#"{{{body},"signed_by":"{pk}","signature_hex":"{sig}"}}"#,
            body = String::from_utf8(canonical)
                .unwrap()
                .trim_start_matches('{')
                .trim_end_matches('}'),
            pk = crate::hex::lower(&signer.public_key_bytes()),
            sig = crate::hex::lower(&sig),
        );
        assert_eq!(
            full, GOLDEN_V2_RECEIPT,
            "the checked-in v2 fixture must be exactly what the frozen v2 canonical produces"
        );
    }

    /// The frozen v3 fixture is a genuine product of the writer, not a
    /// hand-typed string: signing its fields today (v3 is the current
    /// version) reproduces its bytes exactly.
    ///
    /// This is the assertion that a `RECEIPT_VERSION` bump is *expected* to
    /// break, and the split is deliberate — this one tracks the writer, which
    /// always signs the current version, while
    /// [`frozen_v3_receipts_survive_a_later_version_bump`] tracks history,
    /// which never moves. A bumper re-freezes this one against a v4 fixture
    /// and leaves the v2/v3 literals alone.
    #[test]
    fn the_frozen_v3_fixture_is_what_todays_writer_signs() {
        let signer = ApprovalSigner::from_seed(99);
        let (payload, _sig, _pk) = receipt_payload(&golden_v3_receipt_fields(), &signer);
        assert_eq!(
            String::from_utf8(payload).unwrap(),
            GOLDEN_V3_RECEIPT,
            "the checked-in v3 fixture must be exactly what receipt_payload emits today"
        );
    }
}

#[cfg(test)]
mod resolve_token_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    #[test]
    fn resolve_token_verifies_for_its_own_request_and_conversation() {
        let signer = ApprovalSigner::from_seed(11);
        let token = mint_resolve_token("call-1", "conv-a", 1_000, &signer);
        assert!(verify_resolve_token(
            &token, "call-1", "conv-a", 1_000, &signer
        ));
    }

    #[test]
    fn resolve_token_rejects_a_different_request_id() {
        let signer = ApprovalSigner::from_seed(11);
        let token = mint_resolve_token("call-1", "conv-a", 1_000, &signer);
        assert!(!verify_resolve_token(
            &token, "call-2", "conv-a", 1_000, &signer
        ));
    }

    #[test]
    fn resolve_token_rejects_a_different_conversation() {
        let signer = ApprovalSigner::from_seed(11);
        let token = mint_resolve_token("call-1", "conv-a", 1_000, &signer);
        assert!(!verify_resolve_token(
            &token, "call-1", "conv-b", 1_000, &signer
        ));
    }

    #[test]
    fn resolve_token_rejects_wrong_signer() {
        let signer = ApprovalSigner::from_seed(11);
        let other = ApprovalSigner::from_seed(12);
        let token = mint_resolve_token("call-1", "conv-a", 1_000, &signer);
        assert!(!verify_resolve_token(
            &token, "call-1", "conv-a", 1_000, &other
        ));
    }

    #[test]
    fn resolve_token_rejects_after_ttl_elapses() {
        let signer = ApprovalSigner::from_seed(11);
        let token = mint_resolve_token("call-1", "conv-a", 0, &signer);
        assert!(verify_resolve_token(
            &token,
            "call-1",
            "conv-a",
            RESOLVE_TOKEN_TTL_MS,
            &signer
        ));
        assert!(!verify_resolve_token(
            &token,
            "call-1",
            "conv-a",
            RESOLVE_TOKEN_TTL_MS + 1,
            &signer
        ));
    }

    #[test]
    fn resolve_token_rejects_garbage() {
        let signer = ApprovalSigner::from_seed(11);
        assert!(!verify_resolve_token(
            "not-hex", "call-1", "conv-a", 0, &signer
        ));
        assert!(!verify_resolve_token("", "call-1", "conv-a", 0, &signer));
    }
}

#[cfg(test)]
mod admin_model_change_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    #[test]
    fn admin_model_change_round_trips_and_is_tamper_evident() {
        let signer = ApprovalSigner::from_seed(31);
        let (payload, _sig, _pk) = admin_model_change_payload(
            "team-a",
            "vertex",
            "old-model",
            "vertex",
            "new-model",
            1_000,
            &signer,
        );
        let verified = verify_admin_model_change(&payload).expect("genuine record verifies");
        assert_eq!(verified.principal, "team-a");
        assert_eq!(verified.new_model, "new-model");
        assert_eq!(verified.signer_public_key, signer.public_key_bytes());

        for (field, val) in [
            ("principal", serde_json::json!("attacker")),
            ("new_model", serde_json::json!("evil-model")),
            ("new_provider", serde_json::json!("evil-provider")),
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = val;
            assert!(
                verify_admin_model_change(v.to_string().as_bytes()).is_none(),
                "tampered {field} must fail verification"
            );
        }
    }
}

#[cfg(test)]
mod routine_created_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    /// #1497 INV-RL6: the signed `routine_created` payload round-trips its
    /// who/when/originating-conversation fields and is tamper-evident.
    #[test]
    fn routine_created_round_trips_and_is_tamper_evident() {
        let signer = ApprovalSigner::from_seed(41);
        let (payload, _sig, _pk) = routine_created_payload(
            "daily-standup-a1b2",
            "persona-1",
            "conv-1",
            "call-1",
            "hash-1",
            1_000,
            &signer,
        );
        let verified = verify_routine_created(&payload).expect("genuine record verifies");
        assert_eq!(verified.routine, "daily-standup-a1b2");
        assert_eq!(verified.creator_persona, "persona-1");
        assert_eq!(verified.conversation_id, "conv-1");
        assert_eq!(verified.tool_call_id, "call-1");
        assert_eq!(verified.args_hash, "hash-1");
        assert_eq!(verified.created_at_ms, 1_000);
        assert_eq!(verified.signer_public_key, signer.public_key_bytes());

        for (field, val) in [
            ("routine", serde_json::json!("someone-elses-routine")),
            ("creator_persona", serde_json::json!("attacker")),
            ("conversation_id", serde_json::json!("conv-other")),
            ("tool_call_id", serde_json::json!("call-other")),
            ("args_hash", serde_json::json!("hash-other")),
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = val;
            assert!(
                verify_routine_created(v.to_string().as_bytes()).is_none(),
                "tampered {field} must fail verification"
            );
        }
    }

    #[test]
    fn malformed_routine_created_payload_fails_closed() {
        assert!(verify_routine_created(b"not json").is_none());
        assert!(verify_routine_created(b"{}").is_none());
    }
}

#[cfg(test)]
mod routine_paused_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    /// #1495 INV-RL6: the signed `routine_paused` payload round-trips its
    /// who/when/originating-conversation/reason fields and is tamper-evident.
    #[test]
    fn routine_paused_round_trips_and_is_tamper_evident() {
        let signer = ApprovalSigner::from_seed(51);
        let (payload, _sig, _pk) = routine_paused_payload(
            "daily-standup-a1b2",
            "persona-1",
            "conv-1",
            "call-1",
            "hash-1",
            1_000,
            Some("rotating content"),
            &signer,
        );
        let verified = verify_routine_paused(&payload).expect("genuine record verifies");
        assert_eq!(verified.routine, "daily-standup-a1b2");
        assert_eq!(verified.actor_persona, "persona-1");
        assert_eq!(verified.conversation_id, "conv-1");
        assert_eq!(verified.tool_call_id, "call-1");
        assert_eq!(verified.args_hash, "hash-1");
        assert_eq!(verified.paused_at_ms, 1_000);
        assert_eq!(verified.reason.as_deref(), Some("rotating content"));
        assert_eq!(verified.signer_public_key, signer.public_key_bytes());

        for (field, val) in [
            ("routine", serde_json::json!("someone-elses-routine")),
            ("actor_persona", serde_json::json!("attacker")),
            ("conversation_id", serde_json::json!("conv-other")),
            ("tool_call_id", serde_json::json!("call-other")),
            ("args_hash", serde_json::json!("hash-other")),
            ("reason", serde_json::json!("a different reason")),
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = val;
            assert!(
                verify_routine_paused(v.to_string().as_bytes()).is_none(),
                "tampered {field} must fail verification"
            );
        }
    }

    /// A pause with no reason given round-trips `reason: None` rather than an
    /// empty string.
    #[test]
    fn routine_paused_with_no_reason_round_trips_none() {
        let signer = ApprovalSigner::from_seed(52);
        let (payload, _sig, _pk) = routine_paused_payload(
            "weekly-digest",
            "persona-2",
            "conv-2",
            "call-2",
            "hash-2",
            2_000,
            None,
            &signer,
        );
        let verified = verify_routine_paused(&payload).expect("genuine record verifies");
        assert_eq!(verified.reason, None);
    }

    #[test]
    fn malformed_routine_paused_payload_fails_closed() {
        assert!(verify_routine_paused(b"not json").is_none());
        assert!(verify_routine_paused(b"{}").is_none());
    }
}

#[cfg(test)]
mod routine_resumed_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    /// #1495 INV-RL6: the signed `routine_resumed` payload round-trips its
    /// who/when/originating-conversation fields and is tamper-evident.
    #[test]
    fn routine_resumed_round_trips_and_is_tamper_evident() {
        let signer = ApprovalSigner::from_seed(53);
        let (payload, _sig, _pk) = routine_resumed_payload(
            "daily-standup-a1b2",
            "persona-1",
            "conv-1",
            "call-1",
            "hash-1",
            3_000,
            &signer,
        );
        let verified = verify_routine_resumed(&payload).expect("genuine record verifies");
        assert_eq!(verified.routine, "daily-standup-a1b2");
        assert_eq!(verified.actor_persona, "persona-1");
        assert_eq!(verified.conversation_id, "conv-1");
        assert_eq!(verified.tool_call_id, "call-1");
        assert_eq!(verified.args_hash, "hash-1");
        assert_eq!(verified.resumed_at_ms, 3_000);
        assert_eq!(verified.signer_public_key, signer.public_key_bytes());

        for (field, val) in [
            ("routine", serde_json::json!("someone-elses-routine")),
            ("actor_persona", serde_json::json!("attacker")),
            ("conversation_id", serde_json::json!("conv-other")),
            ("tool_call_id", serde_json::json!("call-other")),
            ("args_hash", serde_json::json!("hash-other")),
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = val;
            assert!(
                verify_routine_resumed(v.to_string().as_bytes()).is_none(),
                "tampered {field} must fail verification"
            );
        }
    }

    #[test]
    fn malformed_routine_resumed_payload_fails_closed() {
        assert!(verify_routine_resumed(b"not json").is_none());
        assert!(verify_routine_resumed(b"{}").is_none());
    }
}

#[cfg(test)]
mod routine_deleted_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    /// #1495 INV-RL2/RL6: the signed `routine_deleted` payload round-trips its
    /// who/when/originating-conversation fields and is tamper-evident.
    #[test]
    fn routine_deleted_round_trips_and_is_tamper_evident() {
        let signer = ApprovalSigner::from_seed(54);
        let (payload, _sig, _pk) = routine_deleted_payload(
            "daily-standup-a1b2",
            "persona-1",
            "conv-1",
            "call-1",
            "hash-1",
            4_000,
            &signer,
        );
        let verified = verify_routine_deleted(&payload).expect("genuine record verifies");
        assert_eq!(verified.routine, "daily-standup-a1b2");
        assert_eq!(verified.actor_persona, "persona-1");
        assert_eq!(verified.conversation_id, "conv-1");
        assert_eq!(verified.tool_call_id, "call-1");
        assert_eq!(verified.args_hash, "hash-1");
        assert_eq!(verified.deleted_at_ms, 4_000);
        assert_eq!(verified.signer_public_key, signer.public_key_bytes());

        for (field, val) in [
            ("routine", serde_json::json!("someone-elses-routine")),
            ("actor_persona", serde_json::json!("attacker")),
            ("conversation_id", serde_json::json!("conv-other")),
            ("tool_call_id", serde_json::json!("call-other")),
            ("args_hash", serde_json::json!("hash-other")),
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = val;
            assert!(
                verify_routine_deleted(v.to_string().as_bytes()).is_none(),
                "tampered {field} must fail verification"
            );
        }
    }

    #[test]
    fn malformed_routine_deleted_payload_fails_closed() {
        assert!(verify_routine_deleted(b"not json").is_none());
        assert!(verify_routine_deleted(b"{}").is_none());
    }
}

#[cfg(test)]
mod routine_scope_changed_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    /// #1806 INV-RL6: the signed `routine_scope_changed` payload round-trips
    /// its who/when/originating-conversation/target-scope fields and is
    /// tamper-evident.
    #[test]
    fn routine_scope_changed_round_trips_and_is_tamper_evident() {
        let signer = ApprovalSigner::from_seed(55);
        let (payload, _sig, _pk) = routine_scope_changed_payload(
            "daily-standup-a1b2",
            "persona-1",
            "conv-1",
            "call-1",
            "hash-1",
            "public",
            5_000,
            &signer,
        );
        let verified = verify_routine_scope_changed(&payload).expect("genuine record verifies");
        assert_eq!(verified.routine, "daily-standup-a1b2");
        assert_eq!(verified.actor_persona, "persona-1");
        assert_eq!(verified.conversation_id, "conv-1");
        assert_eq!(verified.tool_call_id, "call-1");
        assert_eq!(verified.args_hash, "hash-1");
        assert_eq!(verified.scope, "public");
        assert_eq!(verified.changed_at_ms, 5_000);
        assert_eq!(verified.signer_public_key, signer.public_key_bytes());

        for (field, val) in [
            ("routine", serde_json::json!("someone-elses-routine")),
            ("actor_persona", serde_json::json!("attacker")),
            ("conversation_id", serde_json::json!("conv-other")),
            ("tool_call_id", serde_json::json!("call-other")),
            ("args_hash", serde_json::json!("hash-other")),
            ("scope", serde_json::json!("private")),
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = val;
            assert!(
                verify_routine_scope_changed(v.to_string().as_bytes()).is_none(),
                "tampered {field} must fail verification"
            );
        }
    }

    #[test]
    fn malformed_routine_scope_changed_payload_fails_closed() {
        assert!(verify_routine_scope_changed(b"not json").is_none());
        assert!(verify_routine_scope_changed(b"{}").is_none());
    }
}

#[cfg(test)]
mod canonical_freeze {
    //! Every signed canonical in this module, frozen as literal bytes (`#1842`).
    //!
    //! These are the bytes a deployment has already signed and has sitting in
    //! its log. They are checked in, never regenerated: regenerating one is the
    //! defect this module exists to catch, because a canonical whose bytes move
    //! invalidates every signature ever minted over the old ones.
    //!
    //! The reason they can be single literals at all is the fix `#1842` made.
    //! Before it, each canonical was a [`serde_json::Value`], whose object is a
    //! `BTreeMap` (keys sorted) by default and an `IndexMap` (insertion order)
    //! whenever anything in the build graph enables `serde_json/preserve_order`
    //! — so the same payload signed by two binaries with different dependency
    //! sets produced different bytes and different signatures. Run this module
    //! under either selection and every literal below holds:
    //!
    //! ```text
    //! cargo nextest run -p polyc-crypto                    # no preserve_order
    //! cargo nextest run -p polyc-crypto -p polyc-payments  # preserve_order on
    //! ```
    //!
    //! Deliberately absent: `request_payload`. The `approval_request` event is
    //! unsigned — the *response* is what carries a signature — so no signature
    //! depends on its bytes, and its `preview` field is caller-supplied JSON
    //! whose key order is the caller's. Nothing here can freeze that, and
    //! nothing needs to.
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;

    /// Assert a canonical's bytes are exactly the frozen literal.
    fn frozen(label: &str, got: &[u8], want: &str) {
        assert_eq!(
            String::from_utf8(got.to_vec()).unwrap(),
            want,
            "{label}: canonical bytes moved — every signature over the old bytes is now unverifiable"
        );
    }

    fn caps() -> Vec<String> {
        vec!["arbitrary-egress".to_owned(), "mutate-external".to_owned()]
    }

    fn transitions() -> Vec<CredentialKeyTransition> {
        vec![
            CredentialKeyTransition {
                kid: "k1".to_owned(),
                from: "absent".to_owned(),
                to: "active".to_owned(),
            },
            CredentialKeyTransition {
                kid: "k2".to_owned(),
                from: "active".to_owned(),
                to: "revoked".to_owned(),
            },
        ]
    }

    const AT_MS: u64 = 1_750_000_000_000;
    /// The routine canonicals' replay-idempotency key (`#1638`), sampled here
    /// so every routine literal below is minted over one fixed pair.
    const ROUTINE_CALL: &str = "call-1";
    const ROUTINE_ARGS_HASH: &str = "abcd1234";

    #[test]
    fn approval_response_canonical_is_frozen() {
        let caps = caps();
        frozen(
            "response_canonical (no approver)",
            &response_canonical(
                "req-1",
                "paid_fetch",
                "{\"a\":1}",
                "{\"a\":2}",
                true,
                false,
                &caps,
                "persona:alice",
                "",
                "workspace-write",
                "looks fine",
                "ctx",
                "conv-1",
                "nonce-1",
            ),
            NO_APPROVER_CANONICAL,
        );
        // A non-empty `approver` is appended after `nonce`, never sorted into
        // the middle — the omit-when-empty rule of #1025, now a property of
        // `ResponseCanonical`'s field order rather than of a map.
        frozen(
            "response_canonical (approver)",
            &response_canonical(
                "req-1",
                "paid_fetch",
                "{\"a\":1}",
                "{\"a\":2}",
                true,
                true,
                &caps,
                "persona:alice",
                "persona:admin",
                "workspace-write",
                "looks fine",
                "ctx",
                "conv-1",
                "nonce-1",
            ),
            APPROVER_CANONICAL,
        );
        let (full, sig, _pk) = response_payload(
            "req-1",
            "paid_fetch",
            "{\"a\":1}",
            "{\"a\":2}",
            true,
            true,
            &caps,
            "persona:alice",
            "persona:admin",
            "workspace-write",
            "looks fine",
            "ctx",
            "conv-1",
            "nonce-1",
            &ApprovalSigner::from_seed(99),
        );
        frozen("response_payload", &full, RESPONSE_PAYLOAD);
        assert_eq!(crate::hex::lower(&sig), RESPONSE_SIG);
    }

    const NO_APPROVER_CANONICAL: &str = r#"{"request_id":"req-1","tool_name":"paid_fetch","args_json":"{\"a\":1}","modified_args_json":"{\"a\":2}","approved":true,"approved_for_session":false,"covered_capabilities":["arbitrary-egress","mutate-external"],"caller":"persona:alice","sandbox_mode":"workspace-write","reason":"looks fine","injected_context":"ctx","conversation_id":"conv-1","nonce":"nonce-1"}"#;
    const APPROVER_CANONICAL: &str = r#"{"request_id":"req-1","tool_name":"paid_fetch","args_json":"{\"a\":1}","modified_args_json":"{\"a\":2}","approved":true,"approved_for_session":true,"covered_capabilities":["arbitrary-egress","mutate-external"],"caller":"persona:alice","sandbox_mode":"workspace-write","reason":"looks fine","injected_context":"ctx","conversation_id":"conv-1","nonce":"nonce-1","approver":"persona:admin"}"#;
    const RESPONSE_PAYLOAD: &str = r#"{"request_id":"req-1","tool_name":"paid_fetch","args_json":"{\"a\":1}","modified_args_json":"{\"a\":2}","approved":true,"approved_for_session":true,"covered_capabilities":["arbitrary-egress","mutate-external"],"caller":"persona:alice","sandbox_mode":"workspace-write","reason":"looks fine","injected_context":"ctx","conversation_id":"conv-1","nonce":"nonce-1","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"aea101dfae5a1cf2568540d4d737b11764d060280049ddfb47d865d108e4897f3144fa3aaeaaa8e0c20a59abf5e18834b51b389c986349bf28391e68a5bc5300","approver":"persona:admin"}"#;
    const RESPONSE_SIG: &str = "aea101dfae5a1cf2568540d4d737b11764d060280049ddfb47d865d108e4897f3144fa3aaeaaa8e0c20a59abf5e18834b51b389c986349bf28391e68a5bc5300";

    #[test]
    fn excision_canonical_is_frozen() {
        let signer = ApprovalSigner::from_seed(99);
        frozen(
            "excision_canonical",
            &excision_canonical(
                "conv-1",
                EXCISION_SCOPE_CASCADE,
                &[17, 23, 40],
                "persona:alice",
                "prompt injection",
            ),
            EXCISION_CANONICAL_LIT,
        );
        let (full, sig, _) = excision_payload(
            "conv-1",
            EXCISION_SCOPE_CASCADE,
            &[17, 23, 40],
            "persona:alice",
            "prompt injection",
            &signer,
        );
        frozen("excision_payload", &full, EXCISION_PAYLOAD_LIT);
        assert_eq!(crate::hex::lower(&sig), EXCISION_SIG_LIT);
    }

    #[test]
    fn grant_replay_canonical_is_frozen() {
        let signer = ApprovalSigner::from_seed(99);
        let caps = caps();
        frozen(
            "grant_replay_canonical",
            &grant_replay_canonical(
                "conv-1",
                "turn-8",
                "paid_fetch",
                "cafe",
                &caps,
                "sha256:abc",
            ),
            GRANT_REPLAY_CANONICAL_LIT,
        );
        let (full, sig, _) = grant_replay_payload(
            "conv-1",
            "turn-8",
            "paid_fetch",
            "cafe",
            &caps,
            "sha256:abc",
            &signer,
        );
        frozen("grant_replay_payload", &full, GRANT_REPLAY_PAYLOAD_LIT);
        assert_eq!(crate::hex::lower(&sig), GRANT_REPLAY_SIG_LIT);
    }

    #[test]
    fn deferred_and_mutation_canonicals_are_frozen() {
        let signer = ApprovalSigner::from_seed(99);
        let (full, sig, _) = deferred_payload("req-1", "conv-1", "needs more detail", &signer);
        frozen("deferred_payload", &full, DEFERRED_PAYLOAD_LIT);
        assert_eq!(crate::hex::lower(&sig), DEFERRED_SIG_LIT);

        let (full, sig, _) = mutation_payload(
            "tool_input_rewrite",
            "call-1",
            "paid_fetch",
            "conv-1",
            "before-args",
            "after-args",
            &signer,
        );
        frozen("mutation_payload", &full, MUTATION_PAYLOAD_LIT);
        assert_eq!(crate::hex::lower(&sig), MUTATION_SIG_LIT);
    }

    #[test]
    fn receipt_canonicals_are_frozen() {
        let signer = ApprovalSigner::from_seed(99);
        let fields = ReceiptPayload {
            kind: "outbound_payment_receipt",
            reference: "tx-frozen-v2",
            amount: "10000",
            currency: "0xToken",
            recipient: "0xrecipient",
            method: "tempo",
            timestamp: "2026-06-02T00:00:00Z",
            tool_call_id: "call-frozen",
            approval_pos: "42",
            approved_args_hash: "abcd1234",
            subject: "conv-frozen",
            // v1/v2 canonicals don't cover payer attribution, so these are
            // never read by either builder below — present only because
            // `ReceiptPayload` names them for every construction site.
            payer_kind: "",
            paying_account: "",
        };
        frozen(
            "canonical_json_v2",
            &canonical_bytes(&fields.canonical_json_v2()),
            RECEIPT_V2_CANONICAL_LIT,
        );
        frozen(
            "canonical_json_v1",
            &canonical_bytes(&fields.canonical_json_v1()),
            RECEIPT_V1_CANONICAL_LIT,
        );

        // `receipt_payload` always signs the CURRENT version (v3), so its
        // pinning needs payer attribution and its own v3 literal — the v1/v2
        // canonical pins above are untouched, since they call the frozen
        // per-version builders directly rather than `receipt_payload`.
        let fields_v3 = ReceiptPayload {
            payer_kind: "linked_wallet",
            paying_account: "0xpayer-frozen",
            ..fields
        };
        frozen(
            "canonical_json_v3",
            &canonical_bytes(&fields_v3.canonical_json_v3()),
            RECEIPT_V3_CANONICAL_LIT,
        );
        let (full, sig, _) = receipt_payload(&fields_v3, &signer);
        frozen("receipt_payload", &full, RECEIPT_PAYLOAD_LIT);
        assert_eq!(crate::hex::lower(&sig), RECEIPT_SIG_LIT);
    }

    #[test]
    fn resolve_token_canonical_is_frozen() {
        let signer = ApprovalSigner::from_seed(99);
        frozen(
            "resolve_token_canonical",
            &resolve_token_canonical("req-1", "conv-1", AT_MS),
            RESOLVE_TOKEN_CANONICAL_LIT,
        );
        assert_eq!(
            mint_resolve_token("req-1", "conv-1", AT_MS, &signer),
            RESOLVE_TOKEN_LIT,
            "a minted resolve token's bytes are frozen — a token is hex of the whole object"
        );
    }

    #[test]
    fn admin_model_change_canonical_is_frozen() {
        let signer = ApprovalSigner::from_seed(99);
        frozen(
            "admin_model_change_canonical",
            &admin_model_change_canonical(
                "admin:root",
                "prov-a",
                "model-a",
                "prov-b",
                "model-b",
                AT_MS,
            ),
            ADMIN_MODEL_CANONICAL_LIT,
        );
        let (full, sig, _) = admin_model_change_payload(
            "admin:root",
            "prov-a",
            "model-a",
            "prov-b",
            "model-b",
            AT_MS,
            &signer,
        );
        frozen("admin_model_change_payload", &full, ADMIN_MODEL_PAYLOAD_LIT);
        assert_eq!(crate::hex::lower(&sig), ADMIN_MODEL_SIG_LIT);
    }

    /// The one canonical here that nests an object: each `transitions` element
    /// is its own `{kid, from, to}`, and its key order was map-dependent for
    /// exactly the same reason the outer object's was.
    #[test]
    fn credential_change_canonical_is_frozen() {
        let signer = ApprovalSigner::from_seed(99);
        let transitions = transitions();
        frozen(
            "credential_change_canonical",
            &credential_change_canonical(
                "credential_enrolled",
                "admin:root",
                "edge-1",
                "k1",
                "edge, admin",
                &transitions,
                AT_MS,
            ),
            CREDENTIAL_CANONICAL_LIT,
        );
        let (full, sig, _) = credential_change_payload(
            "credential_enrolled",
            "admin:root",
            "edge-1",
            "k1",
            "edge, admin",
            &transitions,
            AT_MS,
            &signer,
        );
        frozen("credential_change_payload", &full, CREDENTIAL_PAYLOAD_LIT);
        assert_eq!(crate::hex::lower(&sig), CREDENTIAL_SIG_LIT);
    }

    #[test]
    fn routine_audit_canonicals_are_frozen() {
        let signer = ApprovalSigner::from_seed(99);

        frozen(
            "routine_created_canonical",
            &routine_created_canonical(
                "r-1",
                "persona:alice",
                "conv-1",
                ROUTINE_CALL,
                ROUTINE_ARGS_HASH,
                AT_MS,
            ),
            ROUTINE_CREATED_CANONICAL_LIT,
        );
        let (full, sig, _) = routine_created_payload(
            "r-1",
            "persona:alice",
            "conv-1",
            ROUTINE_CALL,
            ROUTINE_ARGS_HASH,
            AT_MS,
            &signer,
        );
        frozen(
            "routine_created_payload",
            &full,
            ROUTINE_CREATED_PAYLOAD_LIT,
        );
        assert_eq!(crate::hex::lower(&sig), ROUTINE_CREATED_SIG_LIT);

        frozen(
            "routine_paused_canonical (reason)",
            &routine_paused_canonical(
                "r-1",
                "persona:alice",
                "conv-1",
                ROUTINE_CALL,
                ROUTINE_ARGS_HASH,
                AT_MS,
                Some("too noisy"),
            ),
            ROUTINE_PAUSED_SOME_LIT,
        );
        frozen(
            "routine_paused_canonical (no reason)",
            &routine_paused_canonical(
                "r-1",
                "persona:alice",
                "conv-1",
                ROUTINE_CALL,
                ROUTINE_ARGS_HASH,
                AT_MS,
                None,
            ),
            ROUTINE_PAUSED_NONE_LIT,
        );
        let (full, sig, _) = routine_paused_payload(
            "r-1",
            "persona:alice",
            "conv-1",
            ROUTINE_CALL,
            ROUTINE_ARGS_HASH,
            AT_MS,
            Some("too noisy"),
            &signer,
        );
        frozen("routine_paused_payload", &full, ROUTINE_PAUSED_PAYLOAD_LIT);
        assert_eq!(crate::hex::lower(&sig), ROUTINE_PAUSED_SIG_LIT);

        frozen(
            "routine_resumed_canonical",
            &routine_resumed_canonical(
                "r-1",
                "persona:alice",
                "conv-1",
                ROUTINE_CALL,
                ROUTINE_ARGS_HASH,
                AT_MS,
            ),
            ROUTINE_RESUMED_CANONICAL_LIT,
        );
        let (full, sig, _) = routine_resumed_payload(
            "r-1",
            "persona:alice",
            "conv-1",
            ROUTINE_CALL,
            ROUTINE_ARGS_HASH,
            AT_MS,
            &signer,
        );
        frozen(
            "routine_resumed_payload",
            &full,
            ROUTINE_RESUMED_PAYLOAD_LIT,
        );
        assert_eq!(crate::hex::lower(&sig), ROUTINE_RESUMED_SIG_LIT);

        frozen(
            "routine_deleted_canonical",
            &routine_deleted_canonical(
                "r-1",
                "persona:alice",
                "conv-1",
                ROUTINE_CALL,
                ROUTINE_ARGS_HASH,
                AT_MS,
            ),
            ROUTINE_DELETED_CANONICAL_LIT,
        );
        let (full, sig, _) = routine_deleted_payload(
            "r-1",
            "persona:alice",
            "conv-1",
            ROUTINE_CALL,
            ROUTINE_ARGS_HASH,
            AT_MS,
            &signer,
        );
        frozen(
            "routine_deleted_payload",
            &full,
            ROUTINE_DELETED_PAYLOAD_LIT,
        );
        assert_eq!(crate::hex::lower(&sig), ROUTINE_DELETED_SIG_LIT);

        frozen(
            "routine_scope_changed_canonical",
            &routine_scope_changed_canonical(
                "r-1",
                "persona:alice",
                "conv-1",
                ROUTINE_CALL,
                ROUTINE_ARGS_HASH,
                "public",
                AT_MS,
            ),
            ROUTINE_SCOPE_CHANGED_CANONICAL_LIT,
        );
        let (full, sig, _) = routine_scope_changed_payload(
            "r-1",
            "persona:alice",
            "conv-1",
            ROUTINE_CALL,
            ROUTINE_ARGS_HASH,
            "public",
            AT_MS,
            &signer,
        );
        frozen(
            "routine_scope_changed_payload",
            &full,
            ROUTINE_SCOPE_CHANGED_PAYLOAD_LIT,
        );
        assert_eq!(crate::hex::lower(&sig), ROUTINE_SCOPE_CHANGED_SIG_LIT);
    }

    const EXCISION_CANONICAL_LIT: &str = r#"{"conversation_id":"conv-1","scope":"cascade","positions":[17,23,40],"requested_by":"persona:alice","reason":"prompt injection"}"#;
    const EXCISION_PAYLOAD_LIT: &str = r#"{"conversation_id":"conv-1","scope":"cascade","positions":[17,23,40],"requested_by":"persona:alice","reason":"prompt injection","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"6dbe6aef29cd78faf5044e23aa9f49ba281cbda46b06ffdbba8c5b60b7de67f72beafd3fc83710a11fc8bd37a71da51dbfd722eabbc5bd9f509dfb081a35700b"}"#;
    const EXCISION_SIG_LIT: &str = "6dbe6aef29cd78faf5044e23aa9f49ba281cbda46b06ffdbba8c5b60b7de67f72beafd3fc83710a11fc8bd37a71da51dbfd722eabbc5bd9f509dfb081a35700b";
    const GRANT_REPLAY_CANONICAL_LIT: &str = r#"{"conversation_id":"conv-1","turn_id":"turn-8","tool":"paid_fetch","grant_ref":"cafe","covered_capabilities":["arbitrary-egress","mutate-external"],"coverage_hash":"sha256:abc"}"#;
    const GRANT_REPLAY_PAYLOAD_LIT: &str = r#"{"conversation_id":"conv-1","turn_id":"turn-8","tool":"paid_fetch","grant_ref":"cafe","covered_capabilities":["arbitrary-egress","mutate-external"],"coverage_hash":"sha256:abc","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"b98f27ea001616a9c5edf49b71df1c65eaf391462572e1526f8be6ac132bed0aeae56644cdaa77b3112bfffc0d2dc3ac849713ec32563654ceaeb741dfc8550a"}"#;
    const GRANT_REPLAY_SIG_LIT: &str = "b98f27ea001616a9c5edf49b71df1c65eaf391462572e1526f8be6ac132bed0aeae56644cdaa77b3112bfffc0d2dc3ac849713ec32563654ceaeb741dfc8550a";
    const DEFERRED_PAYLOAD_LIT: &str = r#"{"request_id":"req-1","conversation_id":"conv-1","reason":"needs more detail","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"95d968b15da8f3b3f248dbf05b7b819c6f7d969c9c6b3470b8ec0657d63ef1dd38e9d0fdaed43aee7b94ec16828d9ac74634940afebe5a5623dd2561c5afd506"}"#;
    const DEFERRED_SIG_LIT: &str = "95d968b15da8f3b3f248dbf05b7b819c6f7d969c9c6b3470b8ec0657d63ef1dd38e9d0fdaed43aee7b94ec16828d9ac74634940afebe5a5623dd2561c5afd506";
    const MUTATION_PAYLOAD_LIT: &str = r#"{"kind":"tool_input_rewrite","tool_call_id":"call-1","tool_name":"paid_fetch","conversation_id":"conv-1","before":"before-args","after":"after-args","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"c1386859a36e81c0dd0d256a1fb27cd02fb73e59048687d10ec74546b4a95e485aa2f045dab568a4432da72bd7cbcbc0789ee6ce4799017ecc8aaf62efd42e03"}"#;
    const MUTATION_SIG_LIT: &str = "c1386859a36e81c0dd0d256a1fb27cd02fb73e59048687d10ec74546b4a95e485aa2f045dab568a4432da72bd7cbcbc0789ee6ce4799017ecc8aaf62efd42e03";
    const RECEIPT_V2_CANONICAL_LIT: &str = r#"{"version":2,"kind":"outbound_payment_receipt","reference":"tx-frozen-v2","amount":"10000","currency":"0xToken","recipient":"0xrecipient","method":"tempo","timestamp":"2026-06-02T00:00:00Z","tool_call_id":"call-frozen","approval_pos":"42","approved_args_hash":"abcd1234","subject":"conv-frozen"}"#;
    const RECEIPT_V1_CANONICAL_LIT: &str = r#"{"reference":"tx-frozen-v2","amount":"10000","currency":"0xToken","recipient":"0xrecipient","method":"tempo","timestamp":"2026-06-02T00:00:00Z"}"#;
    const RECEIPT_V3_CANONICAL_LIT: &str = r#"{"version":3,"kind":"outbound_payment_receipt","reference":"tx-frozen-v2","amount":"10000","currency":"0xToken","recipient":"0xrecipient","method":"tempo","timestamp":"2026-06-02T00:00:00Z","tool_call_id":"call-frozen","approval_pos":"42","approved_args_hash":"abcd1234","subject":"conv-frozen","payer_kind":"linked_wallet","paying_account":"0xpayer-frozen"}"#;
    const RECEIPT_PAYLOAD_LIT: &str = r#"{"version":3,"kind":"outbound_payment_receipt","reference":"tx-frozen-v2","amount":"10000","currency":"0xToken","recipient":"0xrecipient","method":"tempo","timestamp":"2026-06-02T00:00:00Z","tool_call_id":"call-frozen","approval_pos":"42","approved_args_hash":"abcd1234","subject":"conv-frozen","payer_kind":"linked_wallet","paying_account":"0xpayer-frozen","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"eec04c909fc7ae838bde2e2ab52144a523fe23939e16c355e12420d2d4b354ba528e5162558d9565ce930aac35a8172bfb0801e0c39d80f2864c948181eefe00"}"#;
    const RECEIPT_SIG_LIT: &str = "eec04c909fc7ae838bde2e2ab52144a523fe23939e16c355e12420d2d4b354ba528e5162558d9565ce930aac35a8172bfb0801e0c39d80f2864c948181eefe00";
    const RESOLVE_TOKEN_CANONICAL_LIT: &str =
        r#"{"request_id":"req-1","conversation_id":"conv-1","minted_at_ms":1750000000000}"#;
    const RESOLVE_TOKEN_LIT: &str = "7b22726571756573745f6964223a227265712d31222c22636f6e766572736174696f6e5f6964223a22636f6e762d31222c226d696e7465645f61745f6d73223a313735303030303030303030302c227369676e61747572655f686578223a223234303734613638613638396335613137643037343334353530376535653437626263623531366165616232633363376566656431363435663235383164643665313165616237396466343537333463646136623230306463663938393334333630306365366161303064653161643234633534363733356462336236653034227d";
    const ADMIN_MODEL_CANONICAL_LIT: &str = r#"{"principal":"admin:root","previous_provider":"prov-a","previous_model":"model-a","new_provider":"prov-b","new_model":"model-b","changed_at_ms":1750000000000}"#;
    const ADMIN_MODEL_PAYLOAD_LIT: &str = r#"{"principal":"admin:root","previous_provider":"prov-a","previous_model":"model-a","new_provider":"prov-b","new_model":"model-b","changed_at_ms":1750000000000,"signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"891b2c43aba8d251ad4eb08a70d0cc3791469a4d3995c803e0baae01bfd4a8dc618433f7235ff9746ba1d83d537362d2e490608fd21f3f156794f853d874f903"}"#;
    const ADMIN_MODEL_SIG_LIT: &str = "891b2c43aba8d251ad4eb08a70d0cc3791469a4d3995c803e0baae01bfd4a8dc618433f7235ff9746ba1d83d537362d2e490608fd21f3f156794f853d874f903";
    const CREDENTIAL_CANONICAL_LIT: &str = r#"{"change":"credential_enrolled","principal":"admin:root","edge_id":"edge-1","kid":"k1","grants":"edge, admin","transitions":[{"kid":"k1","from":"absent","to":"active"},{"kid":"k2","from":"active","to":"revoked"}],"changed_at_ms":1750000000000}"#;
    const CREDENTIAL_PAYLOAD_LIT: &str = r#"{"change":"credential_enrolled","principal":"admin:root","edge_id":"edge-1","kid":"k1","grants":"edge, admin","transitions":[{"kid":"k1","from":"absent","to":"active"},{"kid":"k2","from":"active","to":"revoked"}],"changed_at_ms":1750000000000,"signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"e5384d9ba22a1497ce9beba54c62f2c234bd0c84ba9c2f3ded6fff8e30c01a74d0485683aab1196e64a1c567b830e34fa3f715d13f7b8746a66dfe80b18a4c0b"}"#;
    const CREDENTIAL_SIG_LIT: &str = "e5384d9ba22a1497ce9beba54c62f2c234bd0c84ba9c2f3ded6fff8e30c01a74d0485683aab1196e64a1c567b830e34fa3f715d13f7b8746a66dfe80b18a4c0b";
    const ROUTINE_CREATED_CANONICAL_LIT: &str = r#"{"routine":"r-1","creator_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","created_at_ms":1750000000000}"#;
    const ROUTINE_CREATED_PAYLOAD_LIT: &str = r#"{"routine":"r-1","creator_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","created_at_ms":1750000000000,"signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"65ea620c0447550151ebcedaeb325595d8d10a8ec2f39a98d9215042c636d464ed62f82a88378d254fbf4803a2e7b569b26c78c45e74e498785496ed3701400e"}"#;
    const ROUTINE_CREATED_SIG_LIT: &str = "65ea620c0447550151ebcedaeb325595d8d10a8ec2f39a98d9215042c636d464ed62f82a88378d254fbf4803a2e7b569b26c78c45e74e498785496ed3701400e";
    const ROUTINE_PAUSED_SOME_LIT: &str = r#"{"routine":"r-1","actor_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","paused_at_ms":1750000000000,"reason":"too noisy"}"#;
    const ROUTINE_PAUSED_NONE_LIT: &str = r#"{"routine":"r-1","actor_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","paused_at_ms":1750000000000,"reason":null}"#;
    const ROUTINE_PAUSED_PAYLOAD_LIT: &str = r#"{"routine":"r-1","actor_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","paused_at_ms":1750000000000,"reason":"too noisy","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"9dca477fdc2536aa2b0bd1e7fd4a099e880c5a03742c0b4741fe7d2aa62456aa1b96b137d7c9b211f2721a88b72eb98d1694e06c1744e2fcfdf5f3fed5f97e04"}"#;
    const ROUTINE_PAUSED_SIG_LIT: &str = "9dca477fdc2536aa2b0bd1e7fd4a099e880c5a03742c0b4741fe7d2aa62456aa1b96b137d7c9b211f2721a88b72eb98d1694e06c1744e2fcfdf5f3fed5f97e04";
    const ROUTINE_RESUMED_CANONICAL_LIT: &str = r#"{"routine":"r-1","actor_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","resumed_at_ms":1750000000000}"#;
    const ROUTINE_RESUMED_PAYLOAD_LIT: &str = r#"{"routine":"r-1","actor_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","resumed_at_ms":1750000000000,"signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"1a034d680b5a2f034adad6a2034c8f209fdc8336c89541b51edaf889de5066ad59e54af4a8f089ca14720d421c7d85b33d5b75fd3d56c408708ca2812b519b06"}"#;
    const ROUTINE_RESUMED_SIG_LIT: &str = "1a034d680b5a2f034adad6a2034c8f209fdc8336c89541b51edaf889de5066ad59e54af4a8f089ca14720d421c7d85b33d5b75fd3d56c408708ca2812b519b06";
    const ROUTINE_DELETED_CANONICAL_LIT: &str = r#"{"routine":"r-1","actor_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","deleted_at_ms":1750000000000}"#;
    const ROUTINE_DELETED_PAYLOAD_LIT: &str = r#"{"routine":"r-1","actor_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","deleted_at_ms":1750000000000,"signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"c944bb5fea00c41e09ded223f4587d1b13359b9c5a7e38204f3734abafe8dbc747edc7b88dc4b5cab664711c0b1a77f2be928baecdc50d78b4b282812687f50f"}"#;
    const ROUTINE_DELETED_SIG_LIT: &str = "c944bb5fea00c41e09ded223f4587d1b13359b9c5a7e38204f3734abafe8dbc747edc7b88dc4b5cab664711c0b1a77f2be928baecdc50d78b4b282812687f50f";
    const ROUTINE_SCOPE_CHANGED_CANONICAL_LIT: &str = r#"{"routine":"r-1","actor_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","scope":"public","changed_at_ms":1750000000000}"#;
    const ROUTINE_SCOPE_CHANGED_PAYLOAD_LIT: &str = r#"{"routine":"r-1","actor_persona":"persona:alice","conversation_id":"conv-1","tool_call_id":"call-1","args_hash":"abcd1234","scope":"public","changed_at_ms":1750000000000,"signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"e9b66d0c4c738965f873e85e7d2c3c551a4a41778f289cbb1338be7ab3624705e90c01e3f15ca5df130ee8b075c9a91b0dcb01b9bc20c7a48c5364f9a482210e"}"#;
    const ROUTINE_SCOPE_CHANGED_SIG_LIT: &str = "e9b66d0c4c738965f873e85e7d2c3c551a4a41778f289cbb1338be7ab3624705e90c01e3f15ca5df130ee8b075c9a91b0dcb01b9bc20c7a48c5364f9a482210e";
}

/// Drives `polyc-conformance-vectors::PAYMENT_REFUSAL`
/// (`crates/conformance-vectors/vectors/payment-refusal.json`) — the pinned,
/// cross-language conformance vectors for the durable payment-refusal event
/// (`#2090`, INV-W5).
#[cfg(test)]
mod payment_refusal_conformance_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs, clippy::unwrap_used)]

    use serde_json::Value;

    use super::*;

    fn vectors() -> Value {
        serde_json::from_str(polyc_conformance_vectors::PAYMENT_REFUSAL).expect("valid JSON")
    }

    fn signer() -> ApprovalSigner {
        let v = vectors();
        let key_hex = v["signer"]["ed25519_private_key_hex"].as_str().unwrap();
        ApprovalSigner::from_key_bytes(&crate::hex::decode(key_hex).unwrap()).expect("valid key")
    }

    /// A vector's `fields` object, decoded into owned `String`s — a named
    /// struct rather than a positional tuple, the same swap-proofing
    /// [`RefusalClassification`] (`crates/control-plane/src/harness_dialer.rs`)
    /// applies to the production recording seam.
    struct VectorFields {
        kind: String,
        reason: String,
        reason_detail: String,
        merchant_host: String,
        requested_base_units: String,
        permitted_base_units: String,
        tool_call_id: String,
        subject: String,
        timestamp: String,
    }

    impl VectorFields {
        fn from_json(v: &Value) -> Self {
            let field = |name: &str| v["fields"][name].as_str().unwrap().to_owned();
            Self {
                kind: field("kind"),
                reason: field("reason"),
                reason_detail: field("reason_detail"),
                merchant_host: field("merchant_host"),
                requested_base_units: field("requested_base_units"),
                permitted_base_units: field("permitted_base_units"),
                tool_call_id: field("tool_call_id"),
                subject: field("subject"),
                timestamp: field("timestamp"),
            }
        }

        fn as_payload(&self) -> RefusalPayload<'_> {
            RefusalPayload {
                kind: self.kind.as_str(),
                reason: self.reason.as_str(),
                reason_detail: self.reason_detail.as_str(),
                merchant_host: self.merchant_host.as_str(),
                requested_base_units: self.requested_base_units.as_str(),
                permitted_base_units: self.permitted_base_units.as_str(),
                tool_call_id: self.tool_call_id.as_str(),
                subject: self.subject.as_str(),
                timestamp: self.timestamp.as_str(),
            }
        }
    }

    #[test]
    fn the_known_good_vector_reproduces_its_bytes_and_signature() {
        let v = vectors();
        let signer = signer();
        let vf = VectorFields::from_json(&v["vector"]);
        let fields = vf.as_payload();
        let expected_canonical = crate::hex::decode(
            v["vector"]["expected_canonical_bytes_hex"]
                .as_str()
                .unwrap(),
        )
        .unwrap();
        assert_eq!(canonical_bytes(&fields.canonical()), expected_canonical);

        let (payload, sig, _pk) = refusal_payload(&fields, &signer);
        assert_eq!(
            crate::hex::lower(&sig),
            v["vector"]["expected_signature_hex"].as_str().unwrap()
        );
        let expected_full = v["vector"]["expected_full_payload"].as_str().unwrap();
        assert_eq!(String::from_utf8(payload.clone()).unwrap(), expected_full);

        let trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        let verified = verify_signed_refusal(&payload, &trusted).expect("verifies");
        assert_eq!(verified.reason, vf.reason);
        assert_eq!(verified.requested_base_units, vf.requested_base_units);
        assert_eq!(verified.permitted_base_units, vf.permitted_base_units);
        assert_eq!(verified.timestamp, vf.timestamp);
    }

    /// INV-W5b: an unrecognized `reason` tag still verifies — the crypto
    /// layer never special-cases `reason`'s value.
    #[test]
    fn the_unknown_reason_vector_still_verifies() {
        let v = vectors();
        let signer = signer();
        let vf = VectorFields::from_json(&v["unknown_reason_vector"]);
        let fields = vf.as_payload();
        let (payload, sig, _pk) = refusal_payload(&fields, &signer);
        assert_eq!(
            crate::hex::lower(&sig),
            v["unknown_reason_vector"]["expected_signature_hex"]
                .as_str()
                .unwrap()
        );

        let trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        let verified = verify_signed_refusal(&payload, &trusted).expect("verifies");
        assert_eq!(verified.reason, "some_future_reason_v7");
    }

    #[test]
    fn the_tampered_reason_vector_must_not_verify() {
        let v = vectors();
        let entry = v["must_not_verify"]
            .as_array()
            .unwrap()
            .iter()
            .find(|e| e["id"] == "tampered-reason")
            .unwrap();
        let payload = entry["full_payload"].as_str().unwrap().as_bytes();
        let trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        assert!(verify_signed_refusal(payload, &trusted).is_none());
    }

    /// The untrusted-signer `must_not_verify` case ships a REAL, executable
    /// payload (`#2090` review, item 6) — not description-only: a real
    /// second signer minted a genuinely valid signature over it (it
    /// verifies against ITS OWN embedded key), and the case proves it is
    /// rejected ONLY because that key sits outside the main vector's
    /// trusted-signer allow-list, never because anything is malformed.
    #[test]
    fn the_untrusted_signer_vector_must_not_verify_against_the_main_signer() {
        let v = vectors();
        let entry = v["must_not_verify"]
            .as_array()
            .unwrap()
            .iter()
            .find(|e| e["id"] == "untrusted-signer")
            .unwrap();
        let payload = entry["full_payload"].as_str().unwrap().as_bytes();

        // Self-consistent: verifies against its OWN embedded key.
        let own_key =
            crate::hex::decode(entry["signed_by_public_key_hex"].as_str().unwrap()).unwrap();
        assert!(
            verify_signed_refusal(payload, &[own_key]).is_some(),
            "the untrusted-signer vector's payload must be internally consistent — a \
             genuinely valid signature over an out-of-allowlist key, not a malformed one"
        );

        // Rejected against the MAIN vector's trusted-signer set.
        let main_trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        assert!(verify_signed_refusal(payload, &main_trusted).is_none());
    }
}

/// Drives `polyc-conformance-vectors::WALLET_LINK_LIFECYCLE`
/// (`crates/conformance-vectors/vectors/wallet-link-lifecycle.json`) — the
/// pinned, cross-language conformance vectors for the durable
/// wallet-link-lifecycle event (`#2123`).
#[cfg(test)]
mod wallet_link_lifecycle_conformance_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs, clippy::unwrap_used)]

    use serde_json::Value;

    use super::*;

    fn vectors() -> Value {
        serde_json::from_str(polyc_conformance_vectors::WALLET_LINK_LIFECYCLE).expect("valid JSON")
    }

    fn signer() -> ApprovalSigner {
        let v = vectors();
        let key_hex = v["signer"]["ed25519_private_key_hex"].as_str().unwrap();
        ApprovalSigner::from_key_bytes(&crate::hex::decode(key_hex).unwrap()).expect("valid key")
    }

    /// A vector's `fields` object, decoded into owned `String`s — a named
    /// struct rather than a positional tuple, the same swap-proofing
    /// [`RefusalPayload`]'s own vector test struct applies.
    struct VectorFields {
        kind: String,
        transition: String,
        subject: String,
        wallet_address: String,
        currency: String,
        chain_id: String,
        limit_base_units: String,
        limit_human: String,
        period_secs: String,
        expiry_unix: String,
        recipients: String,
        conversation_id: String,
        timestamp: String,
    }

    impl VectorFields {
        fn from_json(v: &Value) -> Self {
            let field = |name: &str| v["fields"][name].as_str().unwrap().to_owned();
            Self {
                kind: field("kind"),
                transition: field("transition"),
                subject: field("subject"),
                wallet_address: field("wallet_address"),
                currency: field("currency"),
                chain_id: field("chain_id"),
                limit_base_units: field("limit_base_units"),
                limit_human: field("limit_human"),
                period_secs: field("period_secs"),
                expiry_unix: field("expiry_unix"),
                recipients: field("recipients"),
                conversation_id: field("conversation_id"),
                timestamp: field("timestamp"),
            }
        }

        fn as_payload(&self) -> WalletLinkLifecyclePayload<'_> {
            WalletLinkLifecyclePayload {
                kind: self.kind.as_str(),
                transition: self.transition.as_str(),
                subject: self.subject.as_str(),
                wallet_address: self.wallet_address.as_str(),
                currency: self.currency.as_str(),
                chain_id: self.chain_id.as_str(),
                limit_base_units: self.limit_base_units.as_str(),
                limit_human: self.limit_human.as_str(),
                period_secs: self.period_secs.as_str(),
                expiry_unix: self.expiry_unix.as_str(),
                recipients: self.recipients.as_str(),
                conversation_id: self.conversation_id.as_str(),
                timestamp: self.timestamp.as_str(),
            }
        }
    }

    fn assert_vector_reproduces(vector_key: &str) {
        let v = vectors();
        let signer = signer();
        let vf = VectorFields::from_json(&v[vector_key]);
        let fields = vf.as_payload();
        let expected_canonical = crate::hex::decode(
            v[vector_key]["expected_canonical_bytes_hex"]
                .as_str()
                .unwrap(),
        )
        .unwrap();
        assert_eq!(canonical_bytes(&fields.canonical()), expected_canonical);

        let (payload, sig, _pk) = wallet_link_lifecycle_payload(&fields, &signer);
        assert_eq!(
            crate::hex::lower(&sig),
            v[vector_key]["expected_signature_hex"].as_str().unwrap()
        );
        let expected_full = v[vector_key]["expected_full_payload"].as_str().unwrap();
        assert_eq!(String::from_utf8(payload.clone()).unwrap(), expected_full);

        let trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        let verified = verify_signed_wallet_link_lifecycle(&payload, &trusted).expect("verifies");
        assert_eq!(verified.transition, vf.transition);
        assert_eq!(verified.limit_base_units, vf.limit_base_units);
        assert_eq!(verified.limit_human, vf.limit_human);
        assert_eq!(verified.period_secs, vf.period_secs);
        assert_eq!(verified.expiry_unix, vf.expiry_unix);
        assert_eq!(verified.timestamp, vf.timestamp);
    }

    #[test]
    fn the_known_good_linked_vector_reproduces_its_bytes_and_signature() {
        assert_vector_reproduces("linked_vector");
    }

    /// `renewed` leaves `period_secs`/`expiry_unix` empty (TIP-1011's
    /// `updateSpendingLimit` cannot change either) — this vector pins that
    /// the recorder never invents values for them.
    #[test]
    fn the_known_good_renewed_vector_reproduces_its_bytes_and_signature() {
        assert_vector_reproduces("renewed_vector");
    }

    /// `revoked` leaves every spend-policy field empty — no cap survives a
    /// dead link.
    #[test]
    fn the_known_good_revoked_vector_reproduces_its_bytes_and_signature() {
        assert_vector_reproduces("revoked_vector");
    }

    /// INV-W5b analogue: an unrecognized `transition` tag still verifies —
    /// the crypto layer never special-cases `transition`'s value.
    #[test]
    fn the_unknown_transition_vector_still_verifies() {
        let v = vectors();
        let signer = signer();
        let vf = VectorFields::from_json(&v["unknown_transition_vector"]);
        let fields = vf.as_payload();
        let (payload, sig, _pk) = wallet_link_lifecycle_payload(&fields, &signer);
        assert_eq!(
            crate::hex::lower(&sig),
            v["unknown_transition_vector"]["expected_signature_hex"]
                .as_str()
                .unwrap()
        );

        let trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        let verified = verify_signed_wallet_link_lifecycle(&payload, &trusted).expect("verifies");
        assert_eq!(verified.transition, "some_future_transition_v7");
    }

    #[test]
    fn the_tampered_transition_vector_must_not_verify() {
        let v = vectors();
        let entry = v["must_not_verify"]
            .as_array()
            .unwrap()
            .iter()
            .find(|e| e["id"] == "tampered-transition")
            .unwrap();
        let payload = entry["full_payload"].as_str().unwrap().as_bytes();
        let trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        assert!(verify_signed_wallet_link_lifecycle(payload, &trusted).is_none());
    }

    /// The untrusted-signer `must_not_verify` case ships a REAL, executable
    /// payload — not description-only: a real second signer minted a
    /// genuinely valid signature over it (it verifies against ITS OWN
    /// embedded key), and the case proves it is rejected ONLY because that
    /// key sits outside the main vector's trusted-signer allow-list, never
    /// because anything is malformed.
    #[test]
    fn the_untrusted_signer_vector_must_not_verify_against_the_main_signer() {
        let v = vectors();
        let entry = v["must_not_verify"]
            .as_array()
            .unwrap()
            .iter()
            .find(|e| e["id"] == "untrusted-signer")
            .unwrap();
        let payload = entry["full_payload"].as_str().unwrap().as_bytes();

        // Self-consistent: verifies against its OWN embedded key.
        let own_key =
            crate::hex::decode(entry["signed_by_public_key_hex"].as_str().unwrap()).unwrap();
        assert!(
            verify_signed_wallet_link_lifecycle(payload, &[own_key]).is_some(),
            "the untrusted-signer vector's payload must be internally consistent — a \
             genuinely valid signature over an out-of-allowlist key, not a malformed one"
        );

        // Rejected against the MAIN vector's trusted-signer set.
        let main_trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        assert!(verify_signed_wallet_link_lifecycle(payload, &main_trusted).is_none());
    }
}

/// Drives `polyc-conformance-vectors::PAYMENT_RECEIPT`
/// (`crates/conformance-vectors/vectors/payment-receipt.json`) — the pinned,
/// cross-language conformance vectors for the durable payment-receipt event's
/// v3 payer-attribution addition (`#2099`). Mirrors
/// `payment_refusal_conformance_tests`' shape exactly.
#[cfg(test)]
mod payment_receipt_conformance_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs, clippy::unwrap_used)]

    use serde_json::Value;

    use super::*;

    fn vectors() -> Value {
        serde_json::from_str(polyc_conformance_vectors::PAYMENT_RECEIPT).expect("valid JSON")
    }

    fn signer() -> ApprovalSigner {
        let v = vectors();
        let key_hex = v["signer"]["ed25519_private_key_hex"].as_str().unwrap();
        ApprovalSigner::from_key_bytes(&crate::hex::decode(key_hex).unwrap()).expect("valid key")
    }

    /// A vector's `fields` object, decoded into owned `String`s — named
    /// fields, no positional tuple, matching [`ReceiptPayload`]'s own
    /// swap-proofing reasoning.
    struct VectorFields {
        kind: String,
        reference: String,
        amount: String,
        currency: String,
        recipient: String,
        method: String,
        timestamp: String,
        tool_call_id: String,
        approval_pos: String,
        approved_args_hash: String,
        subject: String,
        payer_kind: String,
        paying_account: String,
    }

    impl VectorFields {
        /// `payer_kind`/`paying_account` default to `""` when a vector's
        /// `fields` object omits them entirely (the frozen v2 vector, which
        /// predates the v3 addition and never had them to begin with).
        fn from_json(v: &Value) -> Self {
            let field = |name: &str| {
                v["fields"]
                    .get(name)
                    .and_then(Value::as_str)
                    .unwrap_or("")
                    .to_owned()
            };
            Self {
                kind: field("kind"),
                reference: field("reference"),
                amount: field("amount"),
                currency: field("currency"),
                recipient: field("recipient"),
                method: field("method"),
                timestamp: field("timestamp"),
                tool_call_id: field("tool_call_id"),
                approval_pos: field("approval_pos"),
                approved_args_hash: field("approved_args_hash"),
                subject: field("subject"),
                payer_kind: field("payer_kind"),
                paying_account: field("paying_account"),
            }
        }

        fn as_payload(&self) -> ReceiptPayload<'_> {
            ReceiptPayload {
                kind: self.kind.as_str(),
                reference: self.reference.as_str(),
                amount: self.amount.as_str(),
                currency: self.currency.as_str(),
                recipient: self.recipient.as_str(),
                method: self.method.as_str(),
                timestamp: self.timestamp.as_str(),
                tool_call_id: self.tool_call_id.as_str(),
                approval_pos: self.approval_pos.as_str(),
                approved_args_hash: self.approved_args_hash.as_str(),
                subject: self.subject.as_str(),
                payer_kind: self.payer_kind.as_str(),
                paying_account: self.paying_account.as_str(),
            }
        }
    }

    #[test]
    fn the_known_good_v3_vector_reproduces_its_bytes_and_signature() {
        let v = vectors();
        let signer = signer();
        let vf = VectorFields::from_json(&v["vector"]);
        let fields = vf.as_payload();
        let expected_canonical = crate::hex::decode(
            v["vector"]["expected_canonical_bytes_hex"]
                .as_str()
                .unwrap(),
        )
        .unwrap();
        assert_eq!(
            canonical_bytes(&fields.canonical_json_v3()),
            expected_canonical
        );

        let (payload, sig, _pk) = receipt_payload(&fields, &signer);
        assert_eq!(
            crate::hex::lower(&sig),
            v["vector"]["expected_signature_hex"].as_str().unwrap()
        );
        let expected_full = v["vector"]["expected_full_payload"].as_str().unwrap();
        assert_eq!(String::from_utf8(payload.clone()).unwrap(), expected_full);

        let trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        let verified = verify_signed_receipt(&payload, &trusted).expect("verifies");
        assert_eq!(verified.version, 3);
        assert_eq!(verified.reference, vf.reference);
        assert_eq!(verified.payer_kind, vf.payer_kind);
        assert_eq!(verified.paying_account, vf.paying_account);
    }

    /// The frozen v2 vector — signed before payer attribution existed — must
    /// still verify byte-for-byte, and its payer fields must decode as
    /// explicit unknown (`""`), never inferred.
    #[test]
    fn the_frozen_v2_vector_still_verifies_with_payer_unknown() {
        let v = vectors();
        let entry = &v["frozen_v2_vector"];
        let full = entry["expected_full_payload"].as_str().unwrap();
        let trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        let verified = verify_signed_receipt(full.as_bytes(), &trusted)
            .expect("the frozen v2 vector verifies");
        assert_eq!(verified.version, 2);
        assert_eq!(verified.reference, "tx-conformance-v2");
        assert!(verified.payer_kind.is_empty());
        assert!(verified.paying_account.is_empty());
    }

    #[test]
    fn the_tampered_payer_vector_must_not_verify() {
        let v = vectors();
        let entry = v["must_not_verify"]
            .as_array()
            .unwrap()
            .iter()
            .find(|e| e["id"] == "tampered-payer")
            .unwrap();
        let payload = entry["full_payload"].as_str().unwrap().as_bytes();
        let trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        assert!(verify_signed_receipt(payload, &trusted).is_none());
    }

    /// The untrusted-signer `must_not_verify` case ships a REAL, executable
    /// payload: a real second signer minted a genuinely valid signature over
    /// it (it verifies against its own embedded key), and the case proves it
    /// is rejected ONLY because that key sits outside the main vector's
    /// trusted-signer allow-list, never because anything is malformed.
    #[test]
    fn the_untrusted_signer_vector_must_not_verify_against_the_main_signer() {
        let v = vectors();
        let entry = v["must_not_verify"]
            .as_array()
            .unwrap()
            .iter()
            .find(|e| e["id"] == "untrusted-signer")
            .unwrap();
        let payload = entry["full_payload"].as_str().unwrap().as_bytes();

        let own_key =
            crate::hex::decode(entry["signed_by_public_key_hex"].as_str().unwrap()).unwrap();
        assert!(
            verify_signed_receipt(payload, &[own_key]).is_some(),
            "the untrusted-signer vector's payload must be internally consistent — a \
             genuinely valid signature over an out-of-allowlist key, not a malformed one"
        );

        let main_trusted = vec![
            crate::hex::decode(v["signer"]["ed25519_public_key_hex"].as_str().unwrap()).unwrap(),
        ];
        assert!(verify_signed_receipt(payload, &main_trusted).is_none());
    }
}