dyolo-kya 2.0.0

Know Your Agent (KYA): cryptographic chain-of-custody for recursive AI delegation with provable scope narrowing, namespace isolation, and enterprise-grade storage health
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
use blake3::Hasher;
use ed25519_dalek::VerifyingKey;

use crate::audit::{AuditEvent, AuditOutcome, AuditSink, NoopAuditSink};
use crate::cert::DelegationCert;
use crate::crypto::DOMAIN_CHAIN_FP;
use crate::error::KyaError;
use crate::intent::{IntentHash, MerkleProof};
use crate::policy::PolicySet;
use crate::registry::{NonceStore, RevocationStore};
#[cfg(feature = "tracing")]
use tracing::Instrument;

// ── Clock ─────────────────────────────────────────────────────────────────────

pub trait Clock {
    fn unix_now(&self) -> u64;
}

pub struct SystemClock;

impl Clock for SystemClock {
    fn unix_now(&self) -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system clock is before the Unix epoch")
            .as_secs()
    }
}

// ── VerificationReceipt ───────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VerificationReceipt {
    pub chain_depth: usize,
    pub verified_scope_root: IntentHash,
    pub intent: IntentHash,
    pub verified_at_unix: u64,
    pub chain_fingerprint: [u8; 32],
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub namespace: Option<String>,
}

impl VerificationReceipt {
    pub fn fingerprint_hex(&self) -> String {
        hex::encode(self.chain_fingerprint)
    }

    #[cfg(feature = "wire")]
    pub(crate) fn canonical_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(8 + 32 + 32 + 8 + 32 + 64);
        out.extend_from_slice(&(self.chain_depth as u64).to_be_bytes());
        out.extend_from_slice(&self.verified_scope_root);
        out.extend_from_slice(&self.intent);
        out.extend_from_slice(&self.verified_at_unix.to_be_bytes());
        out.extend_from_slice(&self.chain_fingerprint);
        if let Some(ns) = &self.namespace {
            out.extend_from_slice(&(ns.len() as u64).to_be_bytes());
            out.extend_from_slice(ns.as_bytes());
        } else {
            out.extend_from_slice(&0u64.to_be_bytes());
        }
        out
    }
}

// ── BatchAuthorizeResult ──────────────────────────────────────────────────────

#[derive(Debug)]
pub struct BatchAuthorizeResult {
    pub receipts: Vec<Option<VerificationReceipt>>,
    pub errors: Vec<Option<KyaError>>,
    pub all_authorized: bool,
}

impl BatchAuthorizeResult {
    pub fn authorized_count(&self) -> usize {
        self.receipts.iter().filter(|r| r.is_some()).count()
    }
}

// ── AuthorizedAction ──────────────────────────────────────────────────────────

#[must_use]
#[non_exhaustive]
pub struct AuthorizedAction {
    pub receipt: VerificationReceipt,
}

impl AuthorizedAction {
    pub(crate) fn new(receipt: VerificationReceipt) -> Self {
        Self { receipt }
    }

    pub fn receipt(&self) -> &VerificationReceipt {
        &self.receipt
    }
}

impl std::fmt::Debug for AuthorizedAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthorizedAction")
            .field("receipt", &self.receipt)
            .finish()
    }
}

// ── Internal validation result ────────────────────────────────────────────────

struct ChainValidationResult {
    depth: usize,
    verified_scope_root: IntentHash,
    verified_at_unix: u64,
    seen_nonces: Vec<[u8; 16]>,
    cert_fingerprints: Vec<[u8; 32]>,
    chain_fingerprint: [u8; 32],
}

// ── Namespace scope derivation ────────────────────────────────────────────────

fn namespace_scope(namespace: &str, scope: &IntentHash) -> IntentHash {
    let mut h = blake3::Hasher::new_derive_key("dyolo::kya::namespace::scope::v2");
    h.update(&(namespace.len() as u64).to_le_bytes());
    h.update(namespace.as_bytes());
    h.update(scope);
    h.finalize().into()
}

// ── DyoloChain ────────────────────────────────────────────────────────────────

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DyoloChain {
    pub principal_pk: VerifyingKey,
    pub principal_scope: IntentHash,
    certs: Vec<DelegationCert>,
    pub drift_tolerance_secs: u64,
    pub namespace: Option<String>,
}

impl DyoloChain {
    pub fn new(principal_pk: VerifyingKey, principal_scope: IntentHash) -> Self {
        Self {
            principal_pk,
            principal_scope,
            certs: Vec::new(),
            drift_tolerance_secs: 15,
            namespace: None,
        }
    }

