polyc-crypto 2026.7.0

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
//! 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.

use std::collections::HashSet;
use std::sync::Arc;

use serde_json::Value;

use crate::{Signer, verify};

/// Ed25519 signer that mints provenance signatures for `approval_response`
/// payloads. Wraps [`Signer`] in an `Arc` so the gRPC service and the
/// `connect` path share one instance.
#[derive(Clone)]
pub struct ApprovalSigner {
    inner: Arc<Signer>,
}

impl Default for ApprovalSigner {
    /// Deterministic seed (V1 only). Production wires this to a secret
    /// store; the `Default` is here purely so callers can compose.
    fn default() -> Self {
        Self::from_seed(1)
    }
}

impl ApprovalSigner {
    /// Build a signer from a deterministic seed (dev / tests). Production
    /// keys come from a secret store; that wiring is a follow-up.
    #[must_use]
    pub fn from_seed(seed: u64) -> Self {
        Self {
            inner: Arc::new(Signer::from_seed(seed)),
        }
    }

    /// Encoded public key bytes; clients verify approval signatures against
    /// these.
    #[must_use]
    pub fn public_key_bytes(&self) -> Vec<u8> {
        self.inner.public_key_bytes()
    }

    /// Sign the canonical bytes of a response payload. The canonical bytes
    /// are the JSON encoding with the `signature_hex` and `signed_by` fields
    /// cleared — same shape as [`crate::toolcall`] (signature commits to
    /// everything except itself).
    #[must_use]
    pub fn sign(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner.sign(canonical_bytes)
    }
}

/// 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.
#[must_use]
pub fn request_payload(
    request_id: &str,
    tool_name: &str,
    args_json: &str,
    sandbox_mode: &str,
    reason: &str,
    missing_capabilities: &[String],
) -> Vec<u8> {
    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,
    })
    .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`.
///
/// `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,
    sandbox_mode: &str,
    reason: &str,
    injected_context: &str,
    conversation_id: &str,
    nonce: &str,
) -> Vec<u8> {
    serde_json::json!({
        "request_id": request_id,
        "tool_name": tool_name,
        "args_json": args_json,
        "modified_args_json": modified_args_json,
        "approved": approved,
        "approved_for_session": approved_for_session,
        "covered_capabilities": covered_capabilities,
        "caller": caller,
        "sandbox_mode": sandbox_mode,
        "reason": reason,
        "injected_context": injected_context,
        "conversation_id": conversation_id,
        "nonce": nonce,
    })
    .to_string()
    .into_bytes()
}

/// 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,
    sandbox_mode: &str,
    reason: &str,
    injected_context: &str,
    conversation_id: &str,
    nonce: &str,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    let canonical_bytes = response_canonical(
        request_id,
        tool_name,
        args_json,
        modified_args_json,
        approved,
        approved_for_session,
        covered_capabilities,
        caller,
        sandbox_mode,
        reason,
        injected_context,
        conversation_id,
        nonce,
    );
    let signature = signer.sign(&canonical_bytes);
    let pk = signer.public_key_bytes();
    let full = serde_json::json!({
        "request_id": request_id,
        "tool_name": tool_name,
        "args_json": args_json,
        "modified_args_json": modified_args_json,
        "approved": approved,
        "approved_for_session": approved_for_session,
        "covered_capabilities": covered_capabilities,
        "caller": caller,
        "sandbox_mode": sandbox_mode,
        "reason": reason,
        "injected_context": injected_context,
        "conversation_id": conversation_id,
        "nonce": nonce,
        "signed_by": hex_lower(&pk),
        "signature_hex": hex_lower(&signature),
    });
    (full.to_string().into_bytes(), 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> {
    serde_json::json!({
        "conversation_id": conversation_id,
        "scope": scope,
        "positions": positions,
        "requested_by": requested_by,
        "reason": reason,
    })
    .to_string()
    .into_bytes()
}

/// 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>) {
    let canonical = excision_canonical(conversation_id, scope, positions, requested_by, reason);
    let signature = signer.sign(&canonical);
    let pk = signer.public_key_bytes();
    let full = serde_json::json!({
        "conversation_id": conversation_id,
        "scope": scope,
        "positions": positions,
        "requested_by": requested_by,
        "reason": reason,
        "signed_by": hex_lower(&pk),
        "signature_hex": hex_lower(&signature),
    });
    (full.to_string().into_bytes(), signature, pk)
}

