chio-kernel-core 0.1.2

Portable (no_std + alloc) Chio kernel core: pure verdict evaluation, capability verification, and receipt signing
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
extern crate alloc;

use alloc::string::ToString;
use alloc::vec;
use alloc::vec::Vec;

use chio_core_types::capability::{
    scope::{ChioScope, Operation, ToolGrant},
    token::CapabilityToken,
};
use chio_core_types::crypto::{PublicKey, Signature, SigningAlgorithm, SigningBackend};
use chio_core_types::receipt::{
    body::ChioReceiptBody, decision::Decision, decision::ToolCallAction, kinds::TrustLevel,
};
use serde_json::Value;

use crate::capability_verify::CapabilityError;
use crate::clock::FixedClock;
use crate::evaluate::EvaluateInput;
use crate::formal_core::{
    composite_quota_authorize, family_binding_preserved, guard_pipeline_allows,
    monetary_cap_is_subset_by_parts, optional_u32_cap_is_subset, quota_maximum_compatible,
    receipt_fields_coupled, required_true_is_preserved, revocation_snapshot_denies,
    threshold_distinct_eligible_signers, time_window_valid, GuardStep,
};
use crate::guard::PortableToolCallRequest;
use crate::normalized::{NormalizedOperation, NormalizedScope, NormalizedToolGrant};
use crate::receipts::ReceiptSigningError;
use crate::scope::resolve_matching_grants;
use crate::{
    evaluate, sign_receipt, sign_receipt_relaying_trusted_body, verify_capability, Verdict,
};

fn public_key(seed: u8) -> PublicKey {
    let mut bytes = [seed; 65];
    bytes[0] = 0x04;
    PublicKey::from_p256_sec1(&bytes)
        .unwrap_or_else(|_| unreachable!("deterministic P-256 key fixture is well-formed"))
}

fn p384_public_key(seed: u8) -> PublicKey {
    let mut bytes = [seed; 97];
    bytes[0] = 0x04;
    PublicKey::from_p384_sec1(&bytes)
        .unwrap_or_else(|_| unreachable!("deterministic P-384 key fixture is well-formed"))
}

fn grant(server: &str, tool: &str) -> ToolGrant {
    ToolGrant {
        server_id: server.to_string(),
        tool_name: tool.to_string(),
        operations: vec![Operation::Invoke],
        constraints: vec![],
        max_invocations: None,
        max_cost_per_invocation: None,
        max_total_cost: None,
        dpop_required: None,
    }
}

fn unsigned_capability(ttl: u64) -> CapabilityToken {
    CapabilityToken {
        schema: chio_core_types::capability::token::CHIO_CAPABILITY_SCHEMA.to_string(),
        id: "cap-public-kani".to_string(),
        issuer: public_key(7),
        subject: public_key(9),
        scope: ChioScope {
            grants: vec![grant("s", "r")],
            ..ChioScope::default()
        },
        issued_at: 10,
        expires_at: 10 + ttl,
        delegation_chain: vec![],
        algorithm: None,
        caveats: vec![],
        scope_attenuations: None,
        attenuation_proof: None,
        budget_share_bps: None,
        aggregate_invocation_budget: None,
        signature: Signature::from_bytes(&[0; 64]),
    }
}

fn path_arguments(path: &str) -> Value {
    Value::String(path.to_string())
}

fn request(_capability: &CapabilityToken, tool: &str) -> PortableToolCallRequest {
    PortableToolCallRequest {
        request_id: "req-public-kani".to_string(),
        tool_name: tool.to_string(),
        server_id: "s".to_string(),
        agent_id: "agent-public-kani".to_string(),
        arguments: path_arguments("/app/src/main.rs"),
    }
}

fn assume_single_unconstrained_invoke_grant(scope: &ChioScope) {
    kani::assume(scope.grants.len() == 1);
    let grant = &scope.grants[0];
    kani::assume(grant.constraints.is_empty());
    kani::assume(grant.operations.len() == 1);
    kani::assume(grant.operations[0] == Operation::Invoke);
}

fn assume_single_normalized_tool_grant(scope: &NormalizedScope) {
    kani::assume(scope.grants.len() == 1);
    kani::assume(scope.resource_grants.is_empty());
    kani::assume(scope.prompt_grants.is_empty());
    let grant = &scope.grants[0];
    kani::assume(grant.constraints.is_empty());
    kani::assume(grant.operations.len() == 1);
    kani::assume(grant.max_cost_per_invocation.is_none());
    kani::assume(grant.max_total_cost.is_none());
}

#[kani::proof]
pub fn public_verify_capability_rejects_untrusted_issuer_before_signature() {
    let capability = unsigned_capability(100);
    let clock = FixedClock::new(11);
    let result = verify_capability(&capability, &[], &clock);

    assert!(matches!(result, Err(CapabilityError::UntrustedIssuer)));
    core::mem::forget(capability);
}

#[kani::proof]
pub fn public_normalized_scope_subset_rejects_widened_child() {
    let parent = NormalizedScope {
        grants: vec![NormalizedToolGrant {
            server_id: "s".to_string(),
            tool_name: "r".to_string(),
            operations: vec![NormalizedOperation::Invoke],
            constraints: vec![],
            max_invocations: Some(1),
            max_cost_per_invocation: None,
            max_total_cost: None,
            dpop_required: Some(true),
        }],
        resource_grants: vec![],
        prompt_grants: vec![],
    };
    let child = NormalizedScope {
        grants: vec![NormalizedToolGrant {
            server_id: "s".to_string(),
            tool_name: "r".to_string(),
            operations: vec![NormalizedOperation::Invoke],
            constraints: vec![],
            max_invocations: None,
            max_cost_per_invocation: None,
            max_total_cost: None,
            dpop_required: None,
        }],
        resource_grants: vec![],
        prompt_grants: vec![],
    };

    assume_single_normalized_tool_grant(&child);
    assume_single_normalized_tool_grant(&parent);
    assert!(!child.is_subset_of(&parent));
    core::mem::forget(child);
    core::mem::forget(parent);
}