    /// Attach a namespace to this chain.
    ///
    /// The effective scope root becomes a namespace-derived hash of the original
    /// `principal_scope`, cryptographically binding the chain to one tenant namespace.
    /// A cert issued for namespace "tenant-a" cannot authorize under namespace "tenant-b".
    ///
    /// # Multi-tenancy
    ///
    /// Use this when building a chain on behalf of a specific tenant. The human
    /// principal must compute the namespaced scope before issuing the first cert:
    ///
    /// ```rust,ignore
    /// let chain = DyoloChain::new(pk, original_scope)
    ///     .with_namespace("acme-corp");
    /// let namespaced_scope = chain.principal_scope;
    /// let cert = CertBuilder::new(agent_pk, namespaced_scope, now, expiry).sign(&human);
    /// chain.push(cert);
    /// ```
    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
        let ns = namespace.into();
        self.principal_scope = namespace_scope(&ns, &self.principal_scope);
        self.namespace = Some(ns);
        self
    }

    pub fn with_drift_tolerance(mut self, secs: u64) -> Self {
        self.drift_tolerance_secs = secs;
        self
    }

    pub fn push(&mut self, cert: DelegationCert) -> &mut Self {
        self.certs.push(cert);
        self
    }

    pub fn len(&self) -> usize {
        self.certs.len()
    }
    pub fn is_empty(&self) -> bool {
        self.certs.is_empty()
    }
    pub fn certs(&self) -> &[DelegationCert] {
        &self.certs
    }

    pub fn fingerprint(&self) -> [u8; 32] {
        let mut h = Hasher::new_derive_key(DOMAIN_CHAIN_FP);
        h.update(self.principal_pk.as_bytes());
        h.update(&self.principal_scope);
        if let Some(ns) = &self.namespace {
            h.update(&(ns.len() as u64).to_le_bytes());
            h.update(ns.as_bytes());
        } else {
            h.update(&0u64.to_le_bytes());
        }
        self.certs
            .iter()
            .fold(h, |mut h, cert| {
                h.update(&cert.fingerprint());
                h
            })
            .finalize()
            .into()
    }

    // ── Structural validation (CPU-only, no I/O) ──────────────────────────────

    fn validate_structure(
        &self,
        agent_pk: &VerifyingKey,
        intent: &IntentHash,
        proof: &MerkleProof,
        clock: &dyn Clock,
        drift_tolerance: u64,
    ) -> Result<ChainValidationResult, KyaError> {
        if self.certs.is_empty() {
            return Err(KyaError::EmptyChain);
        }
        if self.certs[0].delegator_pk != self.principal_pk {
            return Err(KyaError::RootMismatch);
        }

        let now = clock.unix_now();
        let tolerated_early = now.saturating_add(drift_tolerance);
        let tolerated_late = now.saturating_sub(drift_tolerance);
        let chain_len = self.certs.len();

        if chain_len > 255 {
            return Err(KyaError::MaxDepthExceeded(255, 255));
        }

        let mut current_scope = self.principal_scope;
        let mut expected_delegator = self.principal_pk;
        let mut depth: usize = 0;
        let mut max_allowed_depth = u8::MAX;
        let mut parent_expiry = u64::MAX;

        let mut seen_nonces: Vec<[u8; 16]> = Vec::with_capacity(chain_len);
        let mut cert_fingerprints: Vec<[u8; 32]> = Vec::with_capacity(chain_len);
        let mut batch_sigs: Vec<ed25519_dalek::Signature> = Vec::with_capacity(chain_len);
        let mut batch_pks: Vec<VerifyingKey> = Vec::with_capacity(chain_len);
        let mut batch_msgs: Vec<Vec<u8>> = Vec::with_capacity(chain_len);

        for (i, cert) in self.certs.iter().enumerate() {
            if cert.delegator_pk != expected_delegator {
                return Err(KyaError::BrokenLinkage(i));
            }

            if cert.version != crate::cert::CERT_VERSION {
                return Err(KyaError::UnsupportedVersion {
                    expected: crate::cert::CERT_VERSION,
                    got: cert.version,
                });
            }

            #[cfg(feature = "wire")]
            let ext_commit = cert.extensions.commitment();
            #[cfg(not(feature = "wire"))]
            let ext_commit = [0u8; 32];

            batch_msgs.push(DelegationCert::signable_bytes(
                cert.version,
                &cert.delegator_pk,
                &cert.delegate_pk,
                &cert.scope_root,
                &cert.scope_proof,
                &cert.nonce,
                cert.issued_at,
                cert.expiration_unix,
                cert.max_depth,
                &ext_commit,
            ));
            batch_sigs.push(cert.signature);
            batch_pks.push(cert.delegator_pk);

            if tolerated_early < cert.issued_at {
                return Err(KyaError::NotYetValid(i, cert.issued_at, now));
            }
            if cert.expiration_unix < tolerated_late {
                return Err(KyaError::Expired(i, cert.expiration_unix, now));
            }
            if cert.expiration_unix > parent_expiry {
                return Err(KyaError::TemporalViolation(
                    i,
                    cert.expiration_unix,
                    parent_expiry,
                ));
            }

            depth += 1;
            if depth > max_allowed_depth as usize {
                return Err(KyaError::MaxDepthExceeded(i, max_allowed_depth));
            }
            if cert.max_depth < max_allowed_depth {
                max_allowed_depth = cert.max_depth;
            }

            for seen in &seen_nonces {
                if seen == &cert.nonce {
                    return Err(KyaError::NonceReplay);
                }
            }
            seen_nonces.push(cert.nonce);
            cert_fingerprints.push(cert.fingerprint());

            let is_passthrough =
                cert.scope_proof.subset_intents.is_empty() && cert.scope_proof.proofs.is_empty();
            if is_passthrough {
                use subtle::ConstantTimeEq;
                if cert.scope_root.ct_eq(&current_scope).unwrap_u8() == 0 {
                    return Err(KyaError::ScopeEscalation(i));
                }
            } else {
                let derived = cert
                    .scope_proof
                    .verify_and_derive_root(&current_scope)
                    .map_err(|_| KyaError::ScopeEscalation(i))?;
                use subtle::ConstantTimeEq;
                if derived.ct_eq(&cert.scope_root).unwrap_u8() == 0 {
                    return Err(KyaError::ScopeEscalation(i));
                }
            }

            parent_expiry = cert.expiration_unix;
            current_scope = cert.scope_root;
            expected_delegator = cert.delegate_pk;
        }

        if expected_delegator != *agent_pk {
            return Err(KyaError::UnauthorizedLeaf);
        }

        {
            let msgs_refs: Vec<&[u8]> = batch_msgs.iter().map(|m| m.as_slice()).collect();
            if ed25519_dalek::verify_batch(&msgs_refs, &batch_sigs, &batch_pks).is_err() {
                for (i, cert) in self.certs.iter().enumerate() {
                    if !cert.verify_signature() {
                        return Err(KyaError::InvalidSignature(i));
                    }
                }
                return Err(KyaError::InvalidSignature(0));
            }
        }

        let intent_authorized = if proof.siblings.is_empty() {
            use subtle::ConstantTimeEq;
            intent.ct_eq(&current_scope).into()
        } else {
            proof.verify(intent, &current_scope)
        };
        if !intent_authorized {
            return Err(KyaError::ScopeViolation);
        }

        Ok(ChainValidationResult {
            depth,
            verified_scope_root: current_scope,
            verified_at_unix: now,
            seen_nonces,
            cert_fingerprints,
            chain_fingerprint: self.fingerprint(),
        })
    }

    // ── authorize ─────────────────────────────────────────────────────────────

    pub fn authorize(
        &self,
        agent_pk: &VerifyingKey,
        intent: &IntentHash,
        proof: &MerkleProof,
        clock: &(dyn Clock + Send + Sync),
        revocation: &(dyn RevocationStore + Send + Sync),
        nonces: &(dyn NonceStore + Send + Sync),
    ) -> Result<AuthorizedAction, KyaError> {
        self.authorize_with_options(
            agent_pk,
            intent,
            proof,
            clock,
            revocation,
            nonces,
            None,
            &NoopAuditSink,
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub fn authorize_with_options(
        &self,
        agent_pk: &VerifyingKey,
        intent_h: &IntentHash,
        proof: &MerkleProof,
        clock: &(dyn Clock + Send + Sync),
        revocation: &(dyn RevocationStore + Send + Sync),
        nonces: &(dyn NonceStore + Send + Sync),
        policy: Option<&PolicySet>,
        sink: &dyn AuditSink,
    ) -> Result<AuthorizedAction, KyaError> {
        #[cfg(feature = "tracing")]
        let _span =
            tracing::info_span!("dyolo_kya::authorize", chain_len = self.certs.len()).entered();

        let principal_hex = hex::encode(self.principal_pk.as_bytes());
        let executor_hex = hex::encode(agent_pk.as_bytes());

        let result =
            self.authorize_inner(agent_pk, intent_h, proof, clock, revocation, nonces, policy);

        let outcome = match &result {
            Ok(_) => AuditOutcome::Authorized,
            Err(KyaError::PolicyViolation(_)) => AuditOutcome::PolicyViolation,
            Err(e) if e.is_transient_storage_failure() => AuditOutcome::StorageError,
            Err(_) => AuditOutcome::Denied,
        };

        let mut event = AuditEvent::new(
            outcome,
            principal_hex,
            executor_hex,
            self.certs.len(),
            intent_h,
            clock.unix_now(),
        );

        if let Ok(action) = &result {
            event = event.with_fingerprint(action.receipt.chain_fingerprint);
            #[cfg(feature = "tracing")]
            tracing::info!(
                chain_depth = action.receipt.chain_depth,
                chain_fingerprint = %action.receipt.fingerprint_hex(),
                "dyolo-kya: authorization succeeded"
            );
        } else if let Err(e) = &result {
            event = event.with_error(e.to_string());
            #[cfg(feature = "tracing")]
            tracing::warn!(error = %e, "dyolo-kya: authorization failed");
        }

        sink.emit(event);
        result
    }

    #[allow(clippy::too_many_arguments)]
    fn authorize_inner(
        &self,
        agent_pk: &VerifyingKey,
        intent_h: &IntentHash,
        proof: &MerkleProof,
        clock: &(dyn Clock + Send + Sync),
        revocation: &(dyn RevocationStore + Send + Sync),
        nonces: &(dyn NonceStore + Send + Sync),
        policy: Option<&PolicySet>,
    ) -> Result<AuthorizedAction, KyaError> {
        if let Some(p) = policy {
            p.check_chain(self)?;
        }

        let v =
            self.validate_structure(agent_pk, intent_h, proof, clock, self.drift_tolerance_secs)?;

        for fp in &v.cert_fingerprints {
            if revocation
                .is_revoked(fp)
                .map_err(KyaError::StorageFailure)?
            {
                return Err(KyaError::Revoked);
            }
        }

        if !nonces
            .try_consume_batch(&v.seen_nonces)
            .map_err(KyaError::StorageFailure)?
        {
            return Err(KyaError::NonceReplay);
        }

        Ok(AuthorizedAction::new(VerificationReceipt {
            chain_depth: v.depth,
            verified_scope_root: v.verified_scope_root,
            intent: *intent_h,
            verified_at_unix: v.verified_at_unix,
            chain_fingerprint: v.chain_fingerprint,
            namespace: self.namespace.clone(),
        }))
    }

    // ── authorize_batch ───────────────────────────────────────────────────────

    pub fn authorize_batch(
        &self,
        agent_pk: &VerifyingKey,
        intents: &[(IntentHash, MerkleProof)],
        clock: &(dyn Clock + Send + Sync),
        revocation: &(dyn RevocationStore + Send + Sync),
        nonces: &(dyn NonceStore + Send + Sync),
    ) -> BatchAuthorizeResult {
        if intents.is_empty() {
            return BatchAuthorizeResult {
                receipts: Vec::new(),
                errors: Vec::new(),
                all_authorized: true,
            };
        }

        let now = clock.unix_now();
        let first_intent = &intents[0].0;
        let first_proof = &intents[0].1;

        let v = match self.validate_structure(
            agent_pk,
            first_intent,
            first_proof,
            clock,
            self.drift_tolerance_secs,
        ) {
            Ok(v) => v,
            Err(e) => {
                let n = intents.len();
                let msg = e.to_string();
                return BatchAuthorizeResult {
                    receipts: vec![None; n],
                    errors: (0..n)
                        .map(|i| {
                            Some(KyaError::BatchItemFailed {
                                index: i,
                                reason: msg.clone(),
                            })
                        })
                        .collect(),
                    all_authorized: false,
                };
            }
        };

        for fp in &v.cert_fingerprints {
            match revocation.is_revoked(fp) {
                Ok(true) => {
                    let n = intents.len();
                    return BatchAuthorizeResult {
                        receipts: vec![None; n],
                        errors: (0..n).map(|_| Some(KyaError::Revoked)).collect(),
                        all_authorized: false,
                    };
                }
                Err(e) => {
                    let n = intents.len();
                    let msg = KyaError::StorageFailure(e).to_string();
                    return BatchAuthorizeResult {
                        receipts: vec![None; n],
                        errors: (0..n)
                            .map(|_| {
                                Some(KyaError::BatchItemFailed {
                                    index: 0,
                                    reason: msg.clone(),
                                })
                            })
                            .collect(),
                        all_authorized: false,
                    };
                }
                Ok(false) => {}
            }
        }

        let mut receipts: Vec<Option<VerificationReceipt>> = Vec::with_capacity(intents.len());
        let mut errors: Vec<Option<KyaError>> = Vec::with_capacity(intents.len());
        let mut all_ok = true;

        for (i, (intent_h, proof)) in intents.iter().enumerate() {
            let intent_authorized = if proof.siblings.is_empty() {
                use subtle::ConstantTimeEq;
                intent_h.ct_eq(&v.verified_scope_root).into()
            } else {
                proof.verify(intent_h, &v.verified_scope_root)
            };

            if intent_authorized {
                receipts.push(Some(VerificationReceipt {
                    chain_depth: v.depth,
                    verified_scope_root: v.verified_scope_root,
                    intent: *intent_h,
                    verified_at_unix: now,
                    chain_fingerprint: v.chain_fingerprint,
                    namespace: self.namespace.clone(),
                }));
                errors.push(None);
            } else {
                receipts.push(None);
                errors.push(Some(KyaError::BatchItemFailed {
                    index: i,
                    reason: KyaError::ScopeViolation.to_string(),
                }));
                all_ok = false;
            }
        }

        if !all_ok {
            return BatchAuthorizeResult {
                receipts,
                errors,
                all_authorized: false,
            };
        }

        match nonces.try_consume_batch(&v.seen_nonces) {
            Ok(true) => {}
            Ok(false) => {
                let n = intents.len();
                return BatchAuthorizeResult {
                    receipts: vec![None; n],
                    errors: (0..n).map(|_| Some(KyaError::NonceReplay)).collect(),
                    all_authorized: false,
                };
            }
            Err(e) => {
                let n = intents.len();
                let msg = KyaError::StorageFailure(e).to_string();
                return BatchAuthorizeResult {
                    receipts: vec![None; n],
                    errors: (0..n)
                        .map(|_| {
                            Some(KyaError::BatchItemFailed {
                                index: 0,
                                reason: msg.clone(),
                            })
                        })
                        .collect(),
                    all_authorized: false,
                };
            }
        }

        BatchAuthorizeResult {
            receipts,
            errors,
            all_authorized: true,
        }
    }

    // ── authorize_async ───────────────────────────────────────────────────────

    #[cfg(feature = "async")]
    pub async fn authorize_async(
        &self,
        agent_pk: &VerifyingKey,
        intent: &IntentHash,
        proof: &MerkleProof,
        clock: &(dyn Clock + Send + Sync),
        revocation: &(dyn crate::registry::r#async::AsyncRevocationStore + Send + Sync),
        nonces: &(dyn crate::registry::r#async::AsyncNonceStore + Send + Sync),
    ) -> Result<AuthorizedAction, KyaError> {
        self.authorize_async_with_options(
            agent_pk,
            intent,
            proof,
            clock,
            revocation,
            nonces,
            None,
            &NoopAuditSink,
        )
        .await
    }

    #[cfg(feature = "async")]
    #[allow(clippy::too_many_arguments)]
    pub async fn authorize_async_with_options(
        &self,
        agent_pk: &VerifyingKey,
        intent_h: &IntentHash,
        proof: &MerkleProof,
        clock: &(dyn Clock + Send + Sync),
        revocation: &(dyn crate::registry::r#async::AsyncRevocationStore + Send + Sync),
        nonces: &(dyn crate::registry::r#async::AsyncNonceStore + Send + Sync),
        policy: Option<&PolicySet>,
        sink: &dyn AuditSink,
    ) -> Result<AuthorizedAction, KyaError> {
        let principal_hex = hex::encode(self.principal_pk.as_bytes());
        let executor_hex = hex::encode(agent_pk.as_bytes());

        #[cfg(feature = "tracing")]
        let span = tracing::info_span!("dyolo_kya::authorize_async", chain_len = self.certs.len());

        let result = async {
            if let Some(p) = policy {
                p.check_chain(self)?;
            }

            let v = self.validate_structure(
                agent_pk,
                intent_h,
                proof,
                clock,
                self.drift_tolerance_secs,
            )?;

            for fp in &v.cert_fingerprints {
                if revocation
                    .is_revoked(fp)
                    .await
                    .map_err(KyaError::StorageFailure)?
                {
                    return Err(KyaError::Revoked);
                }
            }

            if !nonces
                .try_consume_batch(&v.seen_nonces)
                .await
                .map_err(KyaError::StorageFailure)?
            {
                return Err(KyaError::NonceReplay);
            }

            Ok(AuthorizedAction::new(VerificationReceipt {
                chain_depth: v.depth,
                verified_scope_root: v.verified_scope_root,
                intent: *intent_h,
                verified_at_unix: v.verified_at_unix,
                chain_fingerprint: v.chain_fingerprint,
                namespace: self.namespace.clone(),
            }))
        };

        #[cfg(feature = "tracing")]
        let result = result.instrument(span).await;
        #[cfg(not(feature = "tracing"))]
        let result = result.await;

        let outcome = match &result {
            Ok(_) => AuditOutcome::Authorized,
            Err(KyaError::PolicyViolation(_)) => AuditOutcome::PolicyViolation,
            Err(e) if e.is_transient_storage_failure() => AuditOutcome::StorageError,
            Err(_) => AuditOutcome::Denied,
        };

        let mut event = AuditEvent::new(
            outcome,
            principal_hex,
            executor_hex,
            self.certs.len(),
            intent_h,
            clock.unix_now(),
        );

        if let Ok(action) = &result {
            event = event.with_fingerprint(action.receipt.chain_fingerprint);
        } else if let Err(e) = &result {
            event = event.with_error(e.to_string());
        }

        sink.emit(event);
        result
    }

    #[cfg(feature = "async")]
    pub async fn authorize_batch_async(
        &self,
        agent_pk: &VerifyingKey,
        intents: &[(IntentHash, MerkleProof)],
        clock: &(dyn Clock + Send + Sync),
        revocation: &(dyn crate::registry::r#async::AsyncRevocationStore + Send + Sync),
        nonces: &(dyn crate::registry::r#async::AsyncNonceStore + Send + Sync),
    ) -> BatchAuthorizeResult {
        if intents.is_empty() {
            return BatchAuthorizeResult {
                receipts: Vec::new(),
                errors: Vec::new(),
                all_authorized: true,
            };
        }

        let now = clock.unix_now();
        let first_intent = &intents[0].0;
        let first_proof = &intents[0].1;

        let v = match self.validate_structure(
            agent_pk,
            first_intent,
            first_proof,
            clock,
            self.drift_tolerance_secs,
        ) {
            Ok(v) => v,
            Err(e) => {
                let n = intents.len();
                let msg = e.to_string();
                return BatchAuthorizeResult {
                    receipts: vec![None; n],
                    errors: (0..n)
                        .map(|i| {
                            Some(KyaError::BatchItemFailed {
                                index: i,
                                reason: msg.clone(),
                            })
                        })
                        .collect(),
                    all_authorized: false,
                };
            }
        };

        for fp in &v.cert_fingerprints {
            match revocation.is_revoked(fp).await {
                Ok(true) => {
                    let n = intents.len();
                    return BatchAuthorizeResult {
                        receipts: vec![None; n],
                        errors: (0..n).map(|_| Some(KyaError::Revoked)).collect(),
                        all_authorized: false,
                    };
                }
                Err(e) => {
                    let n = intents.len();
                    let msg = KyaError::StorageFailure(e).to_string();
                    return BatchAuthorizeResult {
                        receipts: vec![None; n],
                        errors: (0..n)
                            .map(|_| {
                                Some(KyaError::BatchItemFailed {
                                    index: 0,
                                    reason: msg.clone(),
                                })
                            })
                            .collect(),
                        all_authorized: false,
                    };
                }
                Ok(false) => {}
            }
        }

        let mut receipts: Vec<Option<VerificationReceipt>> = Vec::with_capacity(intents.len());
        let mut errors: Vec<Option<KyaError>> = Vec::with_capacity(intents.len());
        let mut all_ok = true;

        for (i, (intent_h, proof)) in intents.iter().enumerate() {
            let intent_authorized = if proof.siblings.is_empty() {
                use subtle::ConstantTimeEq;
                intent_h.ct_eq(&v.verified_scope_root).into()
            } else {
                proof.verify(intent_h, &v.verified_scope_root)
            };

            if intent_authorized {
                receipts.push(Some(VerificationReceipt {
                    chain_depth: v.depth,
                    verified_scope_root: v.verified_scope_root,
                    intent: *intent_h,
                    verified_at_unix: now,
                    chain_fingerprint: v.chain_fingerprint,
                    namespace: self.namespace.clone(),
                }));
                errors.push(None);
            } else {
                receipts.push(None);
                errors.push(Some(KyaError::BatchItemFailed {
                    index: i,
                    reason: KyaError::ScopeViolation.to_string(),
                }));
                all_ok = false;
            }
        }

        if !all_ok {
            return BatchAuthorizeResult {
                receipts,
                errors,
                all_authorized: false,
            };
        }

        match nonces.try_consume_batch(&v.seen_nonces).await {
            Ok(true) => {}
            Ok(false) => {
                let n = intents.len();
                return BatchAuthorizeResult {
                    receipts: vec![None; n],
                    errors: (0..n).map(|_| Some(KyaError::NonceReplay)).collect(),
                    all_authorized: false,
                };
            }
            Err(e) => {
                let n = intents.len();
                let msg = KyaError::StorageFailure(e).to_string();
                return BatchAuthorizeResult {
                    receipts: vec![None; n],
                    errors: (0..n)
                        .map(|_| {
                            Some(KyaError::BatchItemFailed {
                                index: 0,
                                reason: msg.clone(),
                            })
                        })
                        .collect(),
                    all_authorized: false,
                };
            }
        }

        BatchAuthorizeResult {
            receipts,
            errors,
            all_authorized: true,
        }
    }
}

impl Clone for DyoloChain {
    fn clone(&self) -> Self {
        Self {
            principal_pk: self.principal_pk,
            principal_scope: self.principal_scope,
            certs: self.certs.clone(),
            drift_tolerance_secs: self.drift_tolerance_secs,
            namespace: self.namespace.clone(),
        }
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    #[allow(deprecated)]
    use crate::{
        cert::CertBuilder,
        identity::DyoloIdentity,
        intent::{intent_hash, IntentTree},
        registry::{MemoryNonceStore, MemoryRevocationStore},
    };

    struct FixedClock(u64);
    impl Clock for FixedClock {
        fn unix_now(&self) -> u64 {
            self.0
        }
    }

    #[allow(deprecated)]
    fn setup() -> (DyoloIdentity, DyoloIdentity, DyoloIdentity, IntentTree, u64) {
        let human = DyoloIdentity::generate();
        let agent_a = DyoloIdentity::generate();
        let agent_b = DyoloIdentity::generate();
        let trade = intent_hash("TRADE_AAPL_100", b"limit=182.50");
        let query = intent_hash("QUERY_PORTFOLIO", b"");
        let tree = IntentTree::build(vec![trade, query]).unwrap();
        let now = 1_700_000_000u64;
        (human, agent_a, agent_b, tree, now)
    }

    #[allow(deprecated)]
    fn two_hop_chain(
        human: &DyoloIdentity,
        a: &DyoloIdentity,
        b: &DyoloIdentity,
        scope: IntentHash,
        now: u64,
    ) -> DyoloChain {
        let expiry = now + 3600;
        let ca = CertBuilder::new(a.verifying_key(), scope, now, expiry).sign(human);
        let cb = CertBuilder::new(b.verifying_key(), scope, now, expiry).sign(a);
        let mut chain = DyoloChain::new(human.verifying_key(), scope);
        chain.push(ca).push(cb);
        chain
    }

    #[test]
    #[allow(deprecated)]
    fn full_delegation_chain_succeeds() {
        let (human, a, b, tree, now) = setup();
        let root = tree.root();
        let trade = intent_hash("TRADE_AAPL_100", b"limit=182.50");
        let proof = tree.prove(&trade).unwrap();
        let chain = two_hop_chain(&human, &a, &b, root, now);
        let action = chain
            .authorize(
                &b.verifying_key(),
                &trade,
                &proof,
                &FixedClock(now),
                &MemoryRevocationStore::new(),
                &MemoryNonceStore::new(),
            )
            .unwrap();
        assert_eq!(action.receipt.chain_depth, 2);
        assert_eq!(action.receipt.intent, trade);
        assert!(action.receipt.namespace.is_none());
    }

    #[test]
    #[allow(deprecated)]
    fn namespace_isolation_different_scopes() {
        let human = DyoloIdentity::generate();
        let agent = DyoloIdentity::generate();
        let now = SystemClock.unix_now();

        // Two namespaced chains from the same base scope must produce different principal_scopes
        let base_scope: IntentHash = intent_hash("trade", b"");
        let chain_a = DyoloChain::new(human.verifying_key(), base_scope).with_namespace("tenant-a");
        let chain_b = DyoloChain::new(human.verifying_key(), base_scope).with_namespace("tenant-b");

        assert_ne!(
            chain_a.principal_scope, chain_b.principal_scope,
            "namespaced chains must have different effective scopes"
        );
        assert_ne!(chain_a.fingerprint(), chain_b.fingerprint());

        // The namespaced principal_scope IS the intent for a single-scope chain.
        // A cert whose scope_root = scope_a can authorize scope_a as the intent
        // (empty proof: intent must equal current_scope after traversal).
        let scope_a = chain_a.principal_scope;
        let scope_b = chain_b.principal_scope;

        let cert_a =
            CertBuilder::new(agent.verifying_key(), scope_a, now, now + 86400).sign(&human);
        let cert_b =
            CertBuilder::new(agent.verifying_key(), scope_b, now, now + 86400).sign(&human);

        // Tenant-a chain authorizes scope_a as the intent
        let mut ca = DyoloChain::new(human.verifying_key(), scope_a);
        ca.push(cert_a);
        let ok_a = ca.authorize(
            &agent.verifying_key(),
            &scope_a,
            &MerkleProof::default(),
            &FixedClock(now),
            &MemoryRevocationStore::new(),
            &MemoryNonceStore::new(),
        );
        assert!(
            ok_a.is_ok(),
            "tenant-a cert should authorize under tenant-a scope: {:?}",
            ok_a.err()
        );

        // Tenant-b chain authorizes scope_b as the intent
        let mut cb = DyoloChain::new(human.verifying_key(), scope_b);
        cb.push(cert_b);
        let ok_b = cb.authorize(
            &agent.verifying_key(),
            &scope_b,
            &MerkleProof::default(),
            &FixedClock(now),
            &MemoryRevocationStore::new(),
            &MemoryNonceStore::new(),
        );
        assert!(
            ok_b.is_ok(),
            "tenant-b cert should authorize under tenant-b scope: {:?}",
            ok_b.err()
        );

        // Cross-namespace: cert issued for scope_b must fail under a chain expecting scope_a
        // because cert.scope_root (scope_b) != ca.principal_scope (scope_a) => BrokenLinkage or ScopeEscalation
        let cert_b_wrong =
            CertBuilder::new(agent.verifying_key(), scope_b, now, now + 86400).sign(&human);
        let mut c_wrong = DyoloChain::new(human.verifying_key(), scope_a);
        c_wrong.push(cert_b_wrong);
        let result = c_wrong.authorize(
            &agent.verifying_key(),
            &scope_a,
            &MerkleProof::default(),
            &FixedClock(now),
            &MemoryRevocationStore::new(),
            &MemoryNonceStore::new(),
        );
        assert!(
            result.is_err(),
            "cert scoped to tenant-b must not work under tenant-a chain"
        );
    }

    #[test]
    #[allow(deprecated)]
    fn batch_authorize_all_or_nothing() {
        let (human, a, b, tree, now) = setup();
        let root = tree.root();
        let trade = intent_hash("TRADE_AAPL_100", b"limit=182.50");
        let query = intent_hash("QUERY_PORTFOLIO", b"");
        let t_proof = tree.prove(&trade).unwrap();
        let q_proof = tree.prove(&query).unwrap();
        let chain = two_hop_chain(&human, &a, &b, root, now);
        let result = chain.authorize_batch(
            &b.verifying_key(),
            &[(trade, t_proof), (query, q_proof)],
            &FixedClock(now),
            &MemoryRevocationStore::new(),
            &MemoryNonceStore::new(),
        );
        assert!(result.all_authorized);
        assert_eq!(result.authorized_count(), 2);
    }

    #[test]
    #[allow(deprecated)]
    fn chain_fingerprint_stable() {
        let (human, a, b, tree, now) = setup();
        let chain = two_hop_chain(&human, &a, &b, tree.root(), now);
        assert_eq!(chain.fingerprint(), chain.clone().fingerprint());
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    #[allow(deprecated)]
    async fn authorize_async_succeeds() {
        use crate::registry::r#async::{SyncNonceAdapter, SyncRevocationAdapter};
        use std::sync::Arc;
        let (human, a, b, tree, now) = setup();
        let root = tree.root();
        let trade = intent_hash("TRADE_AAPL_100", b"limit=182.50");
        let proof = tree.prove(&trade).unwrap();
        let chain = two_hop_chain(&human, &a, &b, root, now);
        let rev = SyncRevocationAdapter(Arc::new(MemoryRevocationStore::new()));
        let nonces = SyncNonceAdapter(Arc::new(MemoryNonceStore::new()));
        let action = chain
            .authorize_async(
                &b.verifying_key(),
                &trade,
                &proof,
                &FixedClock(now),
                &rev,
                &nonces,
            )
            .await
            .unwrap();
        assert_eq!(action.receipt.chain_depth, 2);
    }
}