asupersync 0.3.4

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Graded/quantitative types for obligations and budgets.
//!
//! Explores an opt-in type layer where obligations carry resource annotations,
//! making "no obligation leaks" a type error (or at minimum a `#[must_use]`
//! warning + panic-on-drop) for code using the graded surface.
//!
//! # Typing Judgment Sketch
//!
//! The graded type discipline assigns resource weights to obligation values:
//!
//! ```text
//! Γ ⊢ reserve(K)    : Obligation<K>     [creates 1 unit of resource K]
//! Γ, x: Obligation<K> ⊢ commit(x) : ()  [consumes 1 unit of resource K]
//! Γ, x: Obligation<K> ⊢ abort(x)  : ()  [consumes 1 unit of resource K]
//!
//! // Scope rule: exit with 0 outstanding obligations
//! Γ ⊢ scope(body) : τ    iff    Γ_exit has no live Obligation<K> values
//! ```
//!
//! In a fully linear type system, forgetting to consume an obligation would
//! be a *type error*. Rust is affine (values may be dropped silently), not
//! linear. We approximate linearity with:
//!
//! 1. **`#[must_use]`**: Compiler warns if an `Obligation<K>` is ignored.
//! 2. **Drop bomb**: `Drop` impl panics if the obligation was not resolved.
//!    In debug/lab mode this catches leaks immediately. In release mode,
//!    this can be replaced with a log+metric.
//! 3. **API shape**: The only ways to disarm the drop bomb are `commit()`,
//!    `abort()`, or `into_raw()` (escape hatch for FFI/tests).
//!
//! # Resource Semiring
//!
//! The graded annotation forms a semiring over obligation counts:
//!
//! ```text
//! (ℕ, +, 0, ×, 1)
//! ```
//!
//! - `0`: no obligation held (empty)
//! - `1`: one obligation held (reserve)
//! - `+`: sequential composition (obligations accumulate)
//! - `×`: parallel composition (obligations from both branches)
//!
//! # Example
//!
//! ```
//! use asupersync::obligation::graded::{GradedObligation, Resolution};
//! use asupersync::record::ObligationKind;
//!
//! // Correct usage: obligation is resolved before scope exit.
//! let ob = GradedObligation::reserve(ObligationKind::SendPermit, "test permit");
//! ob.resolve(Resolution::Commit);
//!
//! // This would panic on drop:
//! // let leaked = GradedObligation::reserve(ObligationKind::Ack, "leaked");
//! // drop(leaked); // PANIC: obligation leaked!
//! ```

use crate::record::{ObligationKind, ObligationState};
use crate::types::{RegionId, id::next_bootstrap_region_id};
use std::fmt;
use std::marker::PhantomData;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicU64, Ordering};

// ============================================================================
// Panic-Safe Leak Tracker
// ============================================================================

/// Tracks obligation leaks that occur during panic unwinding.
///
/// This preserves the "no obligation leaks" invariant even when obligations
/// are dropped during panic unwinding, where we cannot panic again.
struct PanicLeakTracker {
    /// Total number of obligations leaked during panic unwinding.
    leak_count: AtomicU64,
}

impl PanicLeakTracker {
    const fn new() -> Self {
        Self {
            leak_count: AtomicU64::new(0),
        }
    }

    /// Record an obligation leak during panic unwinding.
    ///
    /// This is panic-safe and will not panic even if called during unwinding.
    fn record_panic_leak(&self) {
        self.leak_count.fetch_add(1, Ordering::Relaxed);
    }

    /// Get the total number of panic leaks recorded.
    pub fn leak_count(&self) -> u64 {
        self.leak_count.load(Ordering::Relaxed)
    }
}

/// Global panic leak tracker instance.
static PANIC_LEAK_TRACKER: LazyLock<PanicLeakTracker> = LazyLock::new(PanicLeakTracker::new);

/// Returns the number of obligations that have leaked during panic unwinding.
///
/// This is useful for tests and monitoring to ensure that the "no obligation leaks"
/// invariant is maintained even during exceptional circumstances.
pub fn panic_leak_count() -> u64 {
    PANIC_LEAK_TRACKER.leak_count()
}

// ============================================================================
// Resolution
// ============================================================================

/// How an obligation was resolved.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Resolution {
    /// Obligation was committed (effect took place).
    Commit,
    /// Obligation was aborted (clean cancellation).
    Abort,
}

impl fmt::Display for Resolution {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Commit => f.write_str("commit"),
            Self::Abort => f.write_str("abort"),
        }
    }
}

impl Resolution {
    /// Returns the matching runtime obligation record state.
    #[inline]
    #[must_use]
    pub const fn obligation_state(self) -> ObligationState {
        match self {
            Self::Commit => ObligationState::Committed,
            Self::Abort => ObligationState::Aborted,
        }
    }
}

// ============================================================================
// GradedObligation
// ============================================================================

/// A graded obligation value that must be resolved before being dropped.
///
/// This type approximates a linear type in Rust's affine type system.
/// It uses `#[must_use]` to warn at compile time if the value is unused,
/// and panics on `Drop` if the obligation was not resolved.
///
/// # Graded Semantics
///
/// Each `GradedObligation` represents exactly 1 unit of resource.
/// Resolving it (via `resolve()`) consumes the resource and returns
/// a `Resolved<K>` proof token. Dropping without resolving panics.
///
/// # Type-Level Encoding
///
/// In a fully graded type system, we would write:
/// ```text
/// reserve : () →₁ Obligation<K>
/// commit  : Obligation<K> →₁ ()
/// abort   : Obligation<K> →₁ ()
/// ```
/// where `→₁` means "consumes exactly 1 unit". In Rust, we approximate
/// this with move semantics (value is consumed) and Drop (leak detection).
#[must_use = "obligations must be resolved (commit or abort); dropping leaks the obligation"]
pub struct GradedObligation {
    /// The kind of obligation.
    kind: ObligationKind,
    /// Description for diagnostics.
    description: String,
    /// Whether the obligation has been resolved.
    resolved: bool,
}

impl GradedObligation {
    /// Reserve a new obligation of the given kind.
    ///
    /// This is the `reserve` typing rule:
    /// ```text
    /// Γ ⊢ reserve(K, desc) : Obligation<K>     [+1 resource]
    /// ```
    pub fn reserve(kind: ObligationKind, description: impl Into<String>) -> Self {
        Self {
            kind,
            description: description.into(),
            resolved: false,
        }
    }

    /// Resolve the obligation (commit or abort), consuming the graded value.
    ///
    /// This is the `commit`/`abort` typing rule:
    /// ```text
    /// Γ, x: Obligation<K> ⊢ resolve(x, r) : Proof<K>     [-1 resource]
    /// ```
    ///
    /// Returns a [`ResolvedProof`] token that proves the obligation was handled.
    #[must_use]
    pub fn resolve(mut self, resolution: Resolution) -> ResolvedProof {
        self.resolved = true;
        ResolvedProof {
            kind: self.kind,
            resolution,
        }
    }

    /// Returns the obligation kind.
    #[must_use]
    pub fn kind(&self) -> ObligationKind {
        self.kind
    }

    /// Returns the description.
    #[must_use]
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Returns whether the obligation has been resolved.
    #[must_use]
    pub fn is_resolved(&self) -> bool {
        self.resolved
    }

    /// Escape hatch: disarm the drop bomb without resolving.
    ///
    /// Use only for FFI boundaries, test harnesses, or migration paths.
    /// This intentionally leaks the obligation.
    #[must_use]
    pub fn into_raw(mut self) -> RawObligation {
        self.resolved = true; // Disarm the bomb.
        RawObligation {
            kind: self.kind,
            description: std::mem::take(&mut self.description),
        }
    }
}

impl Drop for GradedObligation {
    fn drop(&mut self) {
        if !self.resolved {
            if std::thread::panicking() {
                // During panic unwinding, we cannot panic again, but we must still
                // track the obligation leak to maintain the "no obligation leaks" invariant.
                // This preserves leak detection even during panic unwinding.
                PANIC_LEAK_TRACKER.record_panic_leak();
                return;
            }
            // In lab/debug mode: panic to surface the bug immediately.
            // In production: this could log+metric instead of panicking.
            panic!(
                "OBLIGATION LEAKED: {} obligation '{}' was dropped without being resolved. \
                 Call .resolve(Resolution::Commit) or .resolve(Resolution::Abort) before scope exit.",
                self.kind, self.description,
            );
        }
    }
}

impl fmt::Debug for GradedObligation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GradedObligation")
            .field("kind", &self.kind)
            .field("description", &self.description)
            .field("resolved", &self.resolved)
            .finish()
    }
}

// ============================================================================
// ResolvedProof
// ============================================================================

/// Proof token that an obligation was resolved.
///
/// Created by [`GradedObligation::resolve`]. This is a zero-cost witness
/// value: it proves at the type level that the obligation was handled.
/// The fields are intentionally opaque so callers cannot forge resolution
/// proofs without actually consuming an obligation.
///
/// In a dependent type system, this would be:
/// ```text
/// ResolvedProof<K, R> : Type    where R ∈ {Commit, Abort}
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct ResolvedProof {
    /// The kind of obligation that was resolved.
    kind: ObligationKind,
    /// How it was resolved.
    resolution: Resolution,
}

impl ResolvedProof {
    /// Returns the obligation kind proven to be resolved.
    #[must_use]
    pub fn kind(&self) -> ObligationKind {
        self.kind
    }

    /// Returns how the obligation was resolved.
    #[must_use]
    pub fn resolution(&self) -> Resolution {
        self.resolution
    }

    /// Returns the matching runtime obligation record state.
    #[must_use]
    pub fn obligation_state(&self) -> ObligationState {
        self.resolution.obligation_state()
    }
}

impl fmt::Display for ResolvedProof {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "resolved({}, {})", self.kind, self.resolution)
    }
}

// ============================================================================
// RawObligation
// ============================================================================

/// An obligation that was disarmed via [`GradedObligation::into_raw`].
///
/// Holds the metadata but not the drop bomb. Used for FFI, migration,
/// and test harness escape paths.
#[derive(Debug, Clone)]
pub struct RawObligation {
    /// The kind of obligation.
    pub kind: ObligationKind,
    /// Description.
    pub description: String,
}

// ============================================================================
// GradedScope
// ============================================================================

/// A scope that tracks obligation counts and verifies zero-leak at exit.
///
/// Models the scope typing rule:
/// ```text
/// Γ ⊢ scope(body) : τ    iff    Γ_exit has 0 outstanding obligations
/// ```
///
/// The scope tracks how many obligations have been reserved and resolved.
/// At scope exit (via `close()`), it verifies the counts match.
pub struct GradedScope {
    /// Label for diagnostics.
    label: String,
    /// Number of obligations reserved.
    reserved: u32,
    /// Number of obligations resolved.
    resolved: u32,
    /// Whether the scope has been explicitly closed.
    closed: bool,
}

impl GradedScope {
    /// Open a new graded scope.
    #[must_use]
    pub fn open(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            reserved: 0,
            resolved: 0,
            closed: false,
        }
    }

    /// Record a reservation (obligation created in this scope).
    pub fn on_reserve(&mut self) {
        self.reserved = self
            .reserved
            .checked_add(1)
            .expect("on_reserve overflowed outstanding obligation count");
    }

    /// Record a resolution (obligation resolved in this scope).
    ///
    /// # Panics
    ///
    /// Panics if called more times than `on_reserve`, which would indicate
    /// a double-resolution bug.
    pub fn on_resolve(&mut self) {
        assert!(
            self.resolved < self.reserved,
            "on_resolve called more times than on_reserve ({} >= {})",
            self.resolved,
            self.reserved,
        );
        self.resolved = self
            .resolved
            .checked_add(1)
            .expect("on_resolve overflowed resolved obligation count");
    }

    /// Returns the number of outstanding (unresolved) obligations.
    #[must_use]
    pub fn outstanding(&self) -> u32 {
        self.reserved.saturating_sub(self.resolved)
    }

    /// Close the scope, verifying zero outstanding obligations.
    ///
    /// # Errors
    ///
    /// Returns `Err` with the number of leaked obligations if any remain.
    #[must_use = "close() must be checked; Err indicates leaked obligations"]
    pub fn close(mut self) -> Result<ScopeProof, ScopeLeakError> {
        let outstanding = self.outstanding();
        if outstanding == 0 {
            self.closed = true;
            Ok(ScopeProof {
                label: self.label.clone(),
                total_reserved: self.reserved,
                total_resolved: self.resolved,
            })
        } else {
            let err = ScopeLeakError {
                label: self.label.clone(),
                outstanding,
                reserved: self.reserved,
                resolved: self.resolved,
            };
            // Mark closed so Drop doesn't panic — the caller explicitly
            // called close() and received the error, so they are aware of
            // the leak. Drop panics are reserved for implicit drops where
            // close() was never called.
            self.closed = true;
            Err(err)
        }
    }

    /// Returns the scope label.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }
}

impl Drop for GradedScope {
    fn drop(&mut self) {
        if !self.closed && self.outstanding() > 0 {
            if std::thread::panicking() {
                return;
            }
            panic!(
                "SCOPE LEAKED: scope '{}' dropped with {} outstanding obligation(s) \
                 ({} reserved, {} resolved). Call .close() before scope exit.",
                self.label,
                self.outstanding(),
                self.reserved,
                self.resolved,
            );
        }
    }
}

impl fmt::Debug for GradedScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GradedScope")
            .field("label", &self.label)
            .field("reserved", &self.reserved)
            .field("resolved", &self.resolved)
            .field("outstanding", &self.outstanding())
            .field("closed", &self.closed)
            .finish()
    }
}

// ============================================================================
// ScopeProof / ScopeLeakError
// ============================================================================

/// Proof that a scope was closed with zero outstanding obligations.
///
/// This witness is intentionally opaque so callers cannot fabricate a clean
/// closure proof without running the scope accounting.
#[derive(Debug, PartialEq, Eq)]
pub struct ScopeProof {
    /// Scope label.
    label: String,
    /// Total obligations reserved.
    total_reserved: u32,
    /// Total obligations resolved.
    total_resolved: u32,
}

impl ScopeProof {
    /// Returns the label of the cleanly closed scope.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Returns how many obligations were reserved in the scope.
    #[must_use]
    pub fn total_reserved(&self) -> u32 {
        self.total_reserved
    }

    /// Returns how many obligations were resolved in the scope.
    #[must_use]
    pub fn total_resolved(&self) -> u32 {
        self.total_resolved
    }
}

impl fmt::Display for ScopeProof {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "scope '{}' clean: {}/{} resolved",
            self.label, self.total_resolved, self.total_reserved
        )
    }
}

/// Error when a scope is closed with outstanding obligations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopeLeakError {
    /// Scope label.
    pub label: String,
    /// Number of leaked obligations.
    pub outstanding: u32,
    /// Total reserved.
    pub reserved: u32,
    /// Total resolved.
    pub resolved: u32,
}

impl fmt::Display for ScopeLeakError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "scope '{}' leaked: {} outstanding ({} reserved, {} resolved)",
            self.label, self.outstanding, self.reserved, self.resolved,
        )
    }
}

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

// ============================================================================
// Toy API demonstration
// ============================================================================

/// Demonstrates the graded obligation API with a toy channel-like pattern.
///
/// This module shows how the graded type discipline makes obligation leaks
/// into compile warnings or runtime panics, while correct usage compiles
/// and runs cleanly.
pub mod toy_api {
    use super::{GradedObligation, ObligationKind, Resolution, ResolvedProof};

    fn assert_send_permit(permit: &GradedObligation, operation: &str) {
        assert_eq!(
            permit.kind(),
            ObligationKind::SendPermit,
            "{operation} requires a SendPermit obligation (got {})",
            permit.kind()
        );
    }

    /// A toy channel that uses graded obligations for the two-phase send.
    pub struct ToyChannel {
        capacity: usize,
        messages: Vec<String>,
        reserved_permits: usize,
    }

    impl ToyChannel {
        /// Creates a new channel with the given capacity.
        #[must_use]
        pub fn new(capacity: usize) -> Self {
            Self {
                capacity,
                messages: Vec::new(),
                reserved_permits: 0,
            }
        }

        #[cfg(test)]
        pub(super) fn from_state(
            capacity: usize,
            messages: Vec<String>,
            reserved_permits: usize,
        ) -> Self {
            Self {
                capacity,
                messages,
                reserved_permits,
            }
        }

        /// Reserve a send permit.
        ///
        /// Returns a [`GradedObligation`] that must be resolved:
        /// - `resolve(Commit)` — message is sent
        /// - `resolve(Abort)` — permit is cancelled
        ///
        /// Dropping the permit without resolving panics.
        #[must_use]
        pub fn reserve_send(&mut self) -> Option<GradedObligation> {
            let occupied = self
                .messages
                .len()
                .checked_add(self.reserved_permits)
                .expect("toy channel occupancy overflowed");
            if occupied < self.capacity {
                self.reserved_permits = self
                    .reserved_permits
                    .checked_add(1)
                    .expect("toy channel reserved permit count overflowed");
                Some(GradedObligation::reserve(
                    ObligationKind::SendPermit,
                    "toy channel send permit",
                ))
            } else {
                None
            }
        }

        /// Commit a send: consumes the permit and enqueues the message.
        pub fn commit_send(&mut self, permit: GradedObligation, message: String) -> ResolvedProof {
            assert_send_permit(&permit, "commit_send");
            self.reserved_permits = self
                .reserved_permits
                .checked_sub(1)
                .expect("commit_send requires an outstanding reservation");
            self.messages.push(message);
            permit.resolve(Resolution::Commit)
        }

        /// Abort a send: cancels the permit without sending.
        #[must_use]
        pub fn abort_send(&mut self, permit: GradedObligation) -> ResolvedProof {
            assert_send_permit(&permit, "abort_send");
            self.reserved_permits = self
                .reserved_permits
                .checked_sub(1)
                .expect("abort_send requires an outstanding reservation");
            permit.resolve(Resolution::Abort)
        }

        /// Returns the number of messages in the channel.
        #[must_use]
        pub fn len(&self) -> usize {
            self.messages.len()
        }

        /// Returns true if the channel is empty.
        #[must_use]
        pub fn is_empty(&self) -> bool {
            self.messages.is_empty()
        }
    }
}

// ============================================================================
// Sealed trait pattern (prevents external impls of TokenKind)
// ============================================================================

mod sealed {
    pub trait Sealed {}
}

// ============================================================================
// TokenKind trait + kind marker enums
// ============================================================================

/// Trait mapping a zero-sized kind marker to its [`ObligationKind`] variant.
///
/// Sealed: cannot be implemented outside this crate.
pub trait TokenKind: sealed::Sealed {
    /// Returns the [`ObligationKind`] corresponding to this marker.
    fn obligation_kind() -> ObligationKind;
}

/// Error returned when dynamic obligation metadata does not match a typed token.
///
/// This is the migration bridge from existing runtime/ledger surfaces that
/// still carry [`ObligationKind`] dynamically into the stronger typestate API.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TypedObligationKindError {
    /// Static obligation kind required by the requested token type.
    pub expected: ObligationKind,
    /// Dynamic obligation kind supplied by the caller.
    pub actual: ObligationKind,
}

impl fmt::Display for TypedObligationKindError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "typed obligation kind mismatch: expected {}, got {}",
            self.expected, self.actual
        )
    }
}

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

/// Contract row describing the typed obligation bridge evidence surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TypedObligationBridgeContract {
    /// Bead that introduced the bridge contract.
    pub bead_id: &'static str,
    /// Protocol family strengthened by the typed bridge.
    pub protocol_family: &'static str,
    /// Typed API entrypoint that materializes a static obligation token.
    pub typed_entrypoint: &'static str,
    /// Dynamic fallback path that remains authoritative during migration.
    pub dynamic_fallback: &'static str,
    /// Compile-fail proof surface for invalid typestate transitions.
    pub compile_fail_surface: &'static str,
    /// Focused reproduction command for the contract evidence.
    pub replay_command: &'static str,
    /// Stable invariant checklist covered by the focused tests.
    pub invariants: &'static [&'static str],
}

const TYPED_OBLIGATION_BRIDGE_INVARIANTS: &[&str] = &[
    "matching dynamic kind creates a typed token",
    "mismatched dynamic kind does not arm a token",
    "scope accounting increments only after kind proof succeeds",
    "abort cleanup balances a scoped lease token",
    "committed proof has no abort transition",
];

/// Returns the contract row for the dynamic-to-typed obligation bridge.
#[must_use]
pub const fn typed_obligation_bridge_contract() -> TypedObligationBridgeContract {
    TypedObligationBridgeContract {
        bead_id: "asupersync-d87ytw.13",
        protocol_family: "send-permit/ack/lease graded obligations",
        typed_entrypoint: "asupersync::obligation::graded::ObligationToken::try_reserve_kind",
        dynamic_fallback: "asupersync::record::ObligationKind",
        compile_fail_surface: "src/obligation/graded.rs::ObligationToken commit-then-abort doctest",
        replay_command: "rch exec -- env CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 RUSTFLAGS='-C debuginfo=0' CARGO_TARGET_DIR=${TMPDIR:-/tmp}/rch_target_asupersync_graded_bridge cargo test -p asupersync --lib dynamic_kind_bridge --features test-internals -- --nocapture",
        invariants: TYPED_OBLIGATION_BRIDGE_INVARIANTS,
    }
}

/// Marker type for [`ObligationKind::SendPermit`].
#[derive(Debug)]
pub enum SendPermit {}
impl sealed::Sealed for SendPermit {}
impl TokenKind for SendPermit {
    fn obligation_kind() -> ObligationKind {
        ObligationKind::SendPermit
    }
}

/// Marker type for [`ObligationKind::Ack`].
#[derive(Debug)]
pub enum AckKind {}
impl sealed::Sealed for AckKind {}
impl TokenKind for AckKind {
    fn obligation_kind() -> ObligationKind {
        ObligationKind::Ack
    }
}

/// Marker type for [`ObligationKind::Lease`].
#[derive(Debug, PartialEq, Eq)]
pub enum LeaseKind {}
impl sealed::Sealed for LeaseKind {}
impl TokenKind for LeaseKind {
    fn obligation_kind() -> ObligationKind {
        ObligationKind::Lease
    }
}

/// Marker type for [`ObligationKind::IoOp`].
#[derive(Debug)]
pub enum IoOpKind {}
impl sealed::Sealed for IoOpKind {}
impl TokenKind for IoOpKind {
    fn obligation_kind() -> ObligationKind {
        ObligationKind::IoOp
    }
}

/// Marker type for [`ObligationKind::SemaphorePermit`].
#[derive(Debug)]
pub enum SemaphorePermitKind {}
impl sealed::Sealed for SemaphorePermitKind {}
impl TokenKind for SemaphorePermitKind {
    fn obligation_kind() -> ObligationKind {
        ObligationKind::SemaphorePermit
    }
}

// ============================================================================
// ObligationToken<K> — typestate linear token
// ============================================================================

/// A typestate-encoded obligation token that must be consumed via
/// [`commit`](Self::commit) or [`abort`](Self::abort).
///
/// Dropping without consuming panics ("drop bomb"), approximating a linear
/// type in Rust's affine type system.
///
/// Invalid transitions stay unrepresentable: after a token is committed, the
/// resulting proof has no `abort` transition.
///
/// ```compile_fail
/// use asupersync::obligation::graded::{ObligationToken, SendPermitToken};
///
/// let token: SendPermitToken = ObligationToken::reserve_test("send");
/// let committed = token.commit();
/// let _late_abort = committed.abort();
/// ```
#[must_use = "obligation tokens must be consumed via commit() or abort()"]
pub struct ObligationToken<K: TokenKind> {
    description: String,
    region: RegionId,
    armed: bool,
    _kind: PhantomData<K>,
}

impl<K: TokenKind> ObligationToken<K> {
    /// Reserve a new obligation token with the given description and region context.
    ///
    /// This method ensures the obligation is properly scoped to a region, preventing
    /// obligation leaks that could occur if tokens outlive their intended scope.
    ///
    /// # Region Validation
    ///
    /// The region must be valid and active. Creating obligations outside of proper
    /// region context violates the "no obligation leaks" invariant.
    #[allow(clippy::double_must_use)]
    #[must_use = "obligation tokens must be committed or aborted"]
    pub fn reserve(description: impl Into<String>, region: RegionId) -> Self {
        let description = description.into();
        // Validate that the region is not the root region (which should not hold obligations)
        // and that we're in a valid execution context. The root region typically has
        // index 0, generation 0.
        assert!(
            region.as_u64() != 0,
            "Cannot create obligation token in root region: obligations must be \
             scoped to non-root regions to prevent leaks. Description: {description}"
        );

        Self {
            description,
            region,
            armed: true,
            _kind: PhantomData,
        }
    }

    /// Returns the region this obligation is scoped to.
    #[must_use]
    pub fn region(&self) -> RegionId {
        self.region
    }

    /// Reserve a token for testing with a synthetic test region.
    ///
    /// This method should only be used in tests where proper region context
    /// is not available. Production code should use `reserve()` with a real
    /// region from the current Cx.
    #[cfg(any(test, feature = "test-internals"))]
    #[must_use = "obligation tokens must be committed or aborted"]
    pub fn reserve_test(description: impl Into<String>) -> Self {
        Self::reserve(description, RegionId::new_ephemeral())
    }

    /// Reserve a typed token from dynamic obligation metadata.
    ///
    /// This preserves the existing dynamic [`ObligationKind`] source of truth
    /// while refusing to manufacture a static token for the wrong protocol
    /// family. On mismatch no token is created, so no drop bomb is armed.
    ///
    /// # Errors
    ///
    /// Returns [`TypedObligationKindError`] when `kind` differs from `K`.
    pub fn try_reserve_kind(
        kind: ObligationKind,
        description: impl Into<String>,
        region: RegionId,
    ) -> Result<Self, TypedObligationKindError> {
        let expected = K::obligation_kind();
        if kind == expected {
            Ok(Self::reserve(description, region))
        } else {
            Err(TypedObligationKindError {
                expected,
                actual: kind,
            })
        }
    }

    /// Commit the obligation, consuming the token and returning a
    /// [`CommittedProof`].
    #[must_use]
    pub fn commit(mut self) -> CommittedProof<K> {
        self.armed = false;
        CommittedProof { _kind: PhantomData }
    }

    /// Abort the obligation, consuming the token and returning an
    /// [`AbortedProof`].
    #[must_use]
    pub fn abort(mut self) -> AbortedProof<K> {
        self.armed = false;
        AbortedProof { _kind: PhantomData }
    }

    /// Escape hatch: disarm the drop bomb and convert to a [`RawObligation`].
    ///
    /// Use only for FFI boundaries, test harnesses, or migration paths.
    #[must_use]
    pub fn into_raw(mut self) -> RawObligation {
        self.armed = false;
        let description = std::mem::take(&mut self.description);
        RawObligation {
            kind: K::obligation_kind(),
            description,
        }
    }

    /// Returns the description.
    #[must_use]
    pub fn description(&self) -> &str {
        &self.description
    }
}

impl<K: TokenKind> Drop for ObligationToken<K> {
    fn drop(&mut self) {
        if self.armed {
            if std::thread::panicking() {
                return;
            }
            panic!(
                // ubs:ignore - intentional panic on leak in debug build
                "OBLIGATION TOKEN LEAKED: {} token '{}' was dropped without being consumed. \
                 Call .commit() or .abort() before scope exit.",
                K::obligation_kind(),
                self.description,
            );
        }
    }
}

impl<K: TokenKind> fmt::Debug for ObligationToken<K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ObligationToken")
            .field("kind", &K::obligation_kind())
            .field("description", &self.description)
            .field("armed", &self.armed)
            .finish()
    }
}

// ============================================================================
// CommittedProof<K> / AbortedProof<K> — ZST witnesses
// ============================================================================

/// Proof that an [`ObligationToken`] was committed.
///
/// Commit proofs are affine witnesses: they are intentionally non-cloneable
/// and can only be constructed by consuming a live token.
#[derive(Debug, PartialEq, Eq)]
pub struct CommittedProof<K: TokenKind> {
    _kind: PhantomData<K>,
}

impl<K: TokenKind> CommittedProof<K> {
    /// Bridge to the existing [`ResolvedProof`] system.
    #[must_use]
    pub fn into_resolved_proof(self) -> ResolvedProof {
        ResolvedProof {
            kind: K::obligation_kind(),
            resolution: Resolution::Commit,
        }
    }

    /// Returns the obligation kind.
    #[must_use]
    pub fn kind(&self) -> ObligationKind {
        K::obligation_kind()
    }
}

/// Proof that an [`ObligationToken`] was aborted.
///
/// Abort proofs are affine witnesses: they are intentionally non-cloneable
/// and can only be constructed by consuming a live token.
#[derive(Debug, PartialEq, Eq)]
pub struct AbortedProof<K: TokenKind> {
    _kind: PhantomData<K>,
}

impl<K: TokenKind> AbortedProof<K> {
    /// Bridge to the existing [`ResolvedProof`] system.
    #[must_use]
    pub fn into_resolved_proof(self) -> ResolvedProof {
        ResolvedProof {
            kind: K::obligation_kind(),
            resolution: Resolution::Abort,
        }
    }

    /// Returns the obligation kind.
    #[must_use]
    pub fn kind(&self) -> ObligationKind {
        K::obligation_kind()
    }
}

// ============================================================================
// Type aliases (ergonomic names)
// ============================================================================

/// Token for a send-permit obligation.
pub type SendPermitToken = ObligationToken<SendPermit>;
/// Token for an acknowledgement obligation.
pub type AckToken = ObligationToken<AckKind>;
/// Token for a lease obligation.
pub type LeaseToken = ObligationToken<LeaseKind>;
/// Token for an I/O operation obligation.
pub type IoOpToken = ObligationToken<IoOpKind>;

// ============================================================================
// GradedScope convenience methods for tokens
// ============================================================================

impl GradedScope {
    /// Reserve a typed obligation token, recording it in this scope.
    #[allow(clippy::double_must_use)]
    #[must_use]
    pub fn reserve_token<K: TokenKind>(
        &mut self,
        description: impl Into<String>,
    ) -> ObligationToken<K> {
        self.on_reserve();
        ObligationToken::reserve(description, next_bootstrap_region_id())
    }

    /// Reserve a typed token from dynamic obligation metadata and record it.
    ///
    /// Scope accounting is updated only after the dynamic kind matches the
    /// requested static token kind. A mismatch therefore cannot create a
    /// synthetic outstanding obligation in the graded scope.
    ///
    /// # Errors
    ///
    /// Returns [`TypedObligationKindError`] when `kind` differs from `K`.
    pub fn try_reserve_token_kind<K: TokenKind>(
        &mut self,
        kind: ObligationKind,
        description: impl Into<String>,
    ) -> Result<ObligationToken<K>, TypedObligationKindError> {
        let token =
            ObligationToken::try_reserve_kind(kind, description, next_bootstrap_region_id())?;
        self.on_reserve();
        Ok(token)
    }

    /// Commit a typed obligation token, recording the resolution in this scope.
    #[must_use]
    pub fn resolve_commit<K: TokenKind>(&mut self, token: ObligationToken<K>) -> CommittedProof<K> {
        self.on_resolve();
        token.commit()
    }

    /// Abort a typed obligation token, recording the resolution in this scope.
    #[must_use]
    pub fn resolve_abort<K: TokenKind>(&mut self, token: ObligationToken<K>) -> AbortedProof<K> {
        self.on_resolve();
        token.abort()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;
    use crate::record::ObligationKind;

    fn init_test(name: &str) {
        crate::test_utils::init_test_logging();
        crate::test_phase!(name);
    }

    // ---- GradedObligation: correct usage -----------------------------------

    #[test]
    fn obligation_commit_clean() {
        init_test("obligation_commit_clean");
        let ob = GradedObligation::reserve(ObligationKind::SendPermit, "test");
        let kind = ob.kind();
        crate::assert_with_log!(
            kind == ObligationKind::SendPermit,
            "kind",
            ObligationKind::SendPermit,
            kind
        );
        let is_resolved = ob.is_resolved();
        crate::assert_with_log!(!is_resolved, "not yet resolved", false, is_resolved);

        let proof = ob.resolve(Resolution::Commit);
        let r = proof.resolution();
        crate::assert_with_log!(r == Resolution::Commit, "resolution", Resolution::Commit, r);
        let state = proof.obligation_state();
        crate::assert_with_log!(
            state == ObligationState::Committed,
            "record state",
            ObligationState::Committed,
            state
        );
        crate::test_complete!("obligation_commit_clean");
    }

    #[test]
    fn obligation_abort_clean() {
        init_test("obligation_abort_clean");
        let ob = GradedObligation::reserve(ObligationKind::Ack, "ack-test");
        let proof = ob.resolve(Resolution::Abort);
        let r = proof.resolution();
        crate::assert_with_log!(r == Resolution::Abort, "resolution", Resolution::Abort, r);
        let state = proof.obligation_state();
        crate::assert_with_log!(
            state == ObligationState::Aborted,
            "record state",
            ObligationState::Aborted,
            state
        );
        crate::test_complete!("obligation_abort_clean");
    }

    #[test]
    fn obligation_into_raw_disarms() {
        init_test("obligation_into_raw_disarms");
        let ob = GradedObligation::reserve(ObligationKind::Lease, "lease-test");
        let raw = ob.into_raw();
        let kind = raw.kind;
        crate::assert_with_log!(
            kind == ObligationKind::Lease,
            "raw kind",
            ObligationKind::Lease,
            kind
        );
        // raw can be dropped without panic.
        drop(raw);
        crate::test_complete!("obligation_into_raw_disarms");
    }

    // ---- GradedObligation: leak detection ----------------------------------

    #[test]
    #[should_panic(expected = "OBLIGATION LEAKED")]
    fn obligation_drop_without_resolve_panics() {
        init_test("obligation_drop_without_resolve_panics");
        let _ob = GradedObligation::reserve(ObligationKind::IoOp, "leaked-io");
        // Dropped without resolving — should panic.
    }

    // ---- GradedScope: correct usage ----------------------------------------

    #[test]
    fn scope_clean_close() {
        init_test("scope_clean_close");
        let mut scope = GradedScope::open("test-scope");
        scope.on_reserve();
        scope.on_resolve();
        let outstanding = scope.outstanding();
        crate::assert_with_log!(outstanding == 0, "outstanding", 0, outstanding);

        let proof = scope.close().expect("scope should close cleanly");
        let label = proof.label();
        crate::assert_with_log!(label == "test-scope", "label", "test-scope", label);
        let total = proof.total_reserved();
        crate::assert_with_log!(total == 1, "reserved", 1, total);
        crate::test_complete!("scope_clean_close");
    }

    #[test]
    fn scope_multiple_obligations() {
        init_test("scope_multiple_obligations");
        let mut scope = GradedScope::open("multi");
        scope.on_reserve();
        scope.on_reserve();
        scope.on_reserve();
        let outstanding = scope.outstanding();
        crate::assert_with_log!(outstanding == 3, "outstanding", 3, outstanding);

        scope.on_resolve();
        scope.on_resolve();
        scope.on_resolve();
        let outstanding = scope.outstanding();
        crate::assert_with_log!(outstanding == 0, "outstanding", 0, outstanding);

        let proof = scope.close().expect("clean");
        let total = proof.total_reserved();
        crate::assert_with_log!(total == 3, "reserved", 3, total);
        crate::test_complete!("scope_multiple_obligations");
    }

    #[test]
    fn scope_close_with_leak_returns_error() {
        init_test("scope_close_with_leak_returns_error");
        let mut scope = GradedScope::open("leaky-scope");
        scope.on_reserve();
        scope.on_reserve();
        scope.on_resolve(); // Only 1 of 2 resolved.

        let err = scope.close().expect_err("should fail");
        let outstanding = err.outstanding;
        crate::assert_with_log!(outstanding == 1, "outstanding", 1, outstanding);
        let label = &err.label;
        crate::assert_with_log!(label == "leaky-scope", "label", "leaky-scope", label);

        // Verify Display impl.
        let msg = format!("{err}");
        let has_leaked = msg.contains("leaked");
        crate::assert_with_log!(has_leaked, "display has leaked", true, has_leaked);
        crate::test_complete!("scope_close_with_leak_returns_error");
    }

    #[test]
    #[should_panic(expected = "SCOPE LEAKED")]
    fn scope_drop_with_outstanding_panics() {
        init_test("scope_drop_with_outstanding_panics");
        let mut scope = GradedScope::open("drop-leak");
        scope.on_reserve();
        // Dropped without closing — should panic because outstanding > 0.
    }

    #[test]
    fn scope_drop_without_close_ok_when_empty() {
        init_test("scope_drop_without_close_ok_when_empty");
        let _scope = GradedScope::open("empty-scope");
        // No obligations reserved, drop is fine.
    }

    // ---- Combined: obligation + scope --------------------------------------

    #[test]
    fn combined_obligation_and_scope() {
        init_test("combined_obligation_and_scope");
        let mut scope = GradedScope::open("combined");

        // Reserve two obligations.
        let ob1 = GradedObligation::reserve(ObligationKind::SendPermit, "send");
        scope.on_reserve();
        let ob2 = GradedObligation::reserve(ObligationKind::Ack, "ack");
        scope.on_reserve();

        let outstanding = scope.outstanding();
        crate::assert_with_log!(outstanding == 2, "outstanding", 2, outstanding);

        // Resolve both.
        let _proof1 = ob1.resolve(Resolution::Commit);
        scope.on_resolve();
        let _proof2 = ob2.resolve(Resolution::Abort);
        scope.on_resolve();

        // Close scope.
        let proof = scope.close().expect("clean close");
        let total = proof.total_reserved();
        crate::assert_with_log!(total == 2, "total reserved", 2, total);
        crate::test_complete!("combined_obligation_and_scope");
    }

    // ---- Toy API -----------------------------------------------------------

    #[test]
    fn toy_channel_correct_usage() {
        init_test("toy_channel_correct_usage");
        let mut ch = toy_api::ToyChannel::new(10);

        // Reserve and commit.
        let permit = ch.reserve_send().expect("should get permit");
        let proof = ch.commit_send(permit, "hello".to_string());
        let resolution = proof.resolution();
        crate::assert_with_log!(
            resolution == Resolution::Commit,
            "commit",
            Resolution::Commit,
            resolution
        );
        let len = ch.len();
        crate::assert_with_log!(len == 1, "len", 1, len);
        crate::test_complete!("toy_channel_correct_usage");
    }

    #[test]
    fn toy_channel_abort_usage() {
        init_test("toy_channel_abort_usage");
        let mut ch = toy_api::ToyChannel::new(10);

        let permit = ch.reserve_send().expect("should get permit");
        let proof = ch.abort_send(permit);
        let resolution = proof.resolution();
        crate::assert_with_log!(
            resolution == Resolution::Abort,
            "abort",
            Resolution::Abort,
            resolution
        );
        let len = ch.len();
        crate::assert_with_log!(len == 0, "len", 0, len);
        crate::test_complete!("toy_channel_abort_usage");
    }

    #[test]
    #[should_panic(expected = "OBLIGATION LEAKED")]
    fn toy_channel_leaked_permit_panics() {
        init_test("toy_channel_leaked_permit_panics");
        let mut ch = toy_api::ToyChannel::new(10);
        let _permit = ch.reserve_send().expect("should get permit");
        // Dropped without commit or abort — panics.
    }

    #[test]
    fn toy_channel_full_returns_none() {
        init_test("toy_channel_full_returns_none");
        let mut ch = toy_api::ToyChannel::new(0);
        let permit = ch.reserve_send();
        let is_none = permit.is_none();
        crate::assert_with_log!(is_none, "full", true, is_none);
        crate::test_complete!("toy_channel_full_returns_none");
    }

    #[test]
    fn toy_channel_reservation_tracks_outstanding_capacity() {
        init_test("toy_channel_reservation_tracks_outstanding_capacity");
        let mut ch = toy_api::ToyChannel::new(1);

        let first = ch.reserve_send().expect("first permit should succeed");
        let second = ch.reserve_send();
        crate::assert_with_log!(
            second.is_none(),
            "second permit blocked by outstanding reservation",
            true,
            second.is_none()
        );

        let _proof = ch.abort_send(first);
        let retry = ch.reserve_send();
        let retry_present = retry.is_some();
        crate::assert_with_log!(
            retry_present,
            "capacity should reopen after abort",
            true,
            retry_present
        );
        let retry = retry.expect("retry permit should be present after abort");
        let _retry_proof = ch.abort_send(retry);
        crate::test_complete!("toy_channel_reservation_tracks_outstanding_capacity");
    }

    #[test]
    fn toy_channel_commit_rejects_wrong_obligation_kind() {
        init_test("toy_channel_commit_rejects_wrong_obligation_kind");
        let mut ch = toy_api::ToyChannel::from_state(1, Vec::new(), 1);
        let forged = GradedObligation::reserve(ObligationKind::Ack, "forged ack");

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            ch.commit_send(forged, "hello".to_string())
        }));

        crate::assert_with_log!(
            result.is_err(),
            "wrong kind rejected",
            true,
            result.is_err()
        );
        crate::assert_with_log!(ch.is_empty(), "no message enqueued", true, ch.is_empty());
        let retry = ch.reserve_send();
        crate::assert_with_log!(
            retry.is_none(),
            "reservation count preserved after rejected commit",
            true,
            retry.is_none()
        );
        crate::test_complete!("toy_channel_commit_rejects_wrong_obligation_kind");
    }

    #[test]
    fn toy_channel_abort_rejects_wrong_obligation_kind() {
        init_test("toy_channel_abort_rejects_wrong_obligation_kind");
        let mut ch = toy_api::ToyChannel::from_state(1, Vec::new(), 1);
        let forged = GradedObligation::reserve(ObligationKind::Lease, "forged lease");

        let result =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ch.abort_send(forged)));

        crate::assert_with_log!(
            result.is_err(),
            "wrong kind rejected",
            true,
            result.is_err()
        );
        crate::assert_with_log!(ch.is_empty(), "abort does not enqueue", true, ch.is_empty());
        let retry = ch.reserve_send();
        crate::assert_with_log!(
            retry.is_none(),
            "reservation count preserved after rejected abort",
            true,
            retry.is_none()
        );
        crate::test_complete!("toy_channel_abort_rejects_wrong_obligation_kind");
    }

    // ---- Display impls -----------------------------------------------------

    #[test]
    fn display_impls() {
        init_test("graded_display_impls");
        let proof = ResolvedProof {
            kind: ObligationKind::SendPermit,
            resolution: Resolution::Commit,
        };
        let s = format!("{proof}");
        let has_resolved = s.contains("resolved");
        crate::assert_with_log!(has_resolved, "proof display", true, has_resolved);

        let scope_proof = ScopeProof {
            label: "test".to_string(),
            total_reserved: 3,
            total_resolved: 3,
        };
        let s = format!("{scope_proof}");
        let has_clean = s.contains("clean");
        crate::assert_with_log!(has_clean, "scope proof display", true, has_clean);

        let err = ScopeLeakError {
            label: "bad".to_string(),
            outstanding: 2,
            reserved: 5,
            resolved: 3,
        };
        let s = format!("{err}");
        let has_leaked = s.contains("leaked");
        crate::assert_with_log!(has_leaked, "scope error display", true, has_leaked);

        let resolution = format!("{}", Resolution::Commit);
        crate::assert_with_log!(
            resolution == "commit",
            "resolution display",
            "commit",
            resolution
        );

        crate::test_complete!("graded_display_impls");
    }

    // ---- Typing judgment demonstration -------------------------------------

    #[test]
    fn typing_judgment_demonstration() {
        init_test("typing_judgment_demonstration");
        // This test demonstrates the typing discipline:
        //
        // 1. reserve() creates an obligation (1 resource unit)
        // 2. resolve() consumes it (0 resource units)
        // 3. Scope verifies zero-leak at exit
        //
        // The key insight: in a linear type system, step 2 is mandatory.
        // In Rust (affine), we enforce it with Drop + #[must_use].

        let mut scope = GradedScope::open("typing_demo");

        // Typing rule: Γ ⊢ reserve(SendPermit) : Obligation<SendPermit>  [+1]
        let ob = GradedObligation::reserve(ObligationKind::SendPermit, "demo");
        scope.on_reserve();

        // Typing rule: Γ, ob: Obligation<SendPermit> ⊢ resolve(ob, Commit) : Proof  [-1]
        let proof = ob.resolve(Resolution::Commit);
        scope.on_resolve();

        // Typing rule: Γ ⊢ scope_close : ScopeProof   [requires 0 outstanding]
        let scope_proof = scope.close().expect("scope should be clean");

        // Verify the proof tokens exist (zero-cost witnesses).
        let kind = proof.kind();
        crate::assert_with_log!(
            kind == ObligationKind::SendPermit,
            "proof kind",
            ObligationKind::SendPermit,
            kind
        );
        let label = scope_proof.label();
        crate::assert_with_log!(label == "typing_demo", "scope label", "typing_demo", label);

        crate::test_complete!("typing_judgment_demonstration");
    }

    // ---- Resource semiring properties --------------------------------------

    #[test]
    fn resource_semiring_identity() {
        init_test("resource_semiring_identity");
        // 0 is the identity for +: scope with 0 obligations is clean.
        let scope = GradedScope::open("zero");
        let proof = scope.close().expect("zero obligations = clean");
        let total = proof.total_reserved();
        crate::assert_with_log!(total == 0, "zero reserved", 0, total);
        crate::test_complete!("resource_semiring_identity");
    }

    #[test]
    fn resource_semiring_additive() {
        init_test("resource_semiring_additive");
        // + is additive: obligations accumulate and must all be resolved.
        let mut scope = GradedScope::open("additive");

        // Reserve 3 obligations (1 + 1 + 1 = 3).
        for _ in 0..3 {
            let ob = GradedObligation::reserve(ObligationKind::Lease, "lease");
            scope.on_reserve();
            let _proof = ob.resolve(Resolution::Commit);
            scope.on_resolve();
        }

        let proof = scope.close().expect("all resolved");
        let total = proof.total_reserved();
        crate::assert_with_log!(total == 3, "3 reserved", 3, total);
        let resolved = proof.total_resolved();
        crate::assert_with_log!(resolved == 3, "3 resolved", 3, resolved);
        crate::test_complete!("resource_semiring_additive");
    }

    // ---- ObligationToken typestate tests ------------------------------------

    #[test]
    fn token_commit_returns_proof() {
        init_test("token_commit_returns_proof");
        let token: SendPermitToken = ObligationToken::reserve_test("commit-test");
        let proof = token.commit();
        let kind = proof.kind();
        crate::assert_with_log!(
            kind == ObligationKind::SendPermit,
            "proof kind",
            ObligationKind::SendPermit,
            kind
        );
        crate::test_complete!("token_commit_returns_proof");
    }

    #[test]
    fn token_abort_returns_proof() {
        init_test("token_abort_returns_proof");
        let token: AckToken = ObligationToken::reserve_test("abort-test");
        let proof = token.abort();
        let kind = proof.kind();
        crate::assert_with_log!(
            kind == ObligationKind::Ack,
            "proof kind",
            ObligationKind::Ack,
            kind
        );
        crate::test_complete!("token_abort_returns_proof");
    }

    #[test]
    fn token_dynamic_kind_bridge_accepts_matching_hot_path_kind() {
        init_test("token_dynamic_kind_bridge_accepts_matching_hot_path_kind");
        let token: SendPermitToken = ObligationToken::try_reserve_kind(
            ObligationKind::SendPermit,
            "hot-path send",
            RegionId::new_ephemeral(),
        )
        .expect("send permit dynamic kind should map to SendPermitToken");

        let proof = token.commit();
        crate::assert_with_log!(
            proof.kind() == ObligationKind::SendPermit,
            "typed proof kind",
            ObligationKind::SendPermit,
            proof.kind()
        );
        let resolved = proof.into_resolved_proof();
        crate::assert_with_log!(
            resolved.resolution() == Resolution::Commit,
            "resolved proof",
            Resolution::Commit,
            resolved.resolution()
        );
        crate::test_complete!("token_dynamic_kind_bridge_accepts_matching_hot_path_kind");
    }

    #[test]
    fn token_dynamic_kind_bridge_rejects_mismatched_protocol_family() {
        init_test("token_dynamic_kind_bridge_rejects_mismatched_protocol_family");
        let err = SendPermitToken::try_reserve_kind(
            ObligationKind::Ack,
            "wrong dynamic family",
            RegionId::new_ephemeral(),
        )
        .expect_err("Ack must not manufacture a SendPermitToken");

        crate::assert_with_log!(
            err.expected == ObligationKind::SendPermit,
            "expected typed kind",
            ObligationKind::SendPermit,
            err.expected
        );
        crate::assert_with_log!(
            err.actual == ObligationKind::Ack,
            "actual dynamic kind",
            ObligationKind::Ack,
            err.actual
        );
        crate::assert_with_log!(
            format!("{err}").contains("expected send_permit, got ack"),
            "diagnostic",
            true,
            format!("{err}").contains("expected send_permit, got ack")
        );
        crate::test_complete!("token_dynamic_kind_bridge_rejects_mismatched_protocol_family");
    }

    #[test]
    fn scoped_dynamic_kind_bridge_tracks_abort_cleanup_parity() {
        init_test("scoped_dynamic_kind_bridge_tracks_abort_cleanup_parity");
        let mut scope = GradedScope::open("lease-hot-path");
        let token: LeaseToken = scope
            .try_reserve_token_kind(ObligationKind::Lease, "lease cancellation cleanup")
            .expect("Lease dynamic kind should map to LeaseToken");
        crate::assert_with_log!(scope.outstanding() == 1, "reserved", 1, scope.outstanding());

        let proof = scope.resolve_abort(token);
        crate::assert_with_log!(
            proof.kind() == ObligationKind::Lease,
            "abort proof kind",
            ObligationKind::Lease,
            proof.kind()
        );
        let resolved = proof.into_resolved_proof();
        crate::assert_with_log!(
            resolved.resolution() == Resolution::Abort,
            "abort bridges to resolved proof",
            Resolution::Abort,
            resolved.resolution()
        );

        let scope_proof = scope.close().expect("abort must leave scope balanced");
        crate::assert_with_log!(
            scope_proof.total_reserved() == 1,
            "scope reserved count",
            1,
            scope_proof.total_reserved()
        );
        crate::assert_with_log!(
            scope_proof.total_resolved() == 1,
            "scope resolved count",
            1,
            scope_proof.total_resolved()
        );
        crate::test_complete!("scoped_dynamic_kind_bridge_tracks_abort_cleanup_parity");
    }

    #[test]
    fn scoped_dynamic_kind_bridge_mismatch_does_not_increment_scope() {
        init_test("scoped_dynamic_kind_bridge_mismatch_does_not_increment_scope");
        let mut scope = GradedScope::open("mismatch");
        let err = scope
            .try_reserve_token_kind::<AckKind>(ObligationKind::SendPermit, "wrong ack family")
            .expect_err("SendPermit must not reserve AckToken scope state");

        crate::assert_with_log!(
            err.expected == ObligationKind::Ack,
            "expected typed kind",
            ObligationKind::Ack,
            err.expected
        );
        crate::assert_with_log!(
            err.actual == ObligationKind::SendPermit,
            "actual dynamic kind",
            ObligationKind::SendPermit,
            err.actual
        );
        crate::assert_with_log!(
            scope.outstanding() == 0,
            "mismatch leaves scope empty",
            0,
            scope.outstanding()
        );
        let proof = scope.close().expect("mismatch must not leak scope state");
        crate::assert_with_log!(
            proof.total_reserved() == 0,
            "no reservation recorded",
            0,
            proof.total_reserved()
        );
        crate::test_complete!("scoped_dynamic_kind_bridge_mismatch_does_not_increment_scope");
    }

    #[test]
    fn typed_obligation_bridge_contract_logs_required_evidence_fields() {
        init_test("typed_obligation_bridge_contract_logs_required_evidence_fields");
        let contract = typed_obligation_bridge_contract();

        crate::assert_with_log!(
            contract.bead_id == "asupersync-d87ytw.13",
            "bead id",
            "asupersync-d87ytw.13",
            contract.bead_id
        );
        crate::assert_with_log!(
            contract.protocol_family.contains("send-permit")
                && contract.protocol_family.contains("lease"),
            "protocol family",
            "send-permit/ack/lease graded obligations",
            contract.protocol_family
        );
        crate::assert_with_log!(
            contract
                .typed_entrypoint
                .ends_with("ObligationToken::try_reserve_kind"),
            "typed entrypoint",
            "ObligationToken::try_reserve_kind",
            contract.typed_entrypoint
        );
        crate::assert_with_log!(
            contract.dynamic_fallback == "asupersync::record::ObligationKind",
            "dynamic fallback",
            "asupersync::record::ObligationKind",
            contract.dynamic_fallback
        );
        crate::assert_with_log!(
            contract.compile_fail_surface.contains("commit-then-abort"),
            "compile-fail surface",
            "commit-then-abort",
            contract.compile_fail_surface
        );
        crate::assert_with_log!(
            contract.replay_command.contains("rch exec --")
                && contract
                    .replay_command
                    .contains("--lib dynamic_kind_bridge"),
            "replay command",
            "rch exec -- cargo test --lib dynamic_kind_bridge",
            contract.replay_command
        );
        crate::assert_with_log!(
            contract
                .invariants
                .contains(&"mismatched dynamic kind does not arm a token"),
            "migration fallback invariant",
            true,
            contract
                .invariants
                .contains(&"mismatched dynamic kind does not arm a token")
        );
        crate::test_complete!("typed_obligation_bridge_contract_logs_required_evidence_fields");
    }

    #[test]
    #[should_panic(expected = "OBLIGATION TOKEN LEAKED")]
    fn token_drop_without_consume_panics() {
        init_test("token_drop_without_consume_panics");
        let _token: SendPermitToken = ObligationToken::reserve_test("leaked-token");
        // Dropped without commit or abort — should panic.
    }

    #[test]
    fn token_into_raw_disarms() {
        init_test("token_into_raw_disarms");
        let token: LeaseToken = ObligationToken::reserve_test("raw-escape");
        let raw = token.into_raw();
        let kind = raw.kind;
        crate::assert_with_log!(
            kind == ObligationKind::Lease,
            "raw kind",
            ObligationKind::Lease,
            kind
        );
        drop(raw);
        crate::test_complete!("token_into_raw_disarms");
    }

    #[test]
    fn committed_proof_bridge() {
        init_test("committed_proof_bridge");
        let token: SendPermitToken = ObligationToken::reserve_test("bridge-commit");
        let committed = token.commit();
        let resolved = committed.into_resolved_proof();
        let r = resolved.resolution();
        crate::assert_with_log!(r == Resolution::Commit, "resolution", Resolution::Commit, r);
        let kind = resolved.kind();
        crate::assert_with_log!(
            kind == ObligationKind::SendPermit,
            "kind",
            ObligationKind::SendPermit,
            kind
        );
        crate::test_complete!("committed_proof_bridge");
    }

    #[test]
    fn aborted_proof_bridge() {
        init_test("aborted_proof_bridge");
        let token: AckToken = ObligationToken::reserve_test("bridge-abort");
        let aborted = token.abort();
        let resolved = aborted.into_resolved_proof();
        let r = resolved.resolution();
        crate::assert_with_log!(r == Resolution::Abort, "resolution", Resolution::Abort, r);
        let kind = resolved.kind();
        crate::assert_with_log!(
            kind == ObligationKind::Ack,
            "kind",
            ObligationKind::Ack,
            kind
        );
        crate::test_complete!("aborted_proof_bridge");
    }

    #[test]
    fn token_kind_mapping() {
        init_test("token_kind_mapping");
        let sp = SendPermit::obligation_kind();
        crate::assert_with_log!(
            sp == ObligationKind::SendPermit,
            "SendPermit",
            ObligationKind::SendPermit,
            sp
        );
        let ack = AckKind::obligation_kind();
        crate::assert_with_log!(
            ack == ObligationKind::Ack,
            "AckKind",
            ObligationKind::Ack,
            ack
        );
        let lease = LeaseKind::obligation_kind();
        crate::assert_with_log!(
            lease == ObligationKind::Lease,
            "LeaseKind",
            ObligationKind::Lease,
            lease
        );
        let io = IoOpKind::obligation_kind();
        crate::assert_with_log!(
            io == ObligationKind::IoOp,
            "IoOpKind",
            ObligationKind::IoOp,
            io
        );
        crate::test_complete!("token_kind_mapping");
    }

    #[test]
    fn scope_reserve_and_commit_token() {
        init_test("scope_reserve_and_commit_token");
        let mut scope = GradedScope::open("token-scope-commit");
        let token: SendPermitToken = scope.reserve_token("scoped-send");
        let outstanding = scope.outstanding();
        crate::assert_with_log!(outstanding == 1, "outstanding", 1, outstanding);

        let proof = scope.resolve_commit(token);
        let outstanding = scope.outstanding();
        crate::assert_with_log!(outstanding == 0, "outstanding", 0, outstanding);

        let kind = proof.kind();
        crate::assert_with_log!(
            kind == ObligationKind::SendPermit,
            "kind",
            ObligationKind::SendPermit,
            kind
        );

        let scope_proof = scope.close().expect("scope should close cleanly");
        let total = scope_proof.total_reserved();
        crate::assert_with_log!(total == 1, "reserved", 1, total);
        crate::test_complete!("scope_reserve_and_commit_token");
    }

    #[test]
    fn scope_reserve_and_abort_token() {
        init_test("scope_reserve_and_abort_token");
        let mut scope = GradedScope::open("token-scope-abort");
        let token: AckToken = scope.reserve_token("scoped-ack");
        let outstanding = scope.outstanding();
        crate::assert_with_log!(outstanding == 1, "outstanding", 1, outstanding);

        let proof = scope.resolve_abort(token);
        let outstanding = scope.outstanding();
        crate::assert_with_log!(outstanding == 0, "outstanding", 0, outstanding);

        let kind = proof.kind();
        crate::assert_with_log!(
            kind == ObligationKind::Ack,
            "kind",
            ObligationKind::Ack,
            kind
        );

        let scope_proof = scope.close().expect("scope should close cleanly");
        let total = scope_proof.total_reserved();
        crate::assert_with_log!(total == 1, "reserved", 1, total);
        crate::test_complete!("scope_reserve_and_abort_token");
    }

    #[test]
    fn all_four_token_kinds() {
        init_test("all_four_token_kinds");

        // SendPermit
        let t1: SendPermitToken = ObligationToken::reserve_test("sp");
        let p1 = t1.commit();
        let k1 = p1.kind();
        crate::assert_with_log!(
            k1 == ObligationKind::SendPermit,
            "SendPermit",
            ObligationKind::SendPermit,
            k1
        );

        // Ack
        let t2: AckToken = ObligationToken::reserve_test("ack");
        let p2 = t2.abort();
        let k2 = p2.kind();
        crate::assert_with_log!(k2 == ObligationKind::Ack, "Ack", ObligationKind::Ack, k2);

        // Lease
        let t3: LeaseToken = ObligationToken::reserve_test("lease");
        let p3 = t3.commit();
        let k3 = p3.kind();
        crate::assert_with_log!(
            k3 == ObligationKind::Lease,
            "Lease",
            ObligationKind::Lease,
            k3
        );

        // IoOp
        let t4: IoOpToken = ObligationToken::reserve_test("io");
        let p4 = t4.abort();
        let k4 = p4.kind();
        crate::assert_with_log!(k4 == ObligationKind::IoOp, "IoOp", ObligationKind::IoOp, k4);

        crate::test_complete!("all_four_token_kinds");
    }

    // =========================================================================
    // Wave 59 – pure data-type trait coverage
    // =========================================================================

    #[test]
    fn resolution_debug_clone_copy_eq() {
        let r = Resolution::Commit;
        let dbg = format!("{r:?}");
        assert!(dbg.contains("Commit"), "{dbg}");
        let copied = r;
        let cloned = r;
        assert_eq!(copied, cloned);
        assert_ne!(r, Resolution::Abort);
    }

    #[test]
    fn resolved_proof_debug_eq() {
        let rp = ResolvedProof {
            kind: ObligationKind::SendPermit,
            resolution: Resolution::Commit,
        };
        let dbg = format!("{rp:?}");
        assert!(dbg.contains("ResolvedProof"), "{dbg}");
        let rp_same = ResolvedProof {
            kind: ObligationKind::SendPermit,
            resolution: Resolution::Commit,
        };
        assert_eq!(rp, rp_same);
    }

    #[test]
    fn scope_proof_debug_accessors() {
        let sp = ScopeProof {
            label: "test".to_string(),
            total_reserved: 5,
            total_resolved: 5,
        };
        let dbg = format!("{sp:?}");
        assert!(dbg.contains("ScopeProof"), "{dbg}");
        assert_eq!(sp.label(), "test");
        assert_eq!(sp.total_reserved(), 5);
        assert_eq!(sp.total_resolved(), 5);
    }

    #[test]
    #[should_panic(expected = "on_reserve overflowed outstanding obligation count")]
    fn scope_on_reserve_overflow_panics_instead_of_wrapping() {
        let mut scope = GradedScope {
            label: "overflow".to_string(),
            reserved: u32::MAX,
            resolved: 0,
            closed: false,
        };
        scope.on_reserve();
    }

    #[test]
    #[should_panic(expected = "toy channel occupancy overflowed")]
    fn toy_channel_capacity_overflow_panics_instead_of_wrapping() {
        let mut ch =
            toy_api::ToyChannel::from_state(usize::MAX, vec!["occupied".to_string()], usize::MAX);
        let _ = ch.reserve_send();
    }

    #[test]
    fn close_err_does_not_panic_when_caller_handles_error() {
        let mut scope = GradedScope::open("leak-test");
        scope.on_reserve();
        // close() returns Err because 1 obligation is outstanding.
        // The caller explicitly called close() and received the error,
        // so Drop should NOT panic — the leak is acknowledged.
        let err = scope.close().expect_err("should return leak error");
        assert_eq!(err.outstanding, 1);
    }

    // ========================================================================
    // GRADED-REFINEMENT conformance harness (Pattern 4: spec-derived)
    //
    // The typing judgment at the top of this module is the spec:
    //
    //   Γ ⊢ reserve(K)     : Obligation<K>     [+1 unit of K]
    //   Γ, x: Obligation<K> ⊢ commit(x) : ()   [-1 unit of K]
    //   Γ, x: Obligation<K> ⊢ abort(x)  : ()   [-1 unit of K]
    //   Γ ⊢ scope(body) : τ   iff   Γ_exit has 0 outstanding Obligation<K>
    //
    // Each GRADED-REFINEMENT-N clause below mechanically verifies one
    // refinement-boundary law implied by the judgment.
    //
    // Every case emits one stderr JSON-line verdict of shape:
    //   {"id":"GRADED-REFINEMENT-N","verdict":"PASS|FAIL","level":"MUST"}
    // so a CI harness can grep+count pass/fail without parsing panics.
    // ========================================================================

    fn emit_verdict(id: &str, pass: bool) {
        eprintln!(
            "{{\"id\":\"{id}\",\"verdict\":\"{}\",\"level\":\"MUST\"}}",
            if pass { "PASS" } else { "FAIL" }
        );
    }

    // GRADED-REFINEMENT-1: reserve(K) increases reserved count by exactly 1.
    #[test]
    fn conformance_graded_refinement_1_reserve_is_plus_one() {
        init_test("GRADED-REFINEMENT-1");
        let mut scope = GradedScope::open("L1");
        let r0 = scope.outstanding();
        scope.on_reserve();
        let r1 = scope.outstanding();
        let pass = r0 == 0 && r1 == 1;
        emit_verdict("GRADED-REFINEMENT-1", pass);
        // Clean up so Drop doesn't panic.
        scope.on_resolve();
        let _ = scope.close();
        assert!(pass, "reserve did not increment outstanding by exactly 1");
    }

    // GRADED-REFINEMENT-2: commit(x) decreases outstanding by exactly 1.
    #[test]
    fn conformance_graded_refinement_2_commit_is_minus_one() {
        init_test("GRADED-REFINEMENT-2");
        let mut scope = GradedScope::open("L2");
        scope.on_reserve();
        let before = scope.outstanding();
        let tok: ObligationToken<SendPermit> = ObligationToken::reserve_test("L2");
        let _proof = tok.commit(); // consume token
        scope.on_resolve();
        let after = scope.outstanding();
        let pass = before == 1 && after == 0;
        emit_verdict("GRADED-REFINEMENT-2", pass);
        let _ = scope.close();
        assert!(pass, "commit did not decrement outstanding by exactly 1");
    }

    // GRADED-REFINEMENT-3: abort(x) decreases outstanding by exactly 1
    // (symmetric with commit: the refinement sees only "resolved").
    #[test]
    fn conformance_graded_refinement_3_abort_is_minus_one() {
        init_test("GRADED-REFINEMENT-3");
        let mut scope = GradedScope::open("L3");
        scope.on_reserve();
        let before = scope.outstanding();
        let tok: ObligationToken<AckKind> = ObligationToken::reserve_test("L3");
        let _proof = tok.abort();
        scope.on_resolve();
        let after = scope.outstanding();
        let pass = before == 1 && after == 0;
        emit_verdict("GRADED-REFINEMENT-3", pass);
        let _ = scope.close();
        assert!(pass, "abort did not decrement outstanding by exactly 1");
    }

    // GRADED-REFINEMENT-4: scope close() at 0 outstanding yields a ScopeProof
    // whose total_reserved == total_resolved.
    #[test]
    fn conformance_graded_refinement_4_close_clean_boundary() {
        init_test("GRADED-REFINEMENT-4");
        let mut scope = GradedScope::open("L4");
        for _ in 0..7 {
            scope.on_reserve();
            scope.on_resolve();
        }
        let result = scope.close();
        let pass = match &result {
            Ok(p) => p.total_reserved() == 7 && p.total_resolved() == 7,
            Err(_) => false,
        };
        emit_verdict("GRADED-REFINEMENT-4", pass);
        assert!(
            pass,
            "close() at 0 outstanding did not produce matching counts"
        );
    }

    // GRADED-REFINEMENT-5: scope close() with outstanding > 0 yields a
    // ScopeLeakError whose fields satisfy reserved - resolved == outstanding.
    #[test]
    fn conformance_graded_refinement_5_close_leak_exact_accounting() {
        init_test("GRADED-REFINEMENT-5");
        let mut scope = GradedScope::open("L5");
        for _ in 0..5 {
            scope.on_reserve();
        }
        for _ in 0..2 {
            scope.on_resolve();
        }
        let err = scope.close().expect_err("expected leak");
        let pass = err.reserved == 5
            && err.resolved == 2
            && err.outstanding == err.reserved - err.resolved
            && err.outstanding == 3;
        emit_verdict("GRADED-REFINEMENT-5", pass);
        assert!(pass, "leak accounting diverges from reserved - resolved");
    }

    // GRADED-REFINEMENT-6: outstanding() is a pure function of the running
    // net of reserves vs. resolves. After any prefix of a balanced interleaving,
    // outstanding() == (#reserves_seen - #resolves_seen) and is non-negative.
    //
    // Note: on_resolve() panics if called more times than on_reserve(), so the
    // op sequence below is a valid prefix (net never goes negative).
    #[test]
    fn conformance_graded_refinement_6_outstanding_tracks_running_net() {
        init_test("GRADED-REFINEMENT-6");
        let mut scope = GradedScope::open("L6");
        let ops = [
            true, true, false, true, false, false, true, true, false, false,
        ];
        let mut net: i64 = 0;
        let mut ok = true;
        for reserve in ops {
            if reserve {
                scope.on_reserve();
                net += 1;
            } else {
                scope.on_resolve();
                net -= 1;
            }
            let got = i64::from(scope.outstanding());
            if got != net || net < 0 {
                ok = false;
            }
        }
        // Balanced: outstanding must be exactly 0 at the end.
        ok = ok && scope.outstanding() == 0 && net == 0;
        emit_verdict("GRADED-REFINEMENT-6", ok);
        let _ = scope.close();
        assert!(ok, "outstanding diverged from the running net of ops");
    }

    // GRADED-REFINEMENT-7: Resolution preserves obligation kind.
    // GradedObligation::reserve(K, _).resolve(r).kind() == K.
    #[test]
    fn conformance_graded_refinement_7_resolution_preserves_kind() {
        init_test("GRADED-REFINEMENT-7");
        let cases = [
            (ObligationKind::SendPermit, Resolution::Commit),
            (ObligationKind::SendPermit, Resolution::Abort),
            (ObligationKind::Ack, Resolution::Commit),
            (ObligationKind::Ack, Resolution::Abort),
            (ObligationKind::Lease, Resolution::Commit),
            (ObligationKind::Lease, Resolution::Abort),
            (ObligationKind::IoOp, Resolution::Commit),
            (ObligationKind::IoOp, Resolution::Abort),
            (ObligationKind::SemaphorePermit, Resolution::Commit),
            (ObligationKind::SemaphorePermit, Resolution::Abort),
        ];
        let mut pass = true;
        for (k, r) in cases {
            let ob = GradedObligation::reserve(k, "kind-test");
            let proof = ob.resolve(r);
            if proof.kind() != k || proof.resolution() != r {
                pass = false;
            }
        }
        emit_verdict("GRADED-REFINEMENT-7", pass);
        assert!(pass, "resolution dropped kind or resolution on the floor");
    }

    // GRADED-REFINEMENT-8: Typestate ObligationToken<K> preserves K through
    // CommittedProof<K> / AbortedProof<K>.
    #[test]
    fn conformance_graded_refinement_8_typestate_preserves_kind() {
        init_test("GRADED-REFINEMENT-8");
        let send_commit = <SendPermit as TokenKind>::obligation_kind();
        let ack_abort = <AckKind as TokenKind>::obligation_kind();

        let t1: SendPermitToken = ObligationToken::reserve_test("send");
        let p1 = t1.commit();
        let pass1 = p1.kind() == send_commit && p1.into_resolved_proof().kind() == send_commit;

        let t2: AckToken = ObligationToken::reserve_test("ack");
        let p2 = t2.abort();
        let pass2 = p2.kind() == ack_abort && p2.into_resolved_proof().kind() == ack_abort;

        let pass = pass1 && pass2;
        emit_verdict("GRADED-REFINEMENT-8", pass);
        assert!(pass, "typestate token lost kind across commit/abort");
    }

    // GRADED-REFINEMENT-9: into_raw() disarms the drop bomb AND preserves kind.
    #[test]
    fn conformance_graded_refinement_9_into_raw_disarms_and_preserves_kind() {
        init_test("GRADED-REFINEMENT-9");
        let ob = GradedObligation::reserve(ObligationKind::Lease, "raw");
        let raw = ob.into_raw();
        let pass_a = raw.kind == ObligationKind::Lease && raw.description == "raw";

        let tok: LeaseToken = ObligationToken::reserve_test("raw-ts");
        let raw2 = tok.into_raw();
        let pass_b = raw2.kind == ObligationKind::Lease && raw2.description == "raw-ts";

        // If into_raw did NOT disarm the drop bomb, the two calls above would
        // have panicked. Reaching this point is the disarm proof.
        let pass = pass_a && pass_b;
        emit_verdict("GRADED-REFINEMENT-9", pass);
        assert!(
            pass,
            "into_raw lost kind or description across the boundary"
        );
    }

    // GRADED-REFINEMENT-10: Boundary monotonicity — scope close() returning
    // Ok implies all ScopeProof counts are ≥ 0 and total_reserved == total_resolved;
    // scope close() returning Err implies outstanding > 0 and
    // reserved > resolved. Cases are disjoint and cover the boundary.
    #[test]
    fn conformance_graded_refinement_10_close_boundary_disjoint() {
        init_test("GRADED-REFINEMENT-10");
        // Clean side.
        let mut clean = GradedScope::open("L10-clean");
        for _ in 0..3 {
            clean.on_reserve();
            clean.on_resolve();
        }
        let clean_ok = clean.close();
        let clean_pass =
            matches!(&clean_ok, Ok(p) if p.total_reserved() == 3 && p.total_resolved() == 3);

        // Leaky side.
        let mut leaky = GradedScope::open("L10-leaky");
        for _ in 0..4 {
            leaky.on_reserve();
        }
        for _ in 0..1 {
            leaky.on_resolve();
        }
        let leaky_err = leaky.close();
        let leaky_pass = matches!(
            &leaky_err,
            Err(e) if e.outstanding == 3 && e.reserved > e.resolved && e.reserved == 4 && e.resolved == 1
        );

        let pass = clean_pass && leaky_pass;
        emit_verdict("GRADED-REFINEMENT-10", pass);
        assert!(
            pass,
            "close() boundary cases are not disjoint or mis-accounted"
        );
    }
}