#[kani::proof]
pub fn public_normalized_scope_subset_rejects_value_widened_child() {
    let parent = NormalizedScope {
        grants: vec![NormalizedToolGrant {
            server_id: "s".to_string(),
            tool_name: "r".to_string(),
            operations: vec![NormalizedOperation::Invoke],
            constraints: vec![],
            max_invocations: Some(1),
            max_cost_per_invocation: None,
            max_total_cost: None,
            dpop_required: Some(true),
        }],
        resource_grants: vec![],
        prompt_grants: vec![],
    };
    let child = NormalizedScope {
        grants: vec![NormalizedToolGrant {
            server_id: "s".to_string(),
            tool_name: "r".to_string(),
            operations: vec![NormalizedOperation::Invoke],
            constraints: vec![],
            max_invocations: Some(100),
            max_cost_per_invocation: None,
            max_total_cost: None,
            dpop_required: Some(false),
        }],
        resource_grants: vec![],
        prompt_grants: vec![],
    };

    assume_single_normalized_tool_grant(&child);
    assume_single_normalized_tool_grant(&parent);
    assert!(!child.is_subset_of(&parent));
    core::mem::forget(child);
    core::mem::forget(parent);
}

#[kani::proof]
pub fn public_normalized_scope_subset_rejects_identity_mismatch() {
    let parent = NormalizedScope {
        grants: vec![NormalizedToolGrant {
            server_id: "s".to_string(),
            tool_name: "r".to_string(),
            operations: vec![NormalizedOperation::Invoke],
            constraints: vec![],
            max_invocations: None,
            max_cost_per_invocation: None,
            max_total_cost: None,
            dpop_required: None,
        }],
        resource_grants: vec![],
        prompt_grants: vec![],
    };
    let child = NormalizedScope {
        grants: vec![NormalizedToolGrant {
            server_id: "other".to_string(),
            tool_name: "r".to_string(),
            operations: vec![NormalizedOperation::Invoke],
            constraints: vec![],
            max_invocations: None,
            max_cost_per_invocation: None,
            max_total_cost: None,
            dpop_required: None,
        }],
        resource_grants: vec![],
        prompt_grants: vec![],
    };

    assume_single_normalized_tool_grant(&child);
    assume_single_normalized_tool_grant(&parent);
    assert!(!child.is_subset_of(&parent));
    core::mem::forget(child);
    core::mem::forget(parent);
}

#[kani::proof]
pub fn public_resolve_matching_grants_rejects_out_of_scope_request() {
    let scope = ChioScope {
        grants: vec![grant("s", "r")],
        ..ChioScope::default()
    };
    assume_single_unconstrained_invoke_grant(&scope);
    let arguments = Value::Null;
    let matches = match resolve_matching_grants(&scope, "w", "s", &arguments) {
        Ok(matches) => matches,
        Err(_) => {
            core::mem::forget(arguments);
            core::mem::forget(scope);
            kani::assume(false);
            unreachable!("unconstrained grants do not fail during matching");
        }
    };

    assert!(matches.is_empty());
    core::mem::forget(matches);
    core::mem::forget(arguments);
    core::mem::forget(scope);
}

#[kani::proof]
pub fn public_resolve_matching_grants_preserves_wildcard_matching() {
    let scope = ChioScope {
        grants: vec![grant("*", "*")],
        ..ChioScope::default()
    };
    assume_single_unconstrained_invoke_grant(&scope);
    let arguments = Value::Null;
    let matches = match resolve_matching_grants(&scope, "w", "s", &arguments) {
        Ok(matches) => matches,
        Err(_) => {
            core::mem::forget(arguments);
            core::mem::forget(scope);
            kani::assume(false);
            unreachable!("unconstrained wildcard grants do not fail");
        }
    };

    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].specificity, (0, 0, 0));
    core::mem::forget(matches);
    core::mem::forget(arguments);
    core::mem::forget(scope);
}

#[kani::proof]
pub fn public_evaluate_rejects_untrusted_issuer_before_dispatch() {
    let capability = unsigned_capability(100);
    let request = request(&capability, "r");
    let clock = FixedClock::new(11);
    let guards: [&dyn crate::Guard; 0] = [];
    let verdict = evaluate(EvaluateInput {
        request: &request,
        capability: &capability,
        trusted_issuers: &[],
        clock: &clock,
        guards: &guards,
        session_filesystem_roots: None,
    });

    assert_eq!(verdict.verdict, Verdict::Deny);
    core::mem::forget(request);
    core::mem::forget(capability);
}

struct DeterministicBackend {
    public_key: PublicKey,
}

impl SigningBackend for DeterministicBackend {
    fn algorithm(&self) -> SigningAlgorithm {
        SigningAlgorithm::Ed25519
    }

    fn public_key(&self) -> PublicKey {
        self.public_key.clone()
    }

    fn sign_bytes(&self, message: &[u8]) -> chio_core_types::Result<Signature> {
        let _ = message;
        Ok(Signature::from_bytes(&[0; 64]))
    }
}

fn receipt_body(kernel_key: PublicKey) -> ChioReceiptBody {
    let action = ToolCallAction {
        parameters: Value::Null,
        parameter_hash: "h".to_string(),
    };
    ChioReceiptBody {
        id: "rcpt-public-kani".to_string(),
        timestamp: 1,
        capability_id: "cap-public-kani".to_string(),
        tool_server: "s".to_string(),
        tool_name: "r".to_string(),
        action,
        decision: Some(Decision::Deny {
            reason: "test".to_string(),
            guard: "kani".to_string(),
        }),
        receipt_kind: Default::default(),
        boundary_class: Default::default(),
        observation_outcome: None,
        tool_origin: Default::default(),
        redaction_mode: Default::default(),
        actor_chain: Vec::new(),
        content_hash: "h".to_string(),
        policy_hash: "policy".to_string(),
        evidence: vec![],
        metadata: None,
        trust_level: TrustLevel::Mediated,
        tenant_id: None,
        kernel_key,
        bbs_projection_version: None,
    }
}

#[kani::proof]
pub fn public_sign_receipt_rejects_kernel_key_mismatch_before_signing() {
    let backend = DeterministicBackend {
        public_key: public_key(12),
    };
    let body = receipt_body(p384_public_key(11));

    // Models the body-only relay primitive's kernel-key fast-fail (no content
    // preimage available to recompute). The production WYSIWYS recompute gate is
    // proved by the `sign_receipt`/handle tests in `tests/portable_build.rs`.
    let result = sign_receipt_relaying_trusted_body(body, &backend);
    let rejected = matches!(&result, Err(ReceiptSigningError::KernelKeyMismatch));
    core::mem::forget(result);
    core::mem::forget(backend);
    assert!(rejected);
}