/// 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 = hex_decode(v.get("signed_by")?.as_str()?)?;
    let sig = 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>) {
    let canonical = serde_json::json!({
        "request_id": request_id,
        "conversation_id": conversation_id,
        "reason": reason,
    })
    .to_string()
    .into_bytes();
    let signature = signer.sign(&canonical);
    let pk = signer.public_key_bytes();
    let full = serde_json::json!({
        "request_id": request_id,
        "conversation_id": conversation_id,
        "reason": reason,
        "signed_by": hex_lower(&pk),
        "signature_hex": hex_lower(&signature),
    });
    (full.to_string().into_bytes(), signature, pk)
}

/// 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 = hex_decode(v.get("signed_by")?.as_str()?)?;
    let sig = hex_decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = serde_json::json!({
        "request_id": request_id,
        "conversation_id": conversation_id,
        "reason": reason,
    })
    .to_string()
    .into_bytes();
    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>) {
    let canonical = serde_json::json!({
        "kind": kind,
        "tool_call_id": tool_call_id,
        "tool_name": tool_name,
        "conversation_id": conversation_id,
        "before": before,
        "after": after,
    })
    .to_string()
    .into_bytes();
    let signature = signer.sign(&canonical);
    let pk = signer.public_key_bytes();
    let full = serde_json::json!({
        "kind": kind,
        "tool_call_id": tool_call_id,
        "tool_name": tool_name,
        "conversation_id": conversation_id,
        "before": before,
        "after": after,
        "signed_by": hex_lower(&pk),
        "signature_hex": hex_lower(&signature),
    });
    (full.to_string().into_bytes(), signature, pk)
}

/// 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 = hex_decode(v.get("signed_by")?.as_str()?)?;
    let sig = hex_decode(v.get("signature_hex")?.as_str()?)?;
    let canonical = serde_json::json!({
        "kind": kind,
        "tool_call_id": tool_call_id,
        "tool_name": tool_name,
        "conversation_id": conversation_id,
        "before": before,
        "after": after,
    })
    .to_string()
    .into_bytes();
    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. 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 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();
    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 = hex_decode(v.get("signed_by")?.as_str()?)?;
    let sig = 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,
        &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,
            sandbox_mode,
            reason,
            injected_context,
            conversation_id,
            nonce,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Verify a persisted `approval_response` as a SINGLE-USE, conversation-bound
/// capability token (`#370`).
///
/// Returns the verified response only when ALL hold:
/// * the signature verifies against the embedded 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>,
) -> Option<VerifiedResponse> {
    let verified = verify_signed_response(payload)?;
    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,
    sandbox_mode: &str,
    reason: &str,
    injected_context: &str,
    conversation_id: &str,
    nonce: &str,
    signer_pk_hex: &str,
    signature_hex: &str,
) -> bool {
    let Some(pk) = hex_decode(signer_pk_hex) else {
        return false;
    };
    let Some(sig) = 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,
        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.
    pub caller: 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(),
        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. **v1** (legacy, no `version` field) signed
/// only the six settlement facts; it still *verifies* for forensics but carries
/// no kind or binding tuple.
pub const RECEIPT_VERSION: u64 = 2;

/// 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,
    /// Decimal amount as a string (avoids float drift).
    pub amount: &'a str,
    /// Currency / asset symbol.
    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,
}

impl ReceiptPayload<'_> {
    /// Build the canonical (unsigned) **v2** JSON the signature commits to.
    ///
    /// 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 canonical bytes through here,
    /// so adding, renaming, or reordering a covered field is a one-line edit
    /// and the two paths cannot drift. The key set/order is the on-wire
    /// signed contract and must NOT change without a version bump.
    #[must_use]
    fn canonical_json(&self) -> Value {
        serde_json::json!({
            "version": RECEIPT_VERSION,
            "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 v2.
    #[must_use]
    fn canonical_json_v1(&self) -> Value {
        serde_json::json!({
            "reference": self.reference,
            "amount": self.amount,
            "currency": self.currency,
            "recipient": self.recipient,
            "method": self.method,
            "timestamp": self.timestamp,
        })
    }
}

/// 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>) {
    let mut full = fields.canonical_json();
    let canonical_bytes = full.to_string().into_bytes();
    let signature = signer.sign(&canonical_bytes);
    let pk = signer.public_key_bytes();
    // The full payload is the canonical body plus the two signature fields,
    // which are NOT covered by the signature. Append them to the single-source
    // canonical object so the body field set still lives only in
    // `ReceiptPayload::canonical_json`.
    if let Value::Object(map) = &mut full {
        map.insert("signed_by".to_owned(), Value::String(hex_lower(&pk)));
        map.insert(
            "signature_hex".to_owned(),
            Value::String(hex_lower(&signature)),
        );
    }
    (full.to_string().into_bytes(), signature, pk)
}

/// 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,
    /// Decimal amount, as a string (avoids float drift).
    pub amount: String,
    /// Currency / asset symbol.
    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,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted `payment_receipt` payload.
///
/// Returns `Some(record)` if the signature checks out against the embedded
/// public key (caller trusts that key; V1 trusts any signed receipt, like
/// [`verify_signed_response`] — a production key allow-list is a follow-up).
///
/// 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_receipt(payload: &[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 = hex_decode(signed_by_hex)?;
    let sig = hex_decode(signature_hex)?;
    // A legacy receipt carries no `version` key; treat it as v1. A present
    // `version` must equal the exact current version — any other value
    // (including an explicit `1`, a future `3`, or a non-integer) is refused
    // outright rather than verified against a guessed canonical. The v1
    // canonical does not cover the `version` key, so dispatching an unknown
    // claimed version to v1 would let a valid v1 signature verify while the
    // output echoed an unsigned, writer-chosen version — fail closed instead.
    let version = match v.get("version") {
        None => 1,
        Some(n) if n.as_u64() == Some(RECEIPT_VERSION) => RECEIPT_VERSION,
        Some(_) => return None,
    };
    let (kind, tool_call_id, approval_pos, approved_args_hash, subject) =
        if version == RECEIPT_VERSION {
            (
                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 {
            (
                String::new(),
                String::new(),
                String::new(),
                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,
    };
    let canonical_bytes = if version == RECEIPT_VERSION {
        fields.canonical_json()
    } else {
        fields.canonical_json_v1()
    }
    .to_string()
    .into_bytes();
    if verify(&pk, &canonical_bytes, &sig) {
        Some(VerifiedReceipt {
            reference,
            amount,
            currency,
            recipient,
            method,
            timestamp,
            version,
            kind,
            tool_call_id,
            approval_pos,
            approved_args_hash,
            subject,
            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()
}

fn hex_lower(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        use std::fmt::Write as _;
        let _ = write!(&mut s, "{b:02x}");
    }
    s
}

fn hex_decode(s: &str) -> Option<Vec<u8>> {
    if !s.len().is_multiple_of(2) {
        return None;
    }
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
        .collect()
}

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

    use super::*;

    // #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);
    }

    #[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.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.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.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.sandbox_mode,
            &d.reason,
            "",
            "conv-OTHER",
            &d.nonce,
            &d.signer_pk_hex,
            &d.signature_hex
        ));
    }

    /// `#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).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).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).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).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).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).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()
            ))
        );
    }

    /// Golden test: `receipt_payload` must produce the EXACT **v2** signed-payload
    /// bytes — `version` + the six settlement facts + the four binding 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 v2 key set, order, and signature so a future
    /// edit cannot silently reorder, rename, or swap a covered field. Recomputing
    /// inline (rather than hardcoding bytes) keeps the golden stable across
    /// `serde_json` feature unification (e.g. `preserve_order`), which only flips
    /// key order — what matters is that both forms agree under whatever ordering
    /// is in effect.
    #[test]
    fn receipt_payload_pins_v2_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",
        );

        // The exact v2 JSON the implementation must build, recomputed here.
        let expected_canonical = serde_json::json!({
            "version": RECEIPT_VERSION,
            "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,
        });
        let expected_sig = signer.sign(expected_canonical.to_string().as_bytes());
        let expected_pk = signer.public_key_bytes();
        let expected_full = serde_json::json!({
            "version": RECEIPT_VERSION,
            "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,
            "signed_by": hex_lower(&expected_pk),
            "signature_hex": hex_lower(&expected_sig),
        })
        .to_string();

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

        assert_eq!(
            String::from_utf8(payload).unwrap(),
            expected_full,
            "v2 receipt payload must be byte-identical to the pinned v2 shape"
        );
        assert_eq!(
            sig, expected_sig,
            "signature must match the pinned v2 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`] 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` 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 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",
        };

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

        // 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).expect("verifies");
        let verified_canonical = 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,
        }
        .canonical_json()
        .to_string()
        .into_bytes();
        assert_eq!(
            verified_canonical, canonical_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 (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",
            },
            &signer,
        );
        let verified =
            verify_signed_receipt(&payload).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");
    }

    #[test]
    fn tampered_receipt_fails_verification() {
        let signer = ApprovalSigner::from_seed(99);
        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",
            },
            &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).is_none());
    }

    #[test]
    fn tampered_receipt_binding_field_fails_verification() {
        let signer = ApprovalSigner::from_seed(99);
        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",
            },
            &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).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).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 canonical = serde_json::json!({
            "reference": "tx-old",
            "amount": "0.02",
            "currency": "USDC",
            "recipient": "0xr",
            "method": "tempo",
            "timestamp": "2026-06-01T00:00:00Z",
        });
        let sig = signer.sign(canonical.to_string().as_bytes());
        let pk = signer.public_key_bytes();
        let v1 = serde_json::json!({
            "reference": "tx-old",
            "amount": "0.02",
            "currency": "USDC",
            "recipient": "0xr",
            "method": "tempo",
            "timestamp": "2026-06-01T00:00:00Z",
            "signed_by": hex_lower(&pk),
            "signature_hex": hex_lower(&sig),
        })
        .to_string()
        .into_bytes();

        let verified = verify_signed_receipt(&v1).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());
    }

    /// 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.
    /// Only an absent `version` (⇒ 1) or the exact current version is accepted.
    #[test]
    fn injected_version_on_v1_signed_receipt_fails() {
        let signer = ApprovalSigner::from_seed(99);
        let canonical = serde_json::json!({
            "reference": "tx-old",
            "amount": "0.02",
            "currency": "USDC",
            "recipient": "0xr",
            "method": "tempo",
            "timestamp": "2026-06-01T00:00:00Z",
        });
        let sig = signer.sign(canonical.to_string().as_bytes());
        let pk = signer.public_key_bytes();
        let mut full = canonical;
        full["signed_by"] = Value::String(hex_lower(&pk));
        full["signature_hex"] = Value::String(hex_lower(&sig));

        // A claimed future version, an explicit "1", and a non-integer are all
        // refused outright (fail closed) — never verified against a guessed
        // canonical.
        for injected in [
            Value::from(7_u64),
            Value::from(1_u64),
            Value::String("2".to_owned()),
        ] {
            let mut tampered = full.clone();
            tampered["version"] = injected;
            assert!(
                verify_signed_receipt(&tampered.to_string().into_bytes()).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(&full.to_string().into_bytes()).is_some());
    }
}