hibana 0.2.0

Const-projected Affine Multiparty Session Types for choreography-first Rust protocols
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
//! CapMint 2.0 primitives for capability minting and validation.
//!
//! Hibana mints control tokens through const-first strategies baked into
//! `RoleProgram` and endpoint-owned local control send paths, with
//! rendezvous tables enforcing nonce/tag side effects via
//! `Rendezvous::mint_cap()` and `Rendezvous::claim_cap()`.
//!
//! # Epoch-Based Revocation (Witness System)
//!
//! This module provides ledger-free capability revocation via epoch witnesses.
//! Capabilities are tied to an epoch witness, and revocation is achieved by
//! advancing the epoch. Operations on old capabilities fail at compile time
//! because the witness is no longer available.
//!
//! ## Design Principles
//!
//! 1. **No global state**: Epoch is tracked via type-level witnesses, not global counters
//! 2. **Affine linearity**: endpoint state carries a rendezvous-scoped owner witness
//! 3. **Compile-time safety**: endpoint-owned epoch witnesses remain in the type system
//! 4. **AMPST compliance**: Integrates with cancellation termination (ECOOP'22)
//!
//! ## Usage Example
//!
//! Internally, the rendezvous core mints a rendezvous-scoped [`Owner`] witness
//! for the active endpoint. Application code never receives the brand directly;
//! the cursor endpoint stores the witness and exposes typed control operations.
//!
//! ## Integration with Endpoint
//!
//! The internal endpoint implementation stores [`Owner<'rv, Step>`] alongside
//! [`EndpointEpoch<'rv, Table>`]. Control plane operations verify epoch progression
//! through the `Step` type parameter, ensuring:
//!
//! - **Affine progression**: Each operation consumes `Endpoint<Step>` and produces
//!   `Endpoint<NextStep>`, making reuse impossible at compile time.
//! - **API simplicity**: Users work with `Endpoint` directly; witness mechanics are hidden
//!   in the `pub(crate)` implementation.
//!
//! The approach keeps ledgers purely internal: the rendezvous retains the brand
//! token and no global bookkeeping structure is required.
//!
//! # Wire Format
//!
//! Capability tokens are 32 bytes on the wire:
//! ```text
//! [16B nonce | 8B header | 8B HMAC]
//! header = (sid:u32, lane:u8, role:u8, kind:u8, shot:u8)
//! HMAC = keyed_hash(mac_key, nonce || header)
//! ```
//!
//! # Usage Pattern
//!
//! ## SessionCluster-driven endpoint minting
//!
//! ```rust,ignore
//! let controller = cluster.enter(rv_id, sid, &CONTROLLER, hibana::substrate::binding::NoBinding)?;
//! let (controller, outcome) = controller.send::<CancelMsg>(()).await?;
//! let _ = outcome;
//! ```
//!
//! ## Rendezvous validation
//!
//! ```rust,ignore
//! let (worker, token) = worker.recv::<CancelMsg>().await?;
//! let verified = rendezvous.claim_cap(&token)?;
//! drop(verified);
//! ```
//!
//! ## Custom Resource Example
//!
//! ```rust,ignore
//! use core::cell::Cell;
//! use hibana::substrate::cap::{CapError, GenericCapToken, ResourceKind};
//!
//! #[derive(Clone, Copy, Debug)]
//! struct PageHandle {
//!     id: u32,
//! }
//!
//! thread_local! {
//!     static LAST_ZEROIZED: Cell<usize> = const { Cell::new(0) };
//! }
//!
//! struct PageResource;
//!
//! impl ResourceKind for PageResource {
//!     type Handle = PageHandle;
//!     const TAG: u8 = 1;
//!
//!     fn encode_handle(handle: &Self::Handle) -> [u8; 6] {
//!         let mut buf = [0u8; 6];
//!         buf[0..4].copy_from_slice(&handle.id.to_be_bytes());
//!         buf
//!     }
//!
//!     fn decode_handle(data: [u8; 6]) -> Result<Self::Handle, CapError> {
//!         let mut id_bytes = [0u8; 4];
//!         id_bytes.copy_from_slice(&data[0..4]);
//!         Ok(PageHandle {
//!             id: u32::from_be_bytes(id_bytes),
//!         })
//!     }
//!
//!     fn zeroize(handle: &mut Self::Handle) {
//!         LAST_ZEROIZED.store(handle.id as usize, Ordering::Relaxed);
//!         handle.id = 0;
//!     }
//! }
//!
//! fn round_trip(token: GenericCapToken<PageResource>) -> GenericCapToken<PageResource> {
//!     // Convert to bytes and back so the token can traverse message routes.
//!     let bytes = token.into_bytes();
//!     <GenericCapToken<PageResource> as hibana::substrate::wire::WirePayload>::decode_payload(
//!         hibana::substrate::wire::Payload::new(&bytes),
//!     )
//!     .unwrap()
//! }
//! ```

use core::marker::PhantomData;

// ============================================================================
// CapMint 2.0 core (const-first / no_std / no_alloc)
// ============================================================================

/// Seed provided by the rendezvous during minting.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NonceSeed {
    counter: u64,
}

impl NonceSeed {
    #[inline(always)]
    pub const fn counter(counter: u64) -> Self {
        Self { counter }
    }

    #[inline(always)]
    pub const fn counter_value(&self) -> u64 {
        self.counter
    }
}

/// Trait implemented by const minting specifications.
pub trait CapMintSpec {
    /// Derive the nonce bytes using the rendezvous-provided seed.
    fn nonce(seed: NonceSeed) -> [u8; CAP_NONCE_LEN];

    /// Derive the authentication tag from nonce + header bytes.
    fn mac(nonce: &[u8; CAP_NONCE_LEN], header: &[u8; CAP_HEADER_LEN]) -> [u8; CAP_TAG_LEN];
}

/// Canonical null strategy – counter-based nonce, zero tag.
#[derive(Clone, Copy, Debug)]
pub struct NullMintSpec;

impl CapMintSpec for NullMintSpec {
    #[inline(always)]
    fn nonce(seed: NonceSeed) -> [u8; CAP_NONCE_LEN] {
        let mut out = [0u8; CAP_NONCE_LEN];
        let bytes = seed.counter_value().to_be_bytes();
        let offset = CAP_NONCE_LEN - bytes.len();
        out[offset..].copy_from_slice(&bytes);
        out
    }

    #[inline(always)]
    fn mac(_nonce: &[u8; CAP_NONCE_LEN], _header: &[u8; CAP_HEADER_LEN]) -> [u8; CAP_TAG_LEN] {
        [0u8; CAP_TAG_LEN]
    }
}

/// Endpoint mint policy – the attached endpoint may mint control payloads.
#[derive(Clone, Copy, Debug)]
pub struct EndpointMintPolicy;

/// Marker trait implemented by policies that permit endpoint minting.
pub trait AllowsEndpointMint {}

impl AllowsEndpointMint for EndpointMintPolicy {}

/// Zero-sized minting strategy wrapper.
#[derive(Debug, Default)]
pub struct CapMintStrategy<S: CapMintSpec> {
    _spec: PhantomData<S>,
}

impl<S: CapMintSpec> Copy for CapMintStrategy<S> {}

impl<S: CapMintSpec> Clone for CapMintStrategy<S> {
    #[inline(always)]
    fn clone(&self) -> Self {
        *self
    }
}

impl<S: CapMintSpec> CapMintStrategy<S> {
    #[inline(always)]
    pub const fn new() -> Self {
        Self { _spec: PhantomData }
    }

    #[inline(always)]
    pub fn derive_nonce(&self, seed: NonceSeed) -> [u8; CAP_NONCE_LEN] {
        S::nonce(seed)
    }

    #[inline(always)]
    pub fn derive_tag(
        &self,
        nonce: &[u8; CAP_NONCE_LEN],
        header: &[u8; CAP_HEADER_LEN],
    ) -> [u8; CAP_TAG_LEN] {
        S::mac(nonce, header)
    }
}

/// Zero-sized mint configuration baked into role programs.
#[derive(Debug)]
pub struct MintConfig<S: CapMintSpec = NullMintSpec, P: Copy = EndpointMintPolicy> {
    strategy: CapMintStrategy<S>,
    _policy: PhantomData<P>,
}

impl<S, P> Copy for MintConfig<S, P>
where
    S: CapMintSpec,
    P: Copy,
{
}

impl<S, P> Clone for MintConfig<S, P>
where
    S: CapMintSpec,
    P: Copy,
{
    #[inline(always)]
    fn clone(&self) -> Self {
        *self
    }
}

impl<S: CapMintSpec, P: Copy> Default for MintConfig<S, P> {
    fn default() -> Self {
        Self::new()
    }
}

impl<S: CapMintSpec, P: Copy> MintConfig<S, P> {
    #[inline(always)]
    pub const fn new() -> Self {
        Self {
            strategy: CapMintStrategy::<S>::new(),
            _policy: PhantomData,
        }
    }

    #[inline(always)]
    pub const fn strategy(&self) -> CapMintStrategy<S> {
        self.strategy
    }
}

/// Marker trait enabling `MintConfig` specialisation.
pub trait MintConfigMarker: Copy {
    type Spec: CapMintSpec;
    type Policy: Copy;
    const INSTANCE: Self;

    fn as_config(&self) -> MintConfig<Self::Spec, Self::Policy>;
}

impl<S, P> MintConfigMarker for MintConfig<S, P>
where
    S: CapMintSpec,
    P: Copy,
{
    type Spec = S;
    type Policy = P;
    const INSTANCE: Self = MintConfig::<S, P>::new();

    #[inline(always)]
    fn as_config(&self) -> MintConfig<Self::Spec, Self::Policy> {
        MintConfig::<S, P>::new()
    }
}

/// Length of the nonce segment inside a capability token.
pub const CAP_NONCE_LEN: usize = 16;
/// Length of the header segment inside a capability token.
pub const CAP_HEADER_LEN: usize = 40;
/// Length of the authentication tag segment inside a capability token.
pub const CAP_TAG_LEN: usize = 16;
/// Number of fixed bytes used by the descriptor-first control header codec.
///
/// Layout:
/// - version: 1
/// - sid: 4
/// - lane: 1
/// - role: 1
/// - tag: 1
/// - op: 1
/// - path: 1
/// - shot: 1
/// - scope_kind: 1
/// - flags: 1
/// - scope_id: 2
/// - epoch: 2
pub const CAP_CONTROL_HEADER_FIXED_LEN: usize = 17;
/// Number of bytes available for resource-specific handle encoding.
pub const CAP_HANDLE_LEN: usize = CAP_HEADER_LEN - CAP_CONTROL_HEADER_FIXED_LEN;
/// Total length of a capability token on the wire.
pub const CAP_TOKEN_LEN: usize = CAP_NONCE_LEN + CAP_HEADER_LEN + CAP_TAG_LEN;
use crate::control::types::Lane;
use crate::control::types::SessionId;
use crate::global::const_dsl::{ControlScopeKind, ScopeId};
use crate::transport::wire::{CodecError, Payload, WireEncode, WirePayload};

// ============================================================================
// Generic capability abstraction
// ============================================================================

/// Resource taxonomy for capabilities.
///
/// Each `ResourceKind` supplies a handle type that is encoded into the opaque
/// payload section of the capability header. The fixed descriptor prefix stores
/// session, routing, and control metadata; the remaining [`CAP_HANDLE_LEN`]
/// bytes are entirely owned by the resource kind for encoding operands.
pub trait ResourceKind {
    /// Handle associated with this capability.
    type Handle;

    /// Capability tag (0-255). `0` is reserved for endpoint capabilities.
    const TAG: u8;

    /// Human-readable name used for observability.
    const NAME: &'static str;

    /// Encode the handle into the resource payload area of the header.
    fn encode_handle(handle: &Self::Handle) -> [u8; CAP_HANDLE_LEN];

    /// Decode the handle from the resource payload area of the header.
    fn decode_handle(data: [u8; CAP_HANDLE_LEN]) -> Result<Self::Handle, CapError>;

    /// Zeroize the handle prior to dropping it.
    fn zeroize(handle: &mut Self::Handle);
}

/// Resource kinds that represent control-plane capabilities.
pub trait ControlResourceKind: ResourceKind {
    const SCOPE: ControlScopeKind;
    const PATH: ControlPath;
    const TAP_ID: u16;
    const SHOT: CapShot;
    const OP: ControlOp;
    const AUTO_MINT_WIRE: bool;

    fn mint_handle(session: SessionId, lane: Lane, scope: ScopeId) -> Self::Handle;
}

impl ResourceKind for () {
    type Handle = ();

    const TAG: u8 = 0;
    const NAME: &'static str = "NoControl";

    fn encode_handle(_handle: &Self::Handle) -> [u8; CAP_HANDLE_LEN] {
        [0u8; CAP_HANDLE_LEN]
    }

    fn decode_handle(_data: [u8; CAP_HANDLE_LEN]) -> Result<Self::Handle, CapError> {
        Ok(())
    }

    fn zeroize(_handle: &mut Self::Handle) {}
}

/// Handle describing an endpoint rendezvous slot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct EndpointHandle {
    pub(crate) sid: SessionId,
    pub(crate) lane: Lane,
    pub(crate) role: u8,
}

impl EndpointHandle {
    pub(crate) const fn new(sid: SessionId, lane: Lane, role: u8) -> Self {
        Self { sid, lane, role }
    }

    fn zeroed() -> Self {
        Self {
            sid: SessionId::new(0),
            lane: Lane::new(0),
            role: 0,
        }
    }
}

/// Marker for endpoint capabilities (kept internal to hibana).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EndpointResource {}

impl ResourceKind for EndpointResource {
    type Handle = EndpointHandle;
    const TAG: u8 = 0;
    const NAME: &'static str = "EndpointResource";

    fn encode_handle(handle: &Self::Handle) -> [u8; CAP_HANDLE_LEN] {
        let mut data = [0u8; CAP_HANDLE_LEN];
        data[0..4].copy_from_slice(&handle.sid.raw().to_be_bytes());
        data[4] = handle.lane.as_wire();
        data[5] = handle.role;
        data
    }

    fn decode_handle(data: [u8; CAP_HANDLE_LEN]) -> Result<Self::Handle, CapError> {
        let sid = SessionId::new(u32::from_be_bytes([data[0], data[1], data[2], data[3]]));
        let lane = Lane::new(u32::from(data[4]));
        let role = data[5];
        Ok(EndpointHandle::new(sid, lane, role))
    }

    fn zeroize(handle: &mut Self::Handle) {
        *handle = EndpointHandle::zeroed();
    }
}

#[derive(Clone, Copy)]
pub(crate) struct Owner<'rv, Step> {
    _brand: PhantomData<crate::control::brand::Guard<'rv>>,
    _step: PhantomData<Step>,
}

impl<'rv, Step> Owner<'rv, Step>
where
    Step: EpochType,
{
    #[inline]
    pub(crate) fn new(_brand: crate::control::brand::Guard<'rv>) -> Self {
        Self {
            _brand: PhantomData,
            _step: PhantomData,
        }
    }
}

// ============================================================================
// Operations that require a short-lived brand witness
// ============================================================================

#[derive(Clone, Copy, Default)]
pub(crate) struct EndpointEpoch<'r, Table: EpochTable> {
    _marker: PhantomData<&'r Table>,
}

impl<'r, Table: EpochTable> EndpointEpoch<'r, Table> {
    #[inline]
    pub(crate) const fn new() -> Self {
        Self {
            _marker: PhantomData,
        }
    }
}

// ============================================================================
// Epoch Witness System (Ledger-Free Revocation)
// ============================================================================

pub trait EpochType {}

/// Marker trait representing logical control-plane steps for a lane.
pub trait EpochStep: EpochType {}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct E0;
impl EpochType for E0 {}
impl EpochStep for E0 {}

pub trait EpochTable {}

/// Compile-time epoch table carrying witnesses for each rendezvous lane.
#[allow(clippy::type_complexity)]
pub struct EpochTbl<
    L0 = E0,
    L1 = E0,
    L2 = E0,
    L3 = E0,
    L4 = E0,
    L5 = E0,
    L6 = E0,
    L7 = E0,
    L8 = E0,
    L9 = E0,
    L10 = E0,
    L11 = E0,
    L12 = E0,
    L13 = E0,
    L14 = E0,
    L15 = E0,
> {
    _marker: PhantomData<(
        L0,
        L1,
        L2,
        L3,
        L4,
        L5,
        L6,
        L7,
        L8,
        L9,
        L10,
        L11,
        L12,
        L13,
        L14,
        L15,
    )>,
}

impl<L0, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12, L13, L14, L15> EpochTable
    for EpochTbl<L0, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12, L13, L14, L15>
where
    L0: EpochStep,
    L1: EpochStep,
    L2: EpochStep,
    L3: EpochStep,
    L4: EpochStep,
    L5: EpochStep,
    L6: EpochStep,
    L7: EpochStep,
    L8: EpochStep,
    L9: EpochStep,
    L10: EpochStep,
    L11: EpochStep,
    L12: EpochStep,
    L13: EpochStep,
    L14: EpochStep,
    L15: EpochStep,
{
}

// ============================================================================
// Original Capability Token System (Wire Format)
// ============================================================================

/// Capability shot semantics embedded in the token wire/runtime encoding.
///
/// `CapShot` records how many times a concrete token may be claimed:
/// - `One`: Single-use (affine). Claiming the token consumes it immediately.
/// - `Many`: Reusable. The token can be claimed multiple times under the
///   resource kind's constraints.
///
/// The compile-time shot discipline for resource kinds stays on
/// `hibana::substrate::cap::{One, Many}`; `CapShot` is the runtime encoding of
/// that decision inside a minted token, not the primary API for choosing shot
/// discipline.
///
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CapShot {
    /// Single-use capability (affine linearity).
    One = 0,
    /// Reusable capability (requires MultiSafe constraints).
    Many = 1,
}

impl CapShot {
    #[inline]
    pub fn from_u8(val: u8) -> Option<Self> {
        match val {
            0 => Some(Self::One),
            1 => Some(Self::Many),
            _ => None,
        }
    }

    #[inline]
    pub fn as_u8(self) -> u8 {
        self as u8
    }
}

/// Atomic control-plane execution unit owned by hibana core.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ControlOp {
    RouteDecision = 0,
    LoopContinue = 1,
    LoopBreak = 2,
    StateSnapshot = 3,
    StateRestore = 4,
    TopologyBegin = 5,
    TopologyAck = 6,
    TopologyCommit = 7,
    CapDelegate = 8,
    AbortBegin = 9,
    AbortAck = 10,
    Fence = 11,
    TxCommit = 12,
    TxAbort = 13,
}

impl ControlOp {
    #[inline]
    pub const fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::RouteDecision),
            1 => Some(Self::LoopContinue),
            2 => Some(Self::LoopBreak),
            3 => Some(Self::StateSnapshot),
            4 => Some(Self::StateRestore),
            5 => Some(Self::TopologyBegin),
            6 => Some(Self::TopologyAck),
            7 => Some(Self::TopologyCommit),
            8 => Some(Self::CapDelegate),
            9 => Some(Self::AbortBegin),
            10 => Some(Self::AbortAck),
            11 => Some(Self::Fence),
            12 => Some(Self::TxCommit),
            13 => Some(Self::TxAbort),
            _ => None,
        }
    }

    #[inline]
    pub const fn as_u8(self) -> u8 {
        self as u8
    }
}

/// Transport crossing mode for control messages.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ControlPath {
    Local = 0,
    Wire = 1,
}

impl ControlPath {
    #[inline]
    pub const fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::Local),
            1 => Some(Self::Wire),
            _ => None,
        }
    }

    #[inline]
    pub const fn as_u8(self) -> u8 {
        self as u8
    }
}

/// Descriptor-first fixed control header.
///
/// This is a wire codec carrier. Callers must use `encode` / `decode` rather
/// than relying on struct layout.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CapHeader {
    version: u8,
    sid: SessionId,
    lane: Lane,
    role: u8,
    tag: u8,
    op: ControlOp,
    path: ControlPath,
    shot: CapShot,
    scope_kind: ControlScopeKind,
    flags: u8,
    scope_id: u16,
    epoch: u16,
    handle: [u8; CAP_HEADER_LEN - CAP_CONTROL_HEADER_FIXED_LEN],
}

impl CapHeader {
    const KNOWN_FLAGS_MASK: u8 = 0b0000_0001;

    #[inline]
    pub const fn new(
        sid: SessionId,
        lane: Lane,
        role: u8,
        tag: u8,
        op: ControlOp,
        path: ControlPath,
        shot: CapShot,
        scope_kind: ControlScopeKind,
        flags: u8,
        scope_id: u16,
        epoch: u16,
        handle: [u8; CAP_HEADER_LEN - CAP_CONTROL_HEADER_FIXED_LEN],
    ) -> Self {
        Self {
            version: 1,
            sid,
            lane,
            role,
            tag,
            op,
            path,
            shot,
            scope_kind,
            flags,
            scope_id,
            epoch,
            handle,
        }
    }

    #[inline]
    pub fn encode(&self, out: &mut [u8; CAP_HEADER_LEN]) {
        out[0] = self.version;
        out[1..5].copy_from_slice(&self.sid.raw().to_be_bytes());
        out[5] = self.lane.as_wire();
        out[6] = self.role;
        out[7] = self.tag;
        out[8] = self.op.as_u8();
        out[9] = self.path.as_u8();
        out[10] = self.shot.as_u8();
        out[11] = self.scope_kind as u8;
        out[12] = self.flags;
        out[13..15].copy_from_slice(&self.scope_id.to_be_bytes());
        out[15..17].copy_from_slice(&self.epoch.to_be_bytes());
        out[17..].copy_from_slice(&self.handle);
    }

    #[inline]
    pub fn decode(raw: [u8; CAP_HEADER_LEN]) -> Result<Self, CapError> {
        if raw[0] != 1 {
            return Err(CapError::Mismatch);
        }
        let op = ControlOp::from_u8(raw[8]).ok_or(CapError::Mismatch)?;
        let path = ControlPath::from_u8(raw[9]).ok_or(CapError::Mismatch)?;
        let shot = CapShot::from_u8(raw[10]).ok_or(CapError::Mismatch)?;
        let scope_kind = ControlScopeKind::from_u8(raw[11]).ok_or(CapError::Mismatch)?;
        if raw[12] & !Self::KNOWN_FLAGS_MASK != 0 {
            return Err(CapError::Mismatch);
        }
        let mut handle = [0u8; CAP_HEADER_LEN - CAP_CONTROL_HEADER_FIXED_LEN];
        handle.copy_from_slice(&raw[17..]);
        Ok(Self {
            version: raw[0],
            sid: SessionId::new(u32::from_be_bytes([raw[1], raw[2], raw[3], raw[4]])),
            lane: Lane::new(u32::from(raw[5])),
            role: raw[6],
            tag: raw[7],
            op,
            path,
            shot,
            scope_kind,
            flags: raw[12],
            scope_id: u16::from_be_bytes([raw[13], raw[14]]),
            epoch: u16::from_be_bytes([raw[15], raw[16]]),
            handle,
        })
    }

    #[inline]
    pub const fn sid(&self) -> SessionId {
        self.sid
    }

    #[inline]
    pub const fn lane(&self) -> Lane {
        self.lane
    }

    #[inline]
    pub const fn role(&self) -> u8 {
        self.role
    }

    #[inline]
    pub const fn tag(&self) -> u8 {
        self.tag
    }

    #[inline]
    pub const fn op(&self) -> ControlOp {
        self.op
    }

    #[inline]
    pub const fn path(&self) -> ControlPath {
        self.path
    }

    #[inline]
    pub const fn shot(&self) -> CapShot {
        self.shot
    }

    #[inline]
    pub const fn scope_kind(&self) -> ControlScopeKind {
        self.scope_kind
    }

    #[inline]
    pub const fn flags(&self) -> u8 {
        self.flags
    }

    #[inline]
    pub const fn scope_id(&self) -> u16 {
        self.scope_id
    }

    #[inline]
    pub const fn epoch(&self) -> u16 {
        self.epoch
    }

    #[inline]
    pub const fn handle(&self) -> &[u8; CAP_HEADER_LEN - CAP_CONTROL_HEADER_FIXED_LEN] {
        &self.handle
    }
}

#[inline]
pub(crate) const fn is_canonical_endpoint_header(header: CapHeader) -> bool {
    header.tag() == EndpointResource::TAG
        && matches!(header.op(), ControlOp::Fence)
        && matches!(header.path(), ControlPath::Local)
        && matches!(header.shot(), CapShot::One)
        && matches!(header.scope_kind(), ControlScopeKind::None)
        && header.flags() == 0
        && header.scope_id() == 0
        && header.epoch() == 0
}

#[inline]
fn decode_canonical_endpoint_identity(
    token: &GenericCapToken<EndpointResource>,
) -> Result<(CapHeader, EndpointHandle), CapError> {
    let header = token.control_header()?;
    if !is_canonical_endpoint_header(header) {
        return Err(CapError::Mismatch);
    }

    let mut handle =
        EndpointResource::decode_handle(token.handle_bytes()).map_err(|_| CapError::Mismatch)?;
    let matches_header =
        handle.sid == header.sid() && handle.lane == header.lane() && handle.role == header.role();
    let matches_encoding = EndpointResource::encode_handle(&handle) == token.handle_bytes();
    if !matches_header || !matches_encoding {
        EndpointResource::zeroize(&mut handle);
        return Err(CapError::Mismatch);
    }

    Ok((header, handle))
}

#[inline]
const fn scope_from_header(header: CapHeader) -> Option<ScopeId> {
    match header.scope_kind() {
        ControlScopeKind::Route => Some(ScopeId::route(header.scope_id())),
        ControlScopeKind::Loop => Some(ScopeId::loop_scope(header.scope_id())),
        _ => None,
    }
}

/// Typed view over a capability handle exposed to the EPF VM.
///
/// The view carries the original resource payload together with the structured
/// scope metadata recovered from the descriptor-first control header.
pub struct HandleView<'ctx, K: ResourceKind> {
    raw: &'ctx [u8; CAP_HANDLE_LEN],
    handle: K::Handle,
    scope: Option<ScopeId>,
}

impl<'ctx, K: ResourceKind> HandleView<'ctx, K> {
    #[inline]
    pub(crate) fn decode(
        raw: &'ctx [u8; CAP_HANDLE_LEN],
        scope: Option<ScopeId>,
    ) -> Result<Self, CapError> {
        let handle = K::decode_handle(*raw)?;
        Ok(Self { raw, handle, scope })
    }

    /// Borrow the encoded resource payload.
    #[inline]
    pub fn bytes(&self) -> &'ctx [u8; CAP_HANDLE_LEN] {
        self.raw
    }

    /// Borrow the decoded handle payload.
    #[inline]
    pub fn handle(&self) -> &K::Handle {
        &self.handle
    }

    /// Structured scope identifier encoded in this handle, when available.
    #[inline]
    pub fn scope(&self) -> Option<ScopeId> {
        self.scope
    }
}

impl<'ctx, K: ResourceKind> Drop for HandleView<'ctx, K> {
    fn drop(&mut self) {
        K::zeroize(&mut self.handle);
    }
}

/// Capability operation errors.
///
/// All errors are non-panicking and should be handled by the caller.
///
/// # Observability
/// Discriminated variants preserve debugging information while maintaining
/// security: `InvalidMac` identifies forgery attempts, `Mismatch` indicates
/// field validation failures (kind/shot/sid/lane), and `TableFull` tracks
/// capacity exhaustion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CapError {
    /// Token not found in capability table.
    UnknownToken,
    /// Session ID or lane does not exist in local Rendezvous.
    WrongSessionOrLane,
    /// One-shot token already consumed.
    Exhausted,
    /// MAC tag verification failed (possible forgery attempt).
    ///
    /// This indicates either:
    /// - Cryptographic forgery (attacker guessing MAC tags)
    /// - Key mismatch between minting and claiming Rendezvous
    /// - Corrupted token during transfer
    InvalidMac,
    /// Capability table is full (64 entries).
    ///
    /// This can happen if too many capabilities are minted without being claimed,
    /// or if Many-shot capabilities accumulate over time.
    TableFull,
    /// Token field mismatch (kind/shot/sid/lane).
    ///
    /// This indicates the token was found in CapTable (nonce matched) but
    /// one or more fields didn't match expected values. This is distinct from
    /// `UnknownToken` (nonce not found) and helps diagnose configuration errors.
    Mismatch,
}

/// Opaque capability-token payload carried by control messages.
///
/// Protocol authors name this type in a `g::Msg<..., GenericCapToken<K>, K>`
/// payload. Descriptor metadata and token header details live under the
/// substrate capability metadata bucket; ordinary choreography code should only
/// pass the token as an opaque payload.
#[repr(C)]
#[derive(Debug, PartialEq, Eq)]
pub struct GenericCapToken<K: ResourceKind> {
    bytes: [u8; CAP_TOKEN_LEN],
    _marker: PhantomData<K>,
}

impl<K: ResourceKind> Copy for GenericCapToken<K> {}

impl<K: ResourceKind> Clone for GenericCapToken<K> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<K: ResourceKind> GenericCapToken<K> {
    pub const AUTO: Self = Self {
        bytes: [0u8; CAP_TOKEN_LEN],
        _marker: PhantomData,
    };

    #[inline(always)]
    pub const fn from_bytes(bytes: [u8; CAP_TOKEN_LEN]) -> Self {
        Self {
            bytes,
            _marker: PhantomData,
        }
    }

    #[inline(always)]
    pub const fn into_bytes(self) -> [u8; CAP_TOKEN_LEN] {
        self.bytes
    }

    #[inline]
    fn header_slice(&self) -> &[u8; CAP_HEADER_LEN] {
        self.bytes[CAP_NONCE_LEN..CAP_NONCE_LEN + CAP_HEADER_LEN]
            .try_into()
            .expect("CAP_HEADER_LEN is compile-time constant")
    }

    pub(crate) fn nonce(&self) -> [u8; CAP_NONCE_LEN] {
        let mut nonce = [0u8; CAP_NONCE_LEN];
        nonce.copy_from_slice(&self.bytes[0..CAP_NONCE_LEN]);
        nonce
    }

    fn raw_header(&self) -> [u8; CAP_HEADER_LEN] {
        let mut header = [0u8; CAP_HEADER_LEN];
        header.copy_from_slice(self.header_slice());
        header
    }

    #[inline]
    pub(crate) fn control_header(&self) -> Result<CapHeader, CapError> {
        CapHeader::decode(self.raw_header())
    }

    /// Extract the structured scope identifier encoded in the handle, if any.
    pub fn scope(&self) -> Option<ScopeId> {
        self.as_view().ok().and_then(|view| view.scope())
    }

    pub(crate) fn handle_bytes(&self) -> [u8; CAP_HANDLE_LEN] {
        *self.handle_bytes_ref()
    }

    #[inline]
    pub(crate) fn is_auto(&self) -> bool {
        self.bytes == [0u8; CAP_TOKEN_LEN]
    }

    /// Get a reference to the handle bytes within the token.
    ///
    /// This is a zero-copy operation that returns a slice reference
    /// to the handle payload embedded in the token header.
    #[inline(always)]
    pub(crate) fn handle_bytes_ref(&self) -> &[u8; CAP_HANDLE_LEN] {
        self.header_slice()
            [CAP_CONTROL_HEADER_FIXED_LEN..CAP_CONTROL_HEADER_FIXED_LEN + CAP_HANDLE_LEN]
            .try_into()
            .expect("CAP_HANDLE_LEN is compile-time constant")
    }

    pub fn decode_handle(&self) -> Result<K::Handle, CapError> {
        let header = self.control_header()?;
        if header.tag() != K::TAG {
            return Err(CapError::Mismatch);
        }
        K::decode_handle(self.handle_bytes())
    }

    /// Extract a HandleView from this token.
    ///
    /// This provides zero-copy access to the embedded handle and its capabilities.
    /// The HandleView lifetime is bounded by the token's lifetime.
    ///
    /// # Type Safety
    ///
    /// The compiler enforces:
    /// - `K` matches the token's ResourceKind (via type parameter)
    /// - HandleView cannot outlive the token (via lifetime `'_`)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let token = flow.mint_token::<LoopContinueKind>()?;
    /// let view = token.as_view()?;
    /// // inspect view.handle() and scope metadata.
    /// ```
    pub fn as_view(&self) -> Result<HandleView<'_, K>, CapError> {
        let header = self.control_header()?;
        HandleView::decode(self.handle_bytes_ref(), scope_from_header(header))
    }
}

impl GenericCapToken<EndpointResource> {
    #[cfg(test)]
    #[inline]
    pub(crate) fn endpoint_header(&self) -> Result<CapHeader, CapError> {
        let (header, mut handle) = decode_canonical_endpoint_identity(self)?;
        EndpointResource::zeroize(&mut handle);
        Ok(header)
    }

    #[inline]
    pub(crate) fn endpoint_identity(&self) -> Result<EndpointHandle, CapError> {
        decode_canonical_endpoint_identity(self).map(|(_, handle)| handle)
    }
}

impl<K: ResourceKind> WireEncode for GenericCapToken<K> {
    fn encoded_len(&self) -> Option<usize> {
        Some(CAP_TOKEN_LEN)
    }

    fn encode_into(&self, out: &mut [u8]) -> Result<usize, CodecError> {
        if out.len() < CAP_TOKEN_LEN {
            return Err(CodecError::Truncated);
        }
        out[0..CAP_TOKEN_LEN].copy_from_slice(&self.bytes);
        Ok(CAP_TOKEN_LEN)
    }
}

impl<K: ResourceKind> WirePayload for GenericCapToken<K> {
    type Decoded<'a> = Self;

    fn decode_payload<'a>(input: Payload<'a>) -> Result<Self::Decoded<'a>, CodecError> {
        let bytes_in = input.as_bytes();
        if bytes_in.len() < CAP_TOKEN_LEN {
            return Err(CodecError::Truncated);
        }
        if bytes_in.len() != CAP_TOKEN_LEN {
            return Err(CodecError::Invalid("trailing bytes after GenericCapToken"));
        }
        let mut bytes = [0u8; CAP_TOKEN_LEN];
        bytes.copy_from_slice(bytes_in);
        Ok(Self {
            bytes,
            _marker: PhantomData,
        })
    }
}

/// Zero-sized proof that MAC tag verification succeeded.
///
/// This witness cannot be constructed outside of this module, ensuring that
/// CapTable lookup can only happen after cryptographic verification.
///
/// # Security
/// This prevents internal code from bypassing MAC validation by directly
/// Zero-sized proof that a capability was validated through `Rendezvous::claim_cap()`.
///
/// This witness cannot be constructed outside of this module, ensuring that
/// `VerifiedCap` instances can only be created by the secure claim path.
///
/// # Security
/// This prevents forgery attacks where an attacker constructs a `VerifiedCap`
/// directly without going through MAC validation and CapTable lookup.
#[derive(Clone, Copy, Debug)]
struct Witness(());

/// Verified capability after successful `claim()` operation.
///
/// This is an affine proof object: the MAC tag has been verified and the token
/// has been consumed (for one-shot caps).
///
/// # Security
/// This struct cannot be constructed directly - it requires a private `Witness`
/// that can only be obtained through `Rendezvous::claim_cap()`. This ensures all
/// `VerifiedCap` instances have been cryptographically validated.
///
/// # Usage
/// ```rust,ignore
/// let (cursor, token) = cursor.recv::<DelegateMsg>().await?;
/// let token = cursor.recv::<DelegateMsg>().await?.1;
/// let verified = rendezvous.claim_cap(&token)?;
/// ```
#[derive(Clone, Debug)]
pub(crate) struct VerifiedCap<K: ResourceKind> {
    handle: K::Handle,
    _marker: PhantomData<K>,
    /// Unforgeable witness proving this capability was validated.
    ///
    /// This field is private and can only be set by `Rendezvous::claim_cap()`,
    /// preventing direct construction of `VerifiedCap`.
    _witness: Witness,
}

impl<K: ResourceKind> VerifiedCap<K> {
    pub(crate) fn new(handle: K::Handle) -> Self {
        Self {
            handle,
            _marker: PhantomData,
            _witness: Witness(()),
        }
    }
}

impl<K: ResourceKind> Drop for VerifiedCap<K> {
    fn drop(&mut self) {
        K::zeroize(&mut self.handle);
    }
}

// ============================================================================
// Default Implementations (No Crypto - Trusted Domains)
// ============================================================================

// Null MAC for trusted domains (same process/same node).
//
// Use this when all roles share the same Rendezvous or communicate over
// trusted channels (e.g., in-process, localhost, secure enclave).
//
// # Security
// - **Only safe in trusted domains** where capability forgery is not a threat
// - No authentication tag (TAG_LEN = 0)
// - Zero-cost abstraction (no computation)
//
// # When to Use
// - Single-process applications with shared Rendezvous
// - Localhost communication (127.0.0.1)
// - Trusted secure enclaves (SGX, TrustZone)
// - Local validation domains
//
// # When NOT to Use
// - Multi-node distributed systems
// - Untrusted network communication
// - Public-facing services
// - Any scenario where token forgery is a concern

#[cfg(test)]
mod tests {
    use super::{
        CapError, CapHeader, CapShot, ControlOp, ControlPath, ControlResourceKind,
        ControlScopeKind, E0, EndpointHandle, EndpointResource, GenericCapToken, HandleView, Owner,
        ResourceKind,
    };
    use crate::{
        control::{
            brand::with_brand,
            cap::resource_kinds::{LoopContinueKind, LoopDecisionHandle},
            types::{Lane, SessionId},
        },
        global::const_dsl::ScopeId,
        transport::wire::{CodecError, Payload, WirePayload},
    };

    fn endpoint_header_fixture() -> [u8; super::CAP_HEADER_LEN] {
        let handle = EndpointHandle::new(SessionId::new(7), Lane::new(3), 1);
        let mut header = [0u8; super::CAP_HEADER_LEN];
        CapHeader::new(
            handle.sid,
            handle.lane,
            handle.role,
            EndpointResource::TAG,
            ControlOp::Fence,
            ControlPath::Local,
            CapShot::One,
            ControlScopeKind::None,
            0,
            0,
            0,
            EndpointResource::encode_handle(&handle),
        )
        .encode(&mut header);
        header
    }

    fn token_from_wire<K: ResourceKind>(
        nonce: [u8; super::CAP_NONCE_LEN],
        header: [u8; super::CAP_HEADER_LEN],
        tag: [u8; super::CAP_TAG_LEN],
    ) -> GenericCapToken<K> {
        let mut bytes = [0u8; super::CAP_TOKEN_LEN];
        bytes[..super::CAP_NONCE_LEN].copy_from_slice(&nonce);
        bytes[super::CAP_NONCE_LEN..super::CAP_NONCE_LEN + super::CAP_HEADER_LEN]
            .copy_from_slice(&header);
        bytes[super::CAP_NONCE_LEN + super::CAP_HEADER_LEN..].copy_from_slice(&tag);
        GenericCapToken::from_bytes(bytes)
    }

    fn endpoint_token_with_mutated_header(
        mutate: fn(&mut [u8; super::CAP_HEADER_LEN]),
    ) -> GenericCapToken<EndpointResource> {
        let mut header = endpoint_header_fixture();
        mutate(&mut header);
        token_from_wire::<EndpointResource>(
            [0u8; super::CAP_NONCE_LEN],
            header,
            [0u8; super::CAP_TAG_LEN],
        )
    }

    #[test]
    fn owner_binds_rendezvous_brand() {
        with_brand(|rv_brand| {
            let owner: Owner<'_, E0> = Owner::new(rv_brand.guard());
            let _ = owner;
        });
    }

    #[test]
    fn handle_view_decodes_payload() {
        let handle = LoopDecisionHandle {
            sid: 12,
            lane: 4,
            scope: ScopeId::route(3),
        };
        let payload = LoopContinueKind::encode_handle(&handle);
        let view =
            HandleView::<LoopContinueKind>::decode(&payload, Some(handle.scope)).expect("decode");
        assert_eq!(view.bytes(), &payload);
        assert_eq!(view.handle(), &handle);
        assert_eq!(view.scope(), Some(handle.scope));
    }

    #[test]
    fn handle_view_decodes_endpoint_payload() {
        let handle = EndpointHandle::new(SessionId::new(1), Lane::new(0), 3);
        let payload = EndpointResource::encode_handle(&handle);
        let view = HandleView::<EndpointResource>::decode(&payload, None).expect("decode");
        assert_eq!(view.bytes(), &payload);
        assert_eq!(view.handle(), &handle);
        assert_eq!(view.scope(), None);
    }

    /// Regression test: lending a `HandleView` twice must reject the second
    /// attempt with `CapError::Consumed`.
    ///
    /// This mirrors rollback/abort scenarios:
    /// 1. Lend out a `HandleView`
    /// 2. Operation aborts midway
    /// 3. Retrying with the same token should be rejected
    #[test]
    fn simulate_abort_then_retry() {
        let handle = EndpointHandle::new(SessionId::new(42), Lane::new(1), 2);
        let payload = EndpointResource::encode_handle(&handle);

        // First decode succeeds
        let view1 = HandleView::<EndpointResource>::decode(&payload, None);
        assert!(view1.is_ok());
        let view1 = view1.unwrap();
        assert_eq!(view1.handle(), &handle);

        // Second decode uses the same payload again. HandleView::decode is
        // stateless; the rendezvous CapTable owns consumed tracking.
        // See capability.rs::one_shot_exhausts_on_second_claim for that test.
        let view2 = HandleView::<EndpointResource>::decode(&payload, None);
        assert!(view2.is_ok());
    }

    /// Test GenericCapToken::as_view() ergonomic API
    ///
    /// This tests the mint → HandleView extraction chain:
    /// 1. Create a token with embedded handle
    /// 2. Extract HandleView via as_view()
    /// 3. Verify descriptor/header fields survive round-trip
    /// 4. Verify handle bytes survive round-trip
    #[test]
    fn generic_cap_token_as_view() {
        use super::{CAP_HEADER_LEN, CAP_NONCE_LEN, CAP_TAG_LEN};

        let handle = EndpointHandle::new(SessionId::new(7), Lane::new(3), 1);
        let handle_bytes = EndpointResource::encode_handle(&handle);

        let mut header = [0u8; CAP_HEADER_LEN];
        CapHeader::new(
            handle.sid,
            handle.lane,
            handle.role,
            EndpointResource::TAG,
            ControlOp::Fence,
            crate::control::cap::mint::ControlPath::Local,
            CapShot::One,
            ControlScopeKind::None,
            0,
            0,
            0,
            handle_bytes,
        )
        .encode(&mut header);

        let token =
            token_from_wire::<EndpointResource>([0u8; CAP_NONCE_LEN], header, [0u8; CAP_TAG_LEN]);

        // Extract HandleView via as_view()
        let view = token.as_view().expect("as_view should succeed");

        // Verify handle matches
        assert_eq!(view.handle(), &handle);
        // Verify bytes match
        assert_eq!(view.bytes(), &handle_bytes);
        let header = token.control_header().expect("header");
        assert_eq!(header.sid(), handle.sid);
        assert_eq!(header.lane(), handle.lane);
        assert_eq!(header.role(), handle.role);
    }

    #[test]
    fn cap_header_decode_rejects_unknown_atomic_fields() {
        let mut raw = [0u8; super::CAP_HEADER_LEN];
        CapHeader::new(
            SessionId::new(7),
            Lane::new(3),
            1,
            LoopContinueKind::TAG,
            LoopContinueKind::OP,
            LoopContinueKind::PATH,
            CapShot::One,
            LoopContinueKind::SCOPE,
            0,
            1,
            2,
            LoopContinueKind::encode_handle(&LoopDecisionHandle {
                sid: 7,
                lane: 3,
                scope: ScopeId::loop_scope(1),
            }),
        )
        .encode(&mut raw);

        for (index, value) in [(8usize, 0xFF), (9, 0xFF), (10, 0xFF), (11, 0xFF)] {
            let mut corrupted = raw;
            corrupted[index] = value;
            assert!(
                matches!(CapHeader::decode(corrupted), Err(super::CapError::Mismatch)),
                "unknown control header field at byte {index} must fail closed",
            );
        }
    }

    #[test]
    fn cap_header_decode_rejects_reserved_flags() {
        let mut raw = [0u8; super::CAP_HEADER_LEN];
        CapHeader::new(
            SessionId::new(7),
            Lane::new(3),
            1,
            LoopContinueKind::TAG,
            LoopContinueKind::OP,
            LoopContinueKind::PATH,
            CapShot::One,
            LoopContinueKind::SCOPE,
            0,
            1,
            2,
            LoopContinueKind::encode_handle(&LoopDecisionHandle {
                sid: 7,
                lane: 3,
                scope: ScopeId::loop_scope(1),
            }),
        )
        .encode(&mut raw);
        raw[12] = 0x80;

        assert!(
            matches!(CapHeader::decode(raw), Err(super::CapError::Mismatch)),
            "reserved control header flags must fail closed",
        );
    }

    #[test]
    fn generic_cap_token_decode_requires_exact_wire_length() {
        let exact = GenericCapToken::<()>::AUTO.into_bytes();
        assert!(
            <GenericCapToken<()> as WirePayload>::decode_payload(Payload::new(&exact)).is_ok(),
            "exact-size capability tokens must decode"
        );

        let mut short = [0u8; super::CAP_TOKEN_LEN - 1];
        short.copy_from_slice(&exact[..super::CAP_TOKEN_LEN - 1]);
        assert!(matches!(
            <GenericCapToken<()> as WirePayload>::decode_payload(Payload::new(&short)),
            Err(CodecError::Truncated)
        ));

        let mut trailing = [0u8; super::CAP_TOKEN_LEN + 1];
        trailing[..super::CAP_TOKEN_LEN].copy_from_slice(&exact);
        trailing[super::CAP_TOKEN_LEN] = 0xA5;
        assert!(
            matches!(
                <GenericCapToken<()> as WirePayload>::decode_payload(Payload::new(&trailing)),
                Err(CodecError::Invalid("trailing bytes after GenericCapToken"))
            ),
            "control tokens are fixed-size and must reject ignored trailing bytes"
        );
    }

    #[test]
    fn malformed_generic_cap_token_preserves_raw_header_bytes() {
        let handle = LoopDecisionHandle {
            sid: 7,
            lane: 3,
            scope: ScopeId::loop_scope(1),
        };
        let mut header = [0u8; super::CAP_HEADER_LEN];
        CapHeader::new(
            SessionId::new(handle.sid),
            Lane::new(handle.lane as u32),
            5,
            LoopContinueKind::TAG,
            LoopContinueKind::OP,
            LoopContinueKind::PATH,
            CapShot::One,
            LoopContinueKind::SCOPE,
            0,
            1,
            2,
            LoopContinueKind::encode_handle(&handle),
        )
        .encode(&mut header);
        header[8] = 0xFF;

        let token = token_from_wire::<LoopContinueKind>(
            [0u8; super::CAP_NONCE_LEN],
            header,
            [0u8; super::CAP_TAG_LEN],
        );

        assert!(matches!(token.control_header(), Err(CapError::Mismatch)));
        assert_eq!(token.raw_header(), header);
    }

    #[test]
    fn malformed_generic_cap_token_decode_handle_fails_closed_for_unit_kind() {
        let handle = EndpointHandle::new(SessionId::new(9), Lane::new(2), 4);
        let mut header = [0u8; super::CAP_HEADER_LEN];
        CapHeader::new(
            handle.sid,
            handle.lane,
            handle.role,
            EndpointResource::TAG,
            ControlOp::Fence,
            ControlPath::Local,
            CapShot::One,
            ControlScopeKind::None,
            0,
            0,
            0,
            EndpointResource::encode_handle(&handle),
        )
        .encode(&mut header);
        header[9] = 0xFF;

        let token = token_from_wire::<()>(
            [0u8; super::CAP_NONCE_LEN],
            header,
            [0u8; super::CAP_TAG_LEN],
        );

        assert!(matches!(token.control_header(), Err(CapError::Mismatch)));
        assert!(matches!(token.decode_handle(), Err(CapError::Mismatch)));
    }

    #[test]
    fn endpoint_header_rejects_noncanonical_decodable_fields() {
        fn mutate_tag(header: &mut [u8; super::CAP_HEADER_LEN]) {
            header[7] = LoopContinueKind::TAG;
        }

        fn mutate_op(header: &mut [u8; super::CAP_HEADER_LEN]) {
            header[8] = ControlOp::TopologyBegin.as_u8();
        }

        fn mutate_path(header: &mut [u8; super::CAP_HEADER_LEN]) {
            header[9] = ControlPath::Wire.as_u8();
        }

        fn mutate_shot(header: &mut [u8; super::CAP_HEADER_LEN]) {
            header[10] = CapShot::Many.as_u8();
        }

        fn mutate_scope_kind(header: &mut [u8; super::CAP_HEADER_LEN]) {
            header[11] = ControlScopeKind::Route as u8;
        }

        fn mutate_flags(header: &mut [u8; super::CAP_HEADER_LEN]) {
            header[12] = 0x01;
        }

        fn mutate_scope_id(header: &mut [u8; super::CAP_HEADER_LEN]) {
            header[13..15].copy_from_slice(&1u16.to_be_bytes());
        }

        fn mutate_epoch(header: &mut [u8; super::CAP_HEADER_LEN]) {
            header[15..17].copy_from_slice(&1u16.to_be_bytes());
        }

        let cases: &[(&str, fn(&mut [u8; super::CAP_HEADER_LEN]))] = &[
            ("tag", mutate_tag),
            ("op", mutate_op),
            ("path", mutate_path),
            ("shot", mutate_shot),
            ("scope_kind", mutate_scope_kind),
            ("flags", mutate_flags),
            ("scope_id", mutate_scope_id),
            ("epoch", mutate_epoch),
        ];

        for (name, mutate) in cases {
            let token = endpoint_token_with_mutated_header(*mutate);
            assert!(
                token.control_header().is_ok(),
                "{name} mutation must stay within decodable header space",
            );
            assert!(
                matches!(token.endpoint_header(), Err(CapError::Mismatch)),
                "{name} mutation must be rejected by endpoint canonical validation",
            );
        }
    }

    #[test]
    fn endpoint_identity_rejects_decodable_handle_payload_mismatches() {
        fn endpoint_token_with_mutated_handle(
            mutate: fn(&mut [u8; super::CAP_HANDLE_LEN]),
        ) -> GenericCapToken<EndpointResource> {
            let mut header = endpoint_header_fixture();
            let handle = &mut header[super::CAP_CONTROL_HEADER_FIXED_LEN
                ..super::CAP_CONTROL_HEADER_FIXED_LEN + super::CAP_HANDLE_LEN];
            let handle: &mut [u8; super::CAP_HANDLE_LEN] =
                handle.try_into().expect("endpoint handle payload must fit");
            mutate(handle);
            token_from_wire::<EndpointResource>(
                [0u8; super::CAP_NONCE_LEN],
                header,
                [0u8; super::CAP_TAG_LEN],
            )
        }

        fn mutate_sid(handle: &mut [u8; super::CAP_HANDLE_LEN]) {
            handle[0] ^= 0x01;
        }

        fn mutate_lane(handle: &mut [u8; super::CAP_HANDLE_LEN]) {
            handle[4] ^= 0x01;
        }

        fn mutate_role(handle: &mut [u8; super::CAP_HANDLE_LEN]) {
            handle[5] ^= 0x01;
        }

        fn mutate_trailing_padding(handle: &mut [u8; super::CAP_HANDLE_LEN]) {
            handle[6] = 0x7F;
        }

        let cases: &[(&str, fn(&mut [u8; super::CAP_HANDLE_LEN]))] = &[
            ("sid", mutate_sid),
            ("lane", mutate_lane),
            ("role", mutate_role),
            ("trailing_padding", mutate_trailing_padding),
        ];

        for (name, mutate) in cases {
            let token = endpoint_token_with_mutated_handle(*mutate);
            assert!(
                token.control_header().is_ok(),
                "{name} mutation must preserve fixed header decoding",
            );
            assert!(
                token.decode_handle().is_ok(),
                "{name} mutation must stay in decodable handle space",
            );
            assert!(
                matches!(token.endpoint_header(), Err(CapError::Mismatch)),
                "{name} mutation must be rejected by endpoint header canonical validation",
            );
            assert!(
                matches!(token.endpoint_identity(), Err(CapError::Mismatch)),
                "{name} mutation must be rejected by endpoint identity validation",
            );
        }
    }

    #[cfg(feature = "std")]
    mod proptests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn handle_view_roundtrip_property(
                sid in 0u32..1000,
                lane in 0u32..64,
                role in 0u8..16
            ) {
                let sid = SessionId::new(sid);
                let lane = Lane::new(lane);
                let handle = EndpointHandle::new(sid, lane, role);
                let payload = EndpointResource::encode_handle(&handle);
                let view = HandleView::<EndpointResource>::decode(&payload, None).expect("decode");
                prop_assert_eq!(view.handle(), &handle);
                prop_assert_eq!(view.bytes(), &payload);
            }

            /// Property test for `LoopContinueKind`.
            ///
            /// The handle is represented as a `(u32, u8, scope)` payload;
            /// verify that HandleView preserves the typed handle and bytes.
            #[test]
            fn handle_view_loop_continue_roundtrip(
                generation in 0u32..10000,
                lane in any::<u8>()
            ) {
                let handle = LoopDecisionHandle {
                    sid: generation,
                    lane,
                    scope: ScopeId::loop_scope(1),
                };
                let payload = LoopContinueKind::encode_handle(&handle);
                let view = HandleView::<LoopContinueKind>::decode(&payload, Some(handle.scope)).expect("decode");
                prop_assert_eq!(view.handle(), &handle);
                prop_assert_eq!(view.bytes(), &payload);
            }
        }
    }
}