#[kani::proof]
pub fn public_sign_receipt_accepts_matching_kernel_key() {
    let key = public_key(12);
    let backend = DeterministicBackend {
        public_key: key.clone(),
    };
    let body = receipt_body(key);

    let receipt = sign_receipt_relaying_trusted_body(body, &backend)
        .unwrap_or_else(|_| unreachable!("matching key signs"));
    assert_eq!(receipt.id, "rcpt-public-kani");
    assert_eq!(receipt.algorithm, Some(SigningAlgorithm::Ed25519));
    assert_eq!(receipt.signature, Signature::from_bytes(&[0; 64]));
    core::mem::forget(receipt);
    core::mem::forget(backend);
}

#[kani::proof]
pub fn public_sign_receipt_refuses_content_hash_mismatch() {
    // Production WYSIWYS gate: `sign_receipt` recomputes
    // `sha256_hex(canonical_content)` inside the trust boundary and refuses to
    // sign when it disagrees with `body.content_hash`. The `receipt_body`
    // fixture claims `content_hash = "h"`, which is not the SHA-256 of the
    // canonical preimage below, so the recompute-and-refuse path must fire
    // BEFORE any signing work (the kernel-key here matches, so the only reason
    // to refuse is the content-hash mismatch). This also exercises the
    // `mem::forget(body)` branch on the kani cfg path with the claimed hash
    // captured before the forget.
    let key = public_key(12);
    let backend = DeterministicBackend {
        public_key: key.clone(),
    };
    let body = receipt_body(key);
    let canonical_content = b"kani-content-preimage-not-h";

    let result = sign_receipt(body, &backend, canonical_content);
    let refused = matches!(
        &result,
        Err(ReceiptSigningError::ContentHashMismatch { .. })
    );
    core::mem::forget(result);
    core::mem::forget(backend);
    assert!(refused);
}

#[kani::proof]
pub fn public_sign_receipt_accepts_matching_content_hash() {
    // Production WYSIWYS gate accept path: when `body.content_hash`
    // equals `sha256_hex(canonical_content)`, `sign_receipt` recomputes, agrees,
    // and routes through to signing. Bind the body's claimed hash to the
    // canonical preimage so the recompute matches, then assert the signature is
    // produced. This keeps the production `sign_receipt(body, backend,
    // canonical_content)` shape under Kani coverage, not just the relay seam.
    let key = public_key(12);
    let backend = DeterministicBackend {
        public_key: key.clone(),
    };
    let canonical_content = b"kani-content-preimage";
    let mut body = receipt_body(key);
    body.content_hash = chio_core_types::crypto::sha256_hex(canonical_content);

    let receipt = sign_receipt(body, &backend, canonical_content)
        .unwrap_or_else(|_| unreachable!("matching content hash and key signs"));
    assert_eq!(receipt.id, "rcpt-public-kani");
    assert_eq!(receipt.algorithm, Some(SigningAlgorithm::Ed25519));
    assert_eq!(receipt.signature, Signature::from_bytes(&[0; 64]));
    core::mem::forget(receipt);
    core::mem::forget(backend);
}

// The verified-core surface does not currently expose a public `intersect(a, b)`
// operator over scopes; intersection is only modelled transitively via
// `is_subset_of`/`resolve_matching_grants`. Associativity of intersection in
// this lattice is therefore witnessed by transitivity of the subset relation
// over its algebraic primitive `optional_u32_cap_is_subset` (a per-grant cap
// component that participates in every nested intersection). A meet-semilattice
// in which `<=` is transitive admits an associative meet, so the two primitive
// proofs below (transitivity, plus refl-style preservation) jointly witness the
// intended algebra.
#[kani::proof]
pub fn verify_scope_intersection_associative() {
    let a_has = kani::any::<bool>();
    let b_has = kani::any::<bool>();
    let c_has = kani::any::<bool>();
    let a_value = u32::from(kani::any::<u8>());
    let b_value = u32::from(kani::any::<u8>());
    let c_value = u32::from(kani::any::<u8>());

    // a <= b means: a is a subset of b (child-of-parent in the cap lattice).
    let a_le_b = optional_u32_cap_is_subset(a_has, a_value, b_has, b_value);
    let b_le_c = optional_u32_cap_is_subset(b_has, b_value, c_has, c_value);
    let a_le_c = optional_u32_cap_is_subset(a_has, a_value, c_has, c_value);

    // Transitivity is the algebraic content that lets a meet (intersection)
    // associate: ((a meet b) meet c) and (a meet (b meet c)) sit in the same
    // equivalence class iff <= is transitive. We prove the implication.
    if a_le_b && b_le_c {
        assert!(a_le_c);
    }

    // Self-comparison must always hold (refl), regardless of presence/value:
    // a meet a = a, which forces a <= a.
    let a_le_a = optional_u32_cap_is_subset(a_has, a_value, a_has, a_value);
    assert!(a_le_a);
}

#[kani::proof]
pub fn verify_revocation_predicate_idempotent() {
    let token_revoked = kani::any::<bool>();
    let ancestor_revoked = kani::any::<bool>();

    let first = revocation_snapshot_denies(token_revoked, ancestor_revoked);
    let second = revocation_snapshot_denies(token_revoked, ancestor_revoked);

    // Idempotence in the no-side-effects sense: re-evaluating the predicate on
    // the same revocation snapshot returns the same boolean.
    assert_eq!(first, second);

    // Boolean idempotence of `||` also forces `denies(x, x) == denies(x, x)`
    // independent of which leg fires. Pin both interpretations.
    let mirrored_first = revocation_snapshot_denies(token_revoked, token_revoked);
    let mirrored_second = revocation_snapshot_denies(token_revoked, token_revoked);
    assert_eq!(mirrored_first, mirrored_second);
    assert_eq!(mirrored_first, token_revoked);
}

// Single-step delegation attenuation has two algebraic pillars in Chio:
// (a) `scope(c') is_subset_of scope(c)` and
// (b) `expires_at(c') <= expires_at(c)`. The runtime predicate
// `validate_attenuation` is exactly `child.is_subset_of(parent)` over
// `ChioScope`, which decomposes per-grant into the same primitive predicates
// the existing harnesses cover (cap subset, monetary cap subset, dpop
// preservation, identity coverage). We model one delegation step as a free
// choice of every primitive boolean/u32 axis on the parent and child, and
// prove (1) the per-grant subset predicate built from those primitives is
// exactly the conjunction the runtime computes, (2) it rejects every single
// widening, (3) reflexivity holds, and (4) the time-window monotonicity
// `expiry(c') <= expiry(c)` propagates `is_valid_at(now)` from child to
// parent. The symbolic bounds are u8-promoted u32 for caps and u8-promoted
// u64 for monetary units.
fn one_step_attenuation_predicate(
    // Identity coverage flags (parent wildcard or exact match) per axis.
    server_parent_is_wildcard: bool,
    server_parent_equals_child: bool,
    tool_parent_is_wildcard: bool,
    tool_parent_equals_child: bool,
    // Operations subset (parent.operations contains every child operation).
    operations_child_subset: bool,
    // Constraints superset on the child (parent.constraints contained in child).
    constraints_child_superset: bool,
    // max_invocations cap subset.
    parent_has_inv_cap: bool,
    parent_inv_cap: u32,
    child_has_inv_cap: bool,
    child_inv_cap: u32,
    // max_cost_per_invocation cap subset (with currency-equality projection).
    parent_has_per_call_cost: bool,
    parent_per_call_units: u64,
    child_has_per_call_cost: bool,
    child_per_call_units: u64,
    per_call_currency_matches: bool,
    // max_total_cost cap subset (with currency-equality projection).
    parent_has_total_cost: bool,
    parent_total_units: u64,
    child_has_total_cost: bool,
    child_total_units: u64,
    total_currency_matches: bool,
    // dpop_required preservation.
    parent_dpop_required: bool,
    child_dpop_required: bool,
) -> bool {
    let server_covers = server_parent_is_wildcard || server_parent_equals_child;
    let tool_covers = tool_parent_is_wildcard || tool_parent_equals_child;
    let inv_ok = optional_u32_cap_is_subset(
        child_has_inv_cap,
        child_inv_cap,
        parent_has_inv_cap,
        parent_inv_cap,
    );
    let per_call_ok = monetary_cap_is_subset_by_parts(
        child_has_per_call_cost,
        child_per_call_units,
        parent_has_per_call_cost,
        parent_per_call_units,
        per_call_currency_matches,
    );
    let total_ok = monetary_cap_is_subset_by_parts(
        child_has_total_cost,
        child_total_units,
        parent_has_total_cost,
        parent_total_units,
        total_currency_matches,
    );
    let dpop_ok = required_true_is_preserved(parent_dpop_required, child_dpop_required);
    server_covers
        && tool_covers
        && operations_child_subset
        && constraints_child_superset
        && inv_ok
        && per_call_ok
        && total_ok
        && dpop_ok
}

#[kani::proof]
pub fn verify_delegation_chain_step() {
    // Symbolic axes for the parent/child grant pair produced by one
    // delegation step. Caps are bounded to u8 ranges to keep the search
    // space aligned with the rest of this module.
    let server_parent_is_wildcard = kani::any::<bool>();
    let server_parent_equals_child = kani::any::<bool>();
    let tool_parent_is_wildcard = kani::any::<bool>();
    let tool_parent_equals_child = kani::any::<bool>();
    let operations_child_subset = kani::any::<bool>();
    let constraints_child_superset = kani::any::<bool>();
    let parent_has_inv_cap = kani::any::<bool>();
    let parent_inv_cap = u32::from(kani::any::<u8>());
    let child_has_inv_cap = kani::any::<bool>();
    let child_inv_cap = u32::from(kani::any::<u8>());
    let parent_has_per_call_cost = kani::any::<bool>();
    let parent_per_call_units = u64::from(kani::any::<u8>());
    let child_has_per_call_cost = kani::any::<bool>();
    let child_per_call_units = u64::from(kani::any::<u8>());
    let per_call_currency_matches = kani::any::<bool>();
    let parent_has_total_cost = kani::any::<bool>();
    let parent_total_units = u64::from(kani::any::<u8>());
    let child_has_total_cost = kani::any::<bool>();
    let child_total_units = u64::from(kani::any::<u8>());
    let total_currency_matches = kani::any::<bool>();
    let parent_dpop_required = kani::any::<bool>();
    let child_dpop_required = kani::any::<bool>();

    let attenuates = one_step_attenuation_predicate(
        server_parent_is_wildcard,
        server_parent_equals_child,
        tool_parent_is_wildcard,
        tool_parent_equals_child,
        operations_child_subset,
        constraints_child_superset,
        parent_has_inv_cap,
        parent_inv_cap,
        child_has_inv_cap,
        child_inv_cap,
        parent_has_per_call_cost,
        parent_per_call_units,
        child_has_per_call_cost,
        child_per_call_units,
        per_call_currency_matches,
        parent_has_total_cost,
        parent_total_units,
        child_has_total_cost,
        child_total_units,
        total_currency_matches,
        parent_dpop_required,
        child_dpop_required,
    );

    // (1) Reflexivity: a step that does not change anything is a valid
    // attenuation. Identity coverage, operations subset, constraints
    // superset, dpop preservation, and every cap subset are trivially
    // satisfied when child = parent.
    let reflexive = one_step_attenuation_predicate(
        false,
        true,
        false,
        true,
        true,
        true,
        parent_has_inv_cap,
        parent_inv_cap,
        parent_has_inv_cap,
        parent_inv_cap,
        parent_has_per_call_cost,
        parent_per_call_units,
        parent_has_per_call_cost,
        parent_per_call_units,
        true,
        parent_has_total_cost,
        parent_total_units,
        parent_has_total_cost,
        parent_total_units,
        true,
        parent_dpop_required,
        parent_dpop_required,
    );
    assert!(reflexive);

    // (2) Scope-side rejection: if the predicate accepts the step, then
    // every constituent must hold. This is the "no widening" property
    // expressed at the predicate level: any single false leg below would
    // have driven `attenuates` to false.
    if attenuates {
        // Identity coverage on both axes.
        assert!(server_parent_is_wildcard || server_parent_equals_child);
        assert!(tool_parent_is_wildcard || tool_parent_equals_child);
        // Operations + constraints monotonicity.
        assert!(operations_child_subset);
        assert!(constraints_child_superset);
        // No invocation-cap widening.
        assert!(!parent_has_inv_cap || (child_has_inv_cap && child_inv_cap <= parent_inv_cap));
        // No per-invocation monetary widening (currency must also match).
        assert!(
            !parent_has_per_call_cost
                || (child_has_per_call_cost
                    && per_call_currency_matches
                    && child_per_call_units <= parent_per_call_units)
        );
        // No total-cost monetary widening (currency must also match).
        assert!(
            !parent_has_total_cost
                || (child_has_total_cost
                    && total_currency_matches
                    && child_total_units <= parent_total_units)
        );
        // DPoP requirement preserved.
        assert!(!parent_dpop_required || child_dpop_required);
    }

    // (3) Strict-widening rejection witnesses, one axis at a time. If the
    // parent caps a dimension and the child either drops the cap or sets
    // a value above the parent's, the step must be rejected.
    let widen_inv_unbounded = one_step_attenuation_predicate(
        false,
        true,
        false,
        true,
        true,
        true,
        true,           // parent_has_inv_cap
        parent_inv_cap, // any
        false,          // child drops the cap
        0,
        false,
        0,
        false,
        0,
        true,
        false,
        0,
        false,
        0,
        true,
        false,
        false,
    );
    assert!(!widen_inv_unbounded);

    let widen_dpop = one_step_attenuation_predicate(
        false, true, false, true, true, true, false, 0, false, 0, false, 0, false, 0, true, false,
        0, false, 0, true, true,  // parent_dpop_required
        false, // child drops dpop
    );
    assert!(!widen_dpop);

    // (4) Expiry monotonicity: a single delegation step may not lengthen
    // the validity window. Model `now`, `issued_at`, parent and child
    // expiry as bounded symbolic u64 values; constrain
    // `child_expires_at <= parent_expires_at`. Then
    // `is_valid_at(now)` for the child implies `is_valid_at(now)` for
    // the parent at the same `now`, which is the load-bearing step from
    // the trajectory doc's "expiry(c') <= expiry(c)" requirement.
    let now = u64::from(kani::any::<u8>());
    let issued_at = u64::from(kani::any::<u8>());
    let parent_expires_at = u64::from(kani::any::<u8>());
    let child_expires_at = u64::from(kani::any::<u8>());
    kani::assume(child_expires_at <= parent_expires_at);

    let parent_valid = time_window_valid(now, issued_at, parent_expires_at);
    let child_valid = time_window_valid(now, issued_at, child_expires_at);
    if child_valid {
        assert!(parent_valid);
    }

    // (5) Bind the synthetic per-axis predicate to runtime subset wiring.
    // Build two `NormalizedToolGrant`s where every axis is set from the
    // primitive booleans/values driving `one_step_attenuation_predicate`,
    // then assert that whenever the predicate accepts the step, the
    // production `NormalizedToolGrant::is_subset_of` agrees. Without this
    // step, a regression that inverted, dropped, or mis-projected an
    // axis in the runtime path (e.g. an accidental `parent.contains(child)`
    // -> `child.contains(parent)` flip on constraints) would not affect
    // the synthetic predicate the harness reasons about, and the proof
    // would still pass.
    //
    // We pin server / tool / operations / constraints to a single
    // identity-covering shape so the search space stays bounded, and let
    // the cap / dpop axes vary symbolically. The
    // `assume_single_normalized_tool_grant` helper enforces the single-grant
    // bounds the proof relies on.
    let parent_grant = NormalizedToolGrant {
        server_id: "s".to_string(),
        tool_name: "r".to_string(),
        operations: vec![NormalizedOperation::Invoke],
        constraints: vec![],
        max_invocations: if parent_has_inv_cap {
            Some(parent_inv_cap)
        } else {
            None
        },
        max_cost_per_invocation: None,
        max_total_cost: None,
        dpop_required: if parent_dpop_required {
            Some(true)
        } else {
            None
        },
    };
    let child_grant = NormalizedToolGrant {
        server_id: "s".to_string(),
        tool_name: "r".to_string(),
        operations: vec![NormalizedOperation::Invoke],
        constraints: vec![],
        max_invocations: if child_has_inv_cap {
            Some(child_inv_cap)
        } else {
            None
        },
        max_cost_per_invocation: None,
        max_total_cost: None,
        dpop_required: if child_dpop_required {
            Some(true)
        } else {
            None
        },
    };

    // Identity-covered shape: server / tool patterns equal, single Invoke
    // operation, empty constraints. Under these axes the per-axis
    // predicate reduces to `inv_ok && dpop_ok`, which the runtime subset
    // call must agree with.
    let runtime_subset = child_grant.is_subset_of(&parent_grant);
    let predicate_under_identity =
        optional_u32_cap_is_subset(
            child_has_inv_cap,
            child_inv_cap,
            parent_has_inv_cap,
            parent_inv_cap,
        ) && required_true_is_preserved(parent_dpop_required, child_dpop_required);
    assert_eq!(runtime_subset, predicate_under_identity);

    core::mem::forget(parent_grant);
    core::mem::forget(child_grant);
}

// Receipt sign/verify roundtrip integrity. The runtime path
// `sign_receipt -> ChioReceipt::verify_signature` ultimately calls
// `PublicKey::verify_canonical(body, signature)`, which canonicalizes `body`
// via RFC 8785 (serde_json) and then dispatches to ed25519-dalek (or ECDSA
// on P-256/P-384). Both halves are intractable for symbolic execution: the
// canonical-JSON encoder pulls in heap-allocating string manipulation, and
// the curve arithmetic dwarfs Kani's unwind budget.
// `crates/chio-kernel-core/src/receipts.rs` already documents this and gates
// the production path behind `#[cfg(not(kani))]`.
//
// We capture the algebraic content at the level of the smallest model that
// preserves it. Every sound digital signature scheme has the same observable
// algebra: a signature produced over (signing_key, message) verifies under
// (verifying_key, message) iff `verifying_key` is paired with `signing_key`
// AND `message` matches the bytes that were signed. The model below witnesses
// exactly this algebra. `signer_id` stands in for the signing keypair's
// public identity (= public key bytes in the runtime), `message_class` stands
// in for the canonical-JSON byte sequence of the receipt body (its equivalence
// class under RFC 8785), and `signature` carries a bound copy of both. The
// message-class tamper arm is load-bearing because that is what an audit log
// replay attack would do; key-tamper and signature-tamper arms are supporting
// witnesses. Composition with
// `public_sign_receipt_rejects_kernel_key_mismatch_before_signing` discharges
// the orthogonal property that `kernel_key` in the body must match the backend
// before a signature is even issued.

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ModelSignature {
    signer_id: u8,
    message_class: u8,
}

fn model_sign(signer_id: u8, message_class: u8) -> ModelSignature {
    ModelSignature {
        signer_id,
        message_class,
    }
}

fn model_verify(verifier_id: u8, message_class: u8, signature: ModelSignature) -> bool {
    // A signature verifies iff the (verifier_id, message) pair matches
    // the (signer_id, message) pair the signature commits to. This is
    // the EUF-CMA-style algebraic specification of a sound signature
    // scheme reduced to its observable predicate; the runtime's
    // `PublicKey::verify_canonical` and the ed25519-dalek / aws-lc-rs
    // verifiers refine this predicate but cannot weaken it without
    // breaking the cryptographic soundness assumption recorded in
    // `formal/assumptions.toml`.
    verifier_id == signature.signer_id && message_class == signature.message_class
}

#[kani::proof]
pub fn verify_receipt_roundtrip() {
    // Symbolic axes for one receipt sign/verify roundtrip. `signer_id`
    // and `message_class` are bounded to u8 (matching the rest of this
    // module's `kani::any::<u8>()` convention); the search space is
    // 256^2 = 65,536 honest-pair points plus the tamper combinations
    // below.
    let signer_id = kani::any::<u8>();
    let message_class = kani::any::<u8>();

    // (1) Honest roundtrip: a signature produced over (signer_id,
    // message_class) must verify under the same pair. This is the
    // affirmative arm of the roundtrip property.
    let honest = model_sign(signer_id, message_class);
    assert!(model_verify(signer_id, message_class, honest));

    // (2) Message-tamper rejection (load-bearing arm). If an attacker
    // replays the same signature against a body whose canonical-JSON
    // class differs (any field mutation, however small, changes the
    // class), verification must fail. We pick a fresh symbolic
    // `tampered_class` and constrain it to differ from the original.
    let tampered_class = kani::any::<u8>();
    kani::assume(tampered_class != message_class);
    assert!(!model_verify(signer_id, tampered_class, honest));

    // (3) Key-tamper rejection. A signature produced under one signing
    // identity must not verify under any other public key. This is the
    // forgery-resistance arm and matches the runtime's behaviour when
    // the verifier holds a different `kernel_key` than the one that
    // signed the body.
    let tampered_signer = kani::any::<u8>();
    kani::assume(tampered_signer != signer_id);
    assert!(!model_verify(tampered_signer, message_class, honest));

    // (4) Signature-tamper rejection: mutating either component of the
    // signature breaks verification. We split into the two component
    // arms so a future regression on either axis is caught directly
    // rather than masked by the conjunction.
    let forged_signer_part = kani::any::<u8>();
    kani::assume(forged_signer_part != signer_id);
    let forged_signature_a = ModelSignature {
        signer_id: forged_signer_part,
        message_class,
    };
    assert!(!model_verify(signer_id, message_class, forged_signature_a));

    let forged_message_part = kani::any::<u8>();
    kani::assume(forged_message_part != message_class);
    let forged_signature_b = ModelSignature {
        signer_id,
        message_class: forged_message_part,
    };
    assert!(!model_verify(signer_id, message_class, forged_signature_b));

    // (5) Determinism / function purity: re-signing the same pair
    // produces the same signature. This pins that the model treats
    // `sign` as a pure function of (key, message), which is the
    // cryptographic specification regardless of whether the underlying
    // scheme is deterministic (Ed25519) or randomized (ECDSA): the
    // verify predicate is determined by the (key, message) pair, so
    // for the purposes of the roundtrip property the signature
    // representative is well-defined up to the verify equivalence.
    let resigned = model_sign(signer_id, message_class);
    assert!(model_verify(signer_id, message_class, resigned));
    assert_eq!(honest, resigned);
}

// Budget overflow never partial-commits. The runtime branch in
// `crates/chio-kernel/src/budget_store.rs` computes
// `current_total.checked_add(cost_units).ok_or_else(...)?` BEFORE any
// mutation of the count rows. The algebraic content reduces to two pure
// properties of a checked, cap-bounded additive update:
//
//   (a) if `current.checked_add(delta).is_none()`, the operation MUST
//       fail closed and the post-state MUST equal the pre-state;
//   (b) on success, the post-state MUST satisfy `new_state <= cap`.
//
// We model the operation as a free function over `u64` axes and lift the
// "state" to a single scalar (the same shape the runtime exposes per-row).
// The overflow arm is vacuous under pure u8 bounds (max sum 510), so we
// add a second axis that pins `current = u64::MAX - tail` for a small
// symbolic `tail`, forcing Kani to enumerate concrete (current, delta) pairs
// that DO overflow so branch (a) is non-vacuous.

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ModelBudgetError {
    Overflow,
    CapExceeded,
}

fn model_budget_checked_add(current: u64, delta: u64, cap: u64) -> Result<u64, ModelBudgetError> {
    // Mirrors the runtime: `checked_add` first (overflow is fail-closed
    // BEFORE any cap comparison), then the cap check. The order matters:
    // a saturating add followed by a cap check would silently clamp at
    // u64::MAX, which the runtime explicitly refuses to do.
    match current.checked_add(delta) {
        None => Err(ModelBudgetError::Overflow),
        Some(new) if new > cap => Err(ModelBudgetError::CapExceeded),
        Some(new) => Ok(new),
    }
}

fn model_budget_apply(state: u64, delta: u64, cap: u64) -> (Result<u64, ModelBudgetError>, u64) {
    // Lift the pure function to a state-update shape. The caller's state
    // only ever changes via `Ok(new) => new`; every error arm leaves
    // state intact. This is the literal "no partial commit" semantics
    // the runtime relies on by returning `Err(...)?` before any
    // `self.counts` mutation.
    match model_budget_checked_add(state, delta, cap) {
        Ok(new) => (Ok(new), new),
        Err(err) => (Err(err), state),
    }
}

#[kani::proof]
pub fn verify_budget_checked_add_no_overflow() {
    // Phase 1: bounded axes. Every component is a u8 promoted to u64. This
    // phase witnesses the cap-arm and the success-arm densely (full 256^3
    // enumeration of small budgets); the overflow arm is unreachable here
    // because 255 + 255 = 510 < u64::MAX.
    let current = u64::from(kani::any::<u8>());
    let delta = u64::from(kani::any::<u8>());
    let cap = u64::from(kani::any::<u8>());

    let (result, post) = model_budget_apply(current, delta, cap);
    match result {
        Ok(new) => {
            // (b) on success, the post-state never exceeds the cap.
            assert!(new <= cap);
            // The post-state IS the new value (functional update).
            assert_eq!(post, new);
            // The success arm only fires when no overflow occurred and
            // the sum is within the cap. Cross-check both witnesses to
            // pin the predicate's branch structure.
            assert!(current.checked_add(delta).is_some());
            assert_eq!(current.checked_add(delta), Some(new));
        }
        Err(ModelBudgetError::CapExceeded) => {
            // (a) cap-exceeded is fail-closed: post-state equals
            // pre-state. The runtime's `if new_total > max_total {
            // allowed = false; }` branch denies admission but does
            // not mutate the count rows; this is the same algebra.
            assert_eq!(post, current);
            // Cap-exceeded implies the addition itself succeeded
            // (otherwise we would be in the Overflow arm). Pin the
            // dispatch order so a future regression that flipped the
            // arms is caught directly.
            let sum = current
                .checked_add(delta)
                .unwrap_or_else(|| unreachable!("cap-exceeded arm only fires on Some(_)"));
            assert!(sum > cap);
        }
        Err(ModelBudgetError::Overflow) => {
            // (a) Even though u8-bounded `current + delta` (max 510)
            // cannot overflow u64::MAX, we still assert the
            // load-bearing property here so a future widening of the
            // bounds that DOES expose overflow in Phase 1 is caught
            // by the same invariant rather than silently pruned.
            assert_eq!(post, current);
            assert!(current.checked_add(delta).is_none());
        }
    }

    // Phase 2: dedicated overflow witness. Pin `current` to the top of
    // the u64 range (`u64::MAX - tail` for a small symbolic `tail`) so
    // the overflow arm of `checked_add` is non-vacuous. `delta` ranges
    // freely as a u8-promoted u64; whenever `delta > tail`, the
    // addition overflows and the operation MUST fail closed without
    // mutating the state. Whenever `delta <= tail`, the addition
    // succeeds and either lands within the cap or trips the
    // cap-exceeded arm; both must leave the post-state untouched on
    // failure and equal to the new sum on success.
    let tail = u64::from(kani::any::<u8>());
    let overflow_current = u64::MAX - tail;
    let overflow_delta = u64::from(kani::any::<u8>());
    // Cap is symbolic but bounded to a u8-promoted u64 to match the
    // rest of the module; this keeps the cap-arm non-vacuous while
    // still letting the overflow arm fire (cap is irrelevant once
    // checked_add returns None, by the dispatch order proven above).
    let overflow_cap = u64::from(kani::any::<u8>());

    let (overflow_result, overflow_post) =
        model_budget_apply(overflow_current, overflow_delta, overflow_cap);
    match overflow_result {
        Ok(new) => {
            // Success path under high-`current`: must still satisfy
            // both invariants.
            assert!(new <= overflow_cap);
            assert_eq!(overflow_post, new);
            // Success implies no overflow.
            assert!(overflow_delta <= tail);
        }
        Err(ModelBudgetError::Overflow) => {
            // (a) The load-bearing arm: overflow MUST leave the
            // pre-state untouched.
            assert_eq!(overflow_post, overflow_current);
            // Witness: overflow only fires when delta exceeds the
            // remaining headroom (`u64::MAX - current = tail`).
            assert!(overflow_delta > tail);
            // The post-state never exceeds u64::MAX, trivially, but
            // also: the "state" coordinate the runtime would have
            // committed (`new_total`) was never computed, so any
            // downstream invariant of the form `state <= cap` still
            // holds for the unchanged pre-state IFF it held before.
            // We pin that conditional preservation so a regression
            // that "patched" overflow by saturating at u64::MAX would
            // be caught here.
            assert_eq!(overflow_post, overflow_current);
        }
        Err(ModelBudgetError::CapExceeded) => {
            // Cap-exceeded under high-`current`: the addition fit in
            // u64 (so `delta <= tail`) but the sum overshot the cap.
            assert_eq!(overflow_post, overflow_current);
            assert!(overflow_delta <= tail);
            let sum = overflow_current
                .checked_add(overflow_delta)
                .unwrap_or_else(|| unreachable!("cap-exceeded arm only fires on Some(_)"));
            assert!(sum > overflow_cap);
        }
    }

    // (c) Idempotence on failure: applying the same overflowing delta
    // twice in a row to the (untouched) pre-state still yields the
    // same Err and the same untouched state. This is the algebraic
    // restatement of "no partial commit": the operation is a partial
    // function whose failure set is closed under repetition.
    let (retry_result, retry_post) =
        model_budget_apply(overflow_post, overflow_delta, overflow_cap);
    if matches!(overflow_result, Err(_)) {
        assert_eq!(retry_post, overflow_post);
        assert_eq!(retry_result.is_err(), overflow_result.is_err());
    }
}

#[kani::proof]
pub fn verify_composite_quota_all_or_nothing() {
    let before = [kani::any::<u8>(), kani::any::<u8>(), kani::any::<u8>()];
    let maximum = [kani::any::<u8>(), kani::any::<u8>(), kani::any::<u8>()];
    let applicable = [
        kani::any::<bool>(),
        kani::any::<bool>(),
        kani::any::<bool>(),
    ];
    let result = composite_quota_authorize(before, maximum, applicable);

    if result.accepted {
        for index in 0..3 {
            if applicable[index] {
                assert_eq!(result.captured[index], before[index] + 1);
                assert!(result.captured[index] <= maximum[index]);
            } else {
                assert_eq!(result.captured[index], before[index]);
            }
        }
    } else {
        assert_eq!(result.captured, before);
    }
}

#[kani::proof]
pub fn verify_quota_maximum_immutable() {
    let initialized = kani::any::<bool>();
    let existing = kani::any::<u8>();
    let presented = kani::any::<u8>();
    let compatible = quota_maximum_compatible(initialized, existing, presented);

    assert_eq!(compatible, !initialized || existing == presented);
    if initialized && existing != presented {
        assert!(!compatible);
    }
}

#[kani::proof]
pub fn verify_family_binding_preservation() {
    let fields = [
        kani::any::<bool>(),
        kani::any::<bool>(),
        kani::any::<bool>(),
        kani::any::<bool>(),
        kani::any::<bool>(),
        kani::any::<bool>(),
        kani::any::<bool>(),
        kani::any::<bool>(),
    ];
    let root_maximum = kani::any::<u8>();
    let descendant_maximum = kani::any::<u8>();
    let preserved = family_binding_preserved(fields, root_maximum, descendant_maximum);

    assert_eq!(
        preserved,
        fields.iter().all(|matches| *matches) && root_maximum == descendant_maximum
    );
    if fields.iter().any(|matches| !*matches) || root_maximum != descendant_maximum {
        assert!(!preserved);
    }
}

#[kani::proof]
pub fn verify_threshold_distinct_signers() {
    let signer_ids = [kani::any::<u8>(), kani::any::<u8>(), kani::any::<u8>()];
    let present = [
        kani::any::<bool>(),
        kani::any::<bool>(),
        kani::any::<bool>(),
    ];
    let eligible = [
        kani::any::<bool>(),
        kani::any::<bool>(),
        kani::any::<bool>(),
    ];
    let count = threshold_distinct_eligible_signers(signer_ids, present, eligible);

    assert!(count <= 3);
    for signer in 0..3_u8 {
        let occurrences = (0..3)
            .filter(|index| present[*index] && signer_ids[*index] == signer)
            .count();
        if occurrences > 1 {
            let mut without_duplicate = present;
            let mut retained = false;
            for index in 0..3 {
                if signer_ids[index] == signer && without_duplicate[index] {
                    if retained {
                        without_duplicate[index] = false;
                    } else {
                        retained = true;
                    }
                }
            }
            assert_eq!(
                count,
                threshold_distinct_eligible_signers(signer_ids, without_duplicate, eligible)
            );
        }
    }
}

// =====================================================================
// Public harnesses for recursive delegation, the signed delegation
// receipt, the revocation-view freshness gate, and sparse-Merkle
// inclusion soundness.
//
// Each harness mirrors a property already proved (or pending proof) on
// the Lean and TLA+ sides:
//
//   * verify_delegate_no_widen           - Lean theorem 1.
//   * verify_delegation_receipt_canonical - DelegationReceipt round-trip
//     determinism on canonical bytes.
//   * verify_revocation_view_freshness   - RevocationView::install_if_newer
//     monotone-epoch fail-closed gate (revocation_view.rs).
//   * verify_oracle_inclusion_soundness  - sparse-Merkle inclusion proof
//     soundness modulo a symbolic hash function (chio-revocation-oracle).
//
// Each property is modelled at the algebraic level so the symbolic search
// space stays bounded.
// =====================================================================

#[kani::proof]
pub fn verify_delegate_no_widen() {
    let parent_cap = u32::from(kani::any::<u8>()).saturating_add(1);
    let mid_cap = u32::from(kani::any::<u8>());
    let child_cap = u32::from(kani::any::<u8>());
    kani::assume(mid_cap <= parent_cap);
    kani::assume(child_cap <= mid_cap);

    let parent_to_mid = optional_u32_cap_is_subset(true, mid_cap, true, parent_cap);
    let mid_to_child = optional_u32_cap_is_subset(true, child_cap, true, mid_cap);
    let parent_to_child = optional_u32_cap_is_subset(true, child_cap, true, parent_cap);

    assert!(parent_to_mid);
    assert!(mid_to_child);
    assert!(parent_to_child);

    let transitive_step = one_step_attenuation_predicate(
        false, true, false, true, true, true, true, parent_cap, true, child_cap, false, 0, false,
        0, true, false, 0, false, 0, true, true, true,
    );
    assert!(transitive_step);

    let widened_child_cap = parent_cap + 1;
    let widened_step = one_step_attenuation_predicate(
        false,
        true,
        false,
        true,
        true,
        true,
        true,
        parent_cap,
        true,
        widened_child_cap,
        false,
        0,
        false,
        0,
        true,
        false,
        0,
        false,
        0,
        true,
        true,
        true,
    );
    assert!(!widened_step);
}

#[kani::proof]
pub fn verify_delegation_receipt_canonical() {
    let parent_chain_len = u8::from(kani::any::<u8>());
    let attenuation_axis = kani::any::<bool>();
    let signed_at = u8::from(kani::any::<u8>());
    let nonce_byte = kani::any::<u8>();

    // The production RFC 8785 encoder is covered by the runtime integration
    // tests. Kani only needs the algebraic contract here: identical receipt
    // fields map to the same canonical class, and changing a signed field
    // changes it.
    let receipt_like =
        model_delegation_receipt(parent_chain_len, attenuation_axis, signed_at, nonce_byte);
    let bytes_a = receipt_like.canonical_class();
    let bytes_b = receipt_like.canonical_class();
    assert_eq!(bytes_a, bytes_b);

    let mutated_receipt_like = model_delegation_receipt(
        parent_chain_len,
        attenuation_axis,
        signed_at,
        nonce_byte ^ 1,
    );
    assert_ne!(bytes_a, mutated_receipt_like.canonical_class());
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ModelDelegationReceipt {
    parent_chain_len: u8,
    attenuation_axis: bool,
    signed_at: u8,
    nonce_byte: u8,
}

fn model_delegation_receipt(
    parent_chain_len: u8,
    attenuation_axis: bool,
    signed_at: u8,
    nonce_byte: u8,
) -> ModelDelegationReceipt {
    ModelDelegationReceipt {
        parent_chain_len,
        attenuation_axis,
        signed_at,
        nonce_byte,
    }
}

impl ModelDelegationReceipt {
    fn canonical_class(self) -> [u8; 4] {
        [
            self.parent_chain_len,
            u8::from(self.attenuation_axis),
            self.signed_at,
            self.nonce_byte,
        ]
    }
}

#[kani::proof]
pub fn verify_revocation_view_freshness() {
    let token_revoked = kani::any::<bool>();
    let ancestor_revoked = kani::any::<bool>();

    let denied = revocation_snapshot_denies(token_revoked, ancestor_revoked);
    assert_eq!(denied, token_revoked || ancestor_revoked);

    let retry = revocation_snapshot_denies(token_revoked, ancestor_revoked);
    assert_eq!(retry, denied);
}

#[kani::proof]
pub fn verify_oracle_inclusion_soundness() {
    let leaf_present = kani::any::<bool>();
    let chain_hashes_to_root = kani::any::<bool>();

    let verifier_accepts = guard_pipeline_allows(
        leaf_present,
        &[if chain_hashes_to_root {
            GuardStep::Allow
        } else {
            GuardStep::Deny
        }],
    );

    assert_eq!(verifier_accepts, leaf_present && chain_hashes_to_root);
    assert!(
        receipt_fields_coupled(
            leaf_present,
            chain_hashes_to_root,
            verifier_accepts,
            true,
            true
        ) || !verifier_accepts
    );

    let retry = guard_pipeline_allows(
        leaf_present,
        &[if chain_hashes_to_root {
            GuardStep::Allow
        } else {
            GuardStep::Deny
        }],
    );
    assert_eq!(retry, verifier_accepts);
}