polyc-crypto 2026.8.2

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
//! Compile-time separated platform signing roles and public identities.
//!
//! Domain prefixes keep signatures for two artifact shapes from verifying as
//! one another. They do not limit what a stolen private key can mint. These
//! role types close that larger blast radius: approval, browser-session,
//! turn-read, web-session-grant, journal-attestation, handoff, and sub-agent
//! keys are different types loaded from different custody references.
//!
//! A role alone does not separate two artifact shapes that share it. The
//! signer must also frame the artifact kind into the signed bytes. See
//! [`RoleSigner::sign_handoff`] and its three siblings for that frame.

use std::{marker::PhantomData, sync::Arc};

use sha2::{Digest as _, Sha256};

use crate::{Signer, verify};

mod private {
    pub trait Sealed {}
}

/// A stable signing-role identity.
pub trait SigningRole: private::Sealed + Send + Sync + 'static {
    /// Stable issuer string recorded beside this role's trust history.
    const ISSUER: &'static str;
}

macro_rules! role {
    ($(#[$meta:meta])* $name:ident, $issuer:literal) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub struct $name;
        impl private::Sealed for $name {}
        impl SigningRole for $name {
            const ISSUER: &'static str = $issuer;
        }
    };
}

role!(
    /// Human and policy approval decisions and their durable markers.
    ApprovalRole,
    "polychrome.control.approval"
);
role!(
    /// State-authorized browser-session bearer tokens.
    SessionRole,
    "polychrome.control.session"
);
role!(
    /// Conversation-scoped query capability grants.
    TurnReadRole,
    "polychrome.control.turn-read"
);
role!(
    /// Deterministic web-session-family rotation grants.
    WebSessionGrantRole,
    "polychrome.control.web-session-grant"
);
role!(
    /// Tamper-evident journal-root attestations.
    JournalAttestationRole,
    "polychrome.state.journal-attestation"
);
role!(
    /// Parent-to-child conversation handoff provenance.
    HandoffRole,
    "polychrome.control.handoff"
);
role!(
    /// Sub-agent delegation spawn and result provenance.
    SubagentRole,
    "polychrome.control.subagent"
);

/// Stable secret-manager reference for Control's approval-role private key.
pub const CONTROL_APPROVAL_KEY_REF: &str = "control-plane/approval-signer";
/// Stable secret-manager reference for Control's approval public history.
pub const CONTROL_APPROVAL_HISTORY_REF: &str = "control-plane/approval-signer-history";
/// Stable secret-manager reference for Control's session-role private key.
pub const CONTROL_SESSION_KEY_REF: &str = "control-plane/session-signer";
/// Stable secret-manager reference for Control's session public history.
pub const CONTROL_SESSION_HISTORY_REF: &str = "control-plane/session-signer-history";
/// Stable secret-manager reference for Control's turn-read private key.
pub const CONTROL_TURN_READ_KEY_REF: &str = "control-plane/turn-read-signer";
/// Stable secret-manager reference for Control's turn-read public history.
pub const CONTROL_TURN_READ_HISTORY_REF: &str = "control-plane/turn-read-signer-history";
/// Stable secret-manager reference for Control's web-session-grant private key.
pub const CONTROL_WEB_SESSION_GRANT_KEY_REF: &str = "control-plane/web-session-grant-signer";
/// Stable secret-manager reference for Control's web-session-grant history.
pub const CONTROL_WEB_SESSION_GRANT_HISTORY_REF: &str =
    "control-plane/web-session-grant-signer-history";
/// Stable reference for Control's temporary memory-journal private key.
pub const CONTROL_MEMORY_JOURNAL_KEY_REF: &str = "control-plane/memory-journal-attestation-signer";
/// Stable reference for Control's temporary memory-journal public history.
pub const CONTROL_MEMORY_JOURNAL_HISTORY_REF: &str =
    "control-plane/memory-journal-attestation-signer-history";
/// Stable secret-manager reference for Control's handoff-role private key.
pub const CONTROL_HANDOFF_KEY_REF: &str = "control-plane/handoff-signer";
/// Stable secret-manager reference for Control's handoff public history.
pub const CONTROL_HANDOFF_HISTORY_REF: &str = "control-plane/handoff-signer-history";
/// Stable secret-manager reference for Control's subagent-role private key.
pub const CONTROL_SUBAGENT_KEY_REF: &str = "control-plane/subagent-signer";
/// Stable secret-manager reference for Control's subagent public history.
pub const CONTROL_SUBAGENT_HISTORY_REF: &str = "control-plane/subagent-signer-history";

/// Public identity of one signing key within one role.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SigningKeyIdentity {
    issuer: String,
    key_id: String,
    public_key: Vec<u8>,
}

impl SigningKeyIdentity {
    /// Derives the canonical identity for a trusted role public key.
    ///
    /// # Errors
    ///
    /// Refuses a value that is not an encoded ed25519 public key.
    pub fn for_public_key<R: SigningRole>(
        public_key: Vec<u8>,
    ) -> Result<Self, SigningIdentityError> {
        if public_key.len() != 32 {
            return Err(SigningIdentityError::InvalidPublicKey);
        }
        Ok(Self {
            issuer: R::ISSUER.to_owned(),
            key_id: key_id(R::ISSUER, &public_key),
            public_key,
        })
    }

    /// Reconstructs a public identity read from trusted custody metadata.
    ///
    /// # Errors
    ///
    /// Refuses an issuer mismatch, malformed key, or key id not derived from
    /// the exact issuer and public key.
    pub fn checked<R: SigningRole>(
        issuer: impl Into<String>,
        claimed_key_id: impl Into<String>,
        public_key: Vec<u8>,
    ) -> Result<Self, SigningIdentityError> {
        let identity = Self {
            issuer: issuer.into(),
            key_id: claimed_key_id.into(),
            public_key,
        };
        if identity.issuer != R::ISSUER {
            return Err(SigningIdentityError::WrongIssuer);
        }
        if identity.public_key.len() != 32 {
            return Err(SigningIdentityError::InvalidPublicKey);
        }
        if identity.key_id != key_id(R::ISSUER, &identity.public_key) {
            return Err(SigningIdentityError::WrongKeyId);
        }
        Ok(identity)
    }

    /// Stable role issuer.
    #[must_use]
    pub fn issuer(&self) -> &str {
        &self.issuer
    }

    /// Deterministic identifier for this issuer/public-key pair.
    #[must_use]
    pub fn key_id(&self) -> &str {
        &self.key_id
    }

    /// Encoded ed25519 public key.
    #[must_use]
    pub fn public_key(&self) -> &[u8] {
        &self.public_key
    }
}

/// Invalid public signing-key identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum SigningIdentityError {
    /// The record belongs to another signing role.
    #[error("signing-key issuer does not match its role")]
    WrongIssuer,
    /// The ed25519 public key is not 32 bytes.
    #[error("signing public key is not an encoded ed25519 key")]
    InvalidPublicKey,
    /// The claimed key id does not cover the issuer and public key.
    #[error("signing key id does not match its issuer and public key")]
    WrongKeyId,
}

/// Deployment-pinned verdict for one signed platform artifact.
///
/// A verdict answers two questions in one value. The signature must check out
/// against the public key the artifact carries. That key must also belong to
/// the deployment trust set for the artifact's signing role.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SignatureVerdict {
    /// The signature checks out and its key is in the deployment trust set.
    Verified,
    /// The signature does not check out against the embedded public key.
    Invalid,
    /// The signature checks out, but the deployment does not trust the key.
    Untrusted,
}

impl SignatureVerdict {
    /// Stable lowercase name for projections, read surfaces, and logs.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Verified => "verified",
            Self::Invalid => "invalid",
            Self::Untrusted => "untrusted",
        }
    }
}

impl std::fmt::Display for SignatureVerdict {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// One role's private signer.
pub struct RoleSigner<R: SigningRole> {
    inner: Arc<Signer>,
    role: PhantomData<R>,
}

impl<R: SigningRole> Clone for RoleSigner<R> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
            role: PhantomData,
        }
    }
}

impl<R: SigningRole> std::fmt::Debug for RoleSigner<R> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("RoleSigner")
            .field("identity", &self.identity())
            .finish_non_exhaustive()
    }
}

impl<R: SigningRole> RoleSigner<R> {
    /// Builds a signer from an insecure deterministic test seed.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub fn from_seed(seed: u64) -> Self {
        Self {
            inner: Arc::new(Signer::from_seed(seed)),
            role: PhantomData,
        }
    }

    /// Builds this role from raw ed25519 private-key bytes held by custody.
    ///
    /// # Errors
    ///
    /// Returns [`crate::SignerError`] for malformed private-key material.
    pub fn from_key_bytes(bytes: &[u8]) -> Result<Self, crate::SignerError> {
        Ok(Self {
            inner: Arc::new(Signer::from_key_bytes(bytes)?),
            role: PhantomData,
        })
    }

    /// Encoded public key.
    #[must_use]
    pub fn public_key_bytes(&self) -> Vec<u8> {
        self.inner.public_key_bytes()
    }

    /// Explicit issuer and deterministic key identity.
    #[must_use]
    pub fn identity(&self) -> SigningKeyIdentity {
        let public_key = self.public_key_bytes();
        SigningKeyIdentity {
            issuer: R::ISSUER.to_owned(),
            key_id: key_id(R::ISSUER, &public_key),
            public_key,
        }
    }

    /// Signs bytes inside this crate's role-specific protocol builders.
    ///
    /// Kept crate-private so holding one role never exposes a generic signing
    /// oracle that can manufacture another role's canonical artifact.
    #[must_use]
    pub(crate) fn sign(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner.sign(canonical_bytes)
    }

    /// Borrows the primitive for this crate's role-specific envelope builders.
    ///
    /// Kept crate-private so an external caller holding one role cannot erase
    /// its type and pass the same private key to another signing protocol.
    #[must_use]
    pub(crate) fn as_signer(&self) -> &Signer {
        &self.inner
    }

    /// Re-labels deterministic fixture material for a different role.
    ///
    /// Production builds cannot convert one signing role into another;
    /// callers must load independent custody records instead.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub fn relabel_for_test<S: SigningRole>(&self) -> RoleSigner<S> {
        RoleSigner {
            inner: Arc::clone(&self.inner),
            role: PhantomData,
        }
    }
}

impl RoleSigner<TurnReadRole> {
    /// Signs a canonical conversation-scoped turn-read capability.
    ///
    /// This named role operation avoids exposing the underlying signer or a
    /// generic cross-protocol signing method to query-layer callers.
    #[must_use]
    pub fn sign_turn_read_capability(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner
            .sign(&role_scoped_message::<TurnReadRole>(canonical_bytes))
    }
}

impl RoleSigner<JournalAttestationRole> {
    /// Signs a canonical Merkle Mountain Range journal-root attestation.
    ///
    /// This named role operation avoids exposing the underlying signer or a
    /// generic cross-protocol signing method to journal callers.
    #[must_use]
    pub fn sign_journal_root(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner
            .sign(&role_scoped_message::<JournalAttestationRole>(
                canonical_bytes,
            ))
    }
}

impl RoleSigner<HandoffRole> {
    /// Signs the canonical bytes of an accepted conversation handoff.
    ///
    /// The signature covers the handoff artifact domain, so it never verifies
    /// as a refusal or as a sub-agent artifact.
    #[must_use]
    pub fn sign_handoff(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner.sign(&artifact_scoped_message::<HandoffRole>(
            HANDOFF_ARTIFACT,
            canonical_bytes,
        ))
    }

    /// Signs the canonical bytes of a refused conversation handoff.
    ///
    /// The signature covers the refusal artifact domain, so it never verifies
    /// as an accepted handoff or as a sub-agent artifact.
    #[must_use]
    pub fn sign_handoff_denied(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner.sign(&artifact_scoped_message::<HandoffRole>(
            HANDOFF_DENIED_ARTIFACT,
            canonical_bytes,
        ))
    }
}

impl RoleSigner<SubagentRole> {
    /// Signs the canonical bytes of a sub-agent spawn.
    ///
    /// The signature covers the spawn artifact domain, so it never verifies as
    /// a sub-agent result or as a handoff artifact.
    #[must_use]
    pub fn sign_subagent_spawn(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner.sign(&artifact_scoped_message::<SubagentRole>(
            SUBAGENT_SPAWN_ARTIFACT,
            canonical_bytes,
        ))
    }

    /// Signs the canonical bytes of a sub-agent result.
    ///
    /// The signature covers the result artifact domain, so it never verifies as
    /// a sub-agent spawn or as a handoff artifact.
    #[must_use]
    pub fn sign_subagent_result(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner.sign(&artifact_scoped_message::<SubagentRole>(
            SUBAGENT_RESULT_ARTIFACT,
            canonical_bytes,
        ))
    }
}

/// Public trust set for exactly one signing role.
#[derive(Debug, Clone)]
pub struct RoleTrustSet<R: SigningRole> {
    keys: Vec<SigningKeyIdentity>,
    role: PhantomData<R>,
}

/// Append-only public-key history for one signing role.
///
/// The record contains public identities only. Custody persists the current
/// private key under a separate secret reference and stores this record as the
/// durable verification history.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SigningKeyHistory {
    current: SigningKeyIdentity,
    retired: Vec<SigningKeyIdentity>,
}

impl SigningKeyHistory {
    /// Starts a history at one role's current signer.
    #[must_use]
    pub fn current<R: SigningRole>(signer: &RoleSigner<R>) -> Self {
        Self {
            current: signer.identity(),
            retired: Vec::new(),
        }
    }

    /// Public identity recorded as current.
    #[must_use]
    pub const fn current_identity(&self) -> &SigningKeyIdentity {
        &self.current
    }

    /// Append-only public identities recorded as retired.
    #[must_use]
    pub fn retired_identities(&self) -> &[SigningKeyIdentity] {
        &self.retired
    }

    /// Reconciles a stored history with the current signer identity.
    ///
    /// A rotation appends the previous current identity to `retired`. Cycling
    /// back to an earlier key never removes it from the stored retired set,
    /// while the returned trust set lists each identity once with current
    /// first.
    ///
    /// # Errors
    ///
    /// Refuses a malformed identity, an identity from another role, or a
    /// duplicate retired identity.
    pub fn reconcile<R: SigningRole>(
        &mut self,
        current: &SigningKeyIdentity,
    ) -> Result<(RoleTrustSet<R>, bool), SigningIdentityError> {
        let current = SigningKeyIdentity::checked::<R>(
            current.issuer.clone(),
            current.key_id.clone(),
            current.public_key.clone(),
        )?;
        let prior_current = SigningKeyIdentity::checked::<R>(
            self.current.issuer.clone(),
            self.current.key_id.clone(),
            self.current.public_key.clone(),
        )?;
        let mut retired = self
            .retired
            .iter()
            .map(|identity| {
                SigningKeyIdentity::checked::<R>(
                    identity.issuer.clone(),
                    identity.key_id.clone(),
                    identity.public_key.clone(),
                )
            })
            .collect::<Result<Vec<_>, _>>()?;
        for (index, identity) in retired.iter().enumerate() {
            if retired[..index]
                .iter()
                .any(|prior| prior.key_id == identity.key_id)
            {
                return Err(SigningIdentityError::WrongKeyId);
            }
        }

        let rotated = prior_current != current;
        if rotated
            && !retired
                .iter()
                .any(|identity| identity.key_id == prior_current.key_id)
        {
            retired.push(prior_current);
        }
        self.current = current.clone();
        self.retired.clone_from(&retired);

        let mut identities = vec![current.clone()];
        identities.extend(
            retired
                .into_iter()
                .filter(|identity| identity.key_id != current.key_id),
        );
        Ok((RoleTrustSet::checked(identities)?, rotated))
    }
}

impl<R: SigningRole> RoleTrustSet<R> {
    /// Derives canonical identities for a non-empty list of trusted keys.
    ///
    /// # Errors
    ///
    /// Refuses empty, duplicate, or malformed public keys.
    pub fn from_public_keys(keys: Vec<Vec<u8>>) -> Result<Self, SigningIdentityError> {
        let identities = keys
            .into_iter()
            .map(SigningKeyIdentity::for_public_key::<R>)
            .collect::<Result<Vec<_>, _>>()?;
        Self::checked(identities)
    }

    /// Validates and canonicalizes a non-empty role trust set.
    ///
    /// # Errors
    ///
    /// Refuses empty, duplicate, malformed, or cross-role identities.
    pub fn checked(keys: Vec<SigningKeyIdentity>) -> Result<Self, SigningIdentityError> {
        if keys.is_empty() {
            return Err(SigningIdentityError::InvalidPublicKey);
        }
        let mut checked = Vec::with_capacity(keys.len());
        for key in keys {
            let key = SigningKeyIdentity::checked::<R>(key.issuer, key.key_id, key.public_key)?;
            if checked
                .iter()
                .any(|known: &SigningKeyIdentity| known.key_id == key.key_id)
            {
                return Err(SigningIdentityError::WrongKeyId);
            }
            checked.push(key);
        }
        Ok(Self {
            keys: checked,
            role: PhantomData,
        })
    }

    /// Trusts only the current signer.
    #[must_use]
    pub fn current(signer: &RoleSigner<R>) -> Self {
        Self {
            keys: vec![signer.identity()],
            role: PhantomData,
        }
    }

    /// Public identities, current first and retired afterward.
    #[must_use]
    pub fn keys(&self) -> &[SigningKeyIdentity] {
        &self.keys
    }

    /// Verifies against the explicitly named key in this role.
    #[must_use]
    pub(crate) fn verify(&self, key_id: &str, message: &[u8], signature: &[u8]) -> bool {
        self.keys
            .iter()
            .find(|key| key.key_id == key_id)
            .is_some_and(|key| verify(&key.public_key, message, signature))
    }

    /// Classifies an artifact that carries the public key it was signed with.
    ///
    /// The check runs in two stages. Stage one verifies the signature against
    /// the embedded key inside this role and artifact domain. Stage two finds
    /// the corresponding trusted identity. It verifies again against the
    /// public key stored in that identity.
    fn classify(
        &self,
        kind: &str,
        signed_by: &[u8],
        canonical_bytes: &[u8],
        signature: &[u8],
    ) -> SignatureVerdict {
        let message = artifact_scoped_message::<R>(kind, canonical_bytes);
        if !verify(signed_by, &message, signature) {
            return SignatureVerdict::Invalid;
        }
        let Ok(identity) = SigningKeyIdentity::for_public_key::<R>(signed_by.to_vec()) else {
            return SignatureVerdict::Invalid;
        };
        if !self.keys.iter().any(|key| key.key_id == identity.key_id) {
            return SignatureVerdict::Untrusted;
        }
        if self.verify(&identity.key_id, &message, signature) {
            SignatureVerdict::Verified
        } else {
            SignatureVerdict::Invalid
        }
    }
}

impl RoleTrustSet<TurnReadRole> {
    /// Verifies a canonical conversation-scoped turn-read capability.
    #[must_use]
    pub fn verify_turn_read_capability(
        &self,
        key_id: &str,
        canonical_bytes: &[u8],
        signature: &[u8],
    ) -> bool {
        self.verify(
            key_id,
            &role_scoped_message::<TurnReadRole>(canonical_bytes),
            signature,
        )
    }
}

impl RoleTrustSet<JournalAttestationRole> {
    /// Verifies a canonical Merkle Mountain Range journal-root attestation.
    #[must_use]
    pub fn verify_journal_root(
        &self,
        key_id: &str,
        canonical_bytes: &[u8],
        signature: &[u8],
    ) -> bool {
        self.verify(
            key_id,
            &role_scoped_message::<JournalAttestationRole>(canonical_bytes),
            signature,
        )
    }
}

impl RoleTrustSet<HandoffRole> {
    /// Classifies the signature on an accepted conversation handoff.
    #[must_use]
    pub fn classify_handoff(
        &self,
        signed_by: &[u8],
        canonical_bytes: &[u8],
        signature: &[u8],
    ) -> SignatureVerdict {
        self.classify(HANDOFF_ARTIFACT, signed_by, canonical_bytes, signature)
    }

    /// Classifies the signature on a refused conversation handoff.
    #[must_use]
    pub fn classify_handoff_denied(
        &self,
        signed_by: &[u8],
        canonical_bytes: &[u8],
        signature: &[u8],
    ) -> SignatureVerdict {
        self.classify(
            HANDOFF_DENIED_ARTIFACT,
            signed_by,
            canonical_bytes,
            signature,
        )
    }
}

impl RoleTrustSet<SubagentRole> {
    /// Classifies the signature on a sub-agent spawn.
    #[must_use]
    pub fn classify_subagent_spawn(
        &self,
        signed_by: &[u8],
        canonical_bytes: &[u8],
        signature: &[u8],
    ) -> SignatureVerdict {
        self.classify(
            SUBAGENT_SPAWN_ARTIFACT,
            signed_by,
            canonical_bytes,
            signature,
        )
    }

    /// Classifies the signature on a sub-agent result.
    #[must_use]
    pub fn classify_subagent_result(
        &self,
        signed_by: &[u8],
        canonical_bytes: &[u8],
        signature: &[u8],
    ) -> SignatureVerdict {
        self.classify(
            SUBAGENT_RESULT_ARTIFACT,
            signed_by,
            canonical_bytes,
            signature,
        )
    }
}

/// Approval signer type retained at its established public path.
pub type ApprovalSigner = RoleSigner<ApprovalRole>;
/// Browser-session signer.
pub type SessionSigner = RoleSigner<SessionRole>;
/// Conversation turn-read capability signer.
pub type TurnReadSigner = RoleSigner<TurnReadRole>;
/// Web-session-family grant signer.
pub type WebSessionGrantSigner = RoleSigner<WebSessionGrantRole>;
/// Journal-root attestation signer.
pub type JournalAttestationSigner = RoleSigner<JournalAttestationRole>;
/// Conversation handoff provenance signer.
pub type HandoffSigner = RoleSigner<HandoffRole>;
/// Sub-agent delegation provenance signer.
pub type SubagentSigner = RoleSigner<SubagentRole>;

/// Artifact domain name for an accepted conversation handoff.
const HANDOFF_ARTIFACT: &str = "handoff";
/// Artifact domain name for a refused conversation handoff.
const HANDOFF_DENIED_ARTIFACT: &str = "handoff-denied";
/// Artifact domain name for a sub-agent spawn.
const SUBAGENT_SPAWN_ARTIFACT: &str = "subagent-spawn";
/// Artifact domain name for a sub-agent result.
const SUBAGENT_RESULT_ARTIFACT: &str = "subagent-result";

fn key_id(issuer: &str, public_key: &[u8]) -> String {
    let mut hash = Sha256::new();
    hash.update(b"polychrome.signing-key-id.v1\0");
    hash.update(
        u64::try_from(issuer.len())
            .unwrap_or(u64::MAX)
            .to_be_bytes(),
    );
    hash.update(issuer.as_bytes());
    hash.update(public_key);
    crate::hex::lower(&hash.finalize())
}

fn role_scoped_message<R: SigningRole>(canonical_bytes: &[u8]) -> Vec<u8> {
    let mut message = Vec::with_capacity(40 + R::ISSUER.len() + canonical_bytes.len());
    message.extend_from_slice(b"polychrome.signing-role.v1\0");
    message.extend_from_slice(
        &u64::try_from(R::ISSUER.len())
            .unwrap_or(u64::MAX)
            .to_be_bytes(),
    );
    message.extend_from_slice(R::ISSUER.as_bytes());
    message.extend_from_slice(canonical_bytes);
    message
}

/// Frames canonical bytes inside one signing role and one artifact kind.
///
/// The frame is injective. Every variable-length field before the trailing
/// canonical bytes carries its own big-endian length. Two different (role,
/// kind) pairs therefore never produce the same signed message.
fn artifact_scoped_message<R: SigningRole>(kind: &str, canonical_bytes: &[u8]) -> Vec<u8> {
    let mut message = Vec::with_capacity(48 + R::ISSUER.len() + kind.len() + canonical_bytes.len());
    message.extend_from_slice(b"polychrome.signed-artifact.v1\0");
    message.extend_from_slice(&length_prefix(R::ISSUER.len()));
    message.extend_from_slice(R::ISSUER.as_bytes());
    message.extend_from_slice(&length_prefix(kind.len()));
    message.extend_from_slice(kind.as_bytes());
    message.extend_from_slice(canonical_bytes);
    message
}

fn length_prefix(length: usize) -> [u8; 8] {
    u64::try_from(length).unwrap_or(u64::MAX).to_be_bytes()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn roles_have_distinct_issuers_and_key_ids() {
        let approval = ApprovalSigner::from_seed(7);
        let session = SessionSigner::from_seed(7);
        assert_ne!(approval.identity().issuer(), session.identity().issuer());
        assert_ne!(approval.identity().key_id(), session.identity().key_id());
        assert_eq!(approval.public_key_bytes(), session.public_key_bytes());
    }

    #[test]
    fn a_cross_role_identity_is_refused() {
        let identity = ApprovalSigner::from_seed(7).identity();
        assert_eq!(
            SigningKeyIdentity::checked::<SessionRole>(
                identity.issuer,
                identity.key_id,
                identity.public_key,
            ),
            Err(SigningIdentityError::WrongIssuer)
        );
    }

    #[test]
    fn role_trust_requires_the_named_key() {
        let current = SessionSigner::from_seed(7);
        let retired = SessionSigner::from_seed(8);
        let trust =
            RoleTrustSet::<SessionRole>::checked(vec![current.identity(), retired.identity()])
                .expect("valid role history");
        let message = b"session";
        assert!(trust.verify(current.identity().key_id(), message, &current.sign(message)));
        assert!(trust.verify(retired.identity().key_id(), message, &retired.sign(message)));
        assert!(!trust.verify("unknown", message, &current.sign(message)));
    }

    #[test]
    fn role_trust_survives_key_cycling_without_cross_role_acceptance() {
        let first = SessionSigner::from_seed(7);
        let second = SessionSigner::from_seed(8);
        let third = SessionSigner::from_seed(9);
        let trust = RoleTrustSet::<SessionRole>::checked(vec![
            third.identity(),
            second.identity(),
            first.identity(),
        ])
        .expect("valid cycled history");
        let message = b"session";

        for signer in [&first, &second, &third] {
            assert!(trust.verify(signer.identity().key_id(), message, &signer.sign(message)));
        }

        let approval = ApprovalSigner::from_seed(7);
        assert!(!trust.verify(
            approval.identity().key_id(),
            message,
            &approval.sign(message),
        ));
    }

    #[test]
    fn history_rotation_and_cycling_preserve_each_public_identity_once() {
        let first = SessionSigner::from_seed(7);
        let second = SessionSigner::from_seed(8);
        let mut history = SigningKeyHistory::current(&first);

        let (trust, rotated) = history
            .reconcile::<SessionRole>(&second.identity())
            .expect("first rotation is valid");
        assert!(rotated);
        assert_eq!(trust.keys(), &[second.identity(), first.identity()]);

        let (trust, rotated) = history
            .reconcile::<SessionRole>(&first.identity())
            .expect("cycling back is valid");
        assert!(rotated);
        assert_eq!(trust.keys(), &[first.identity(), second.identity()]);

        let (trust, rotated) = history
            .reconcile::<SessionRole>(&second.identity())
            .expect("cycling forward is valid");
        assert!(rotated);
        assert_eq!(trust.keys(), &[second.identity(), first.identity()]);
        assert_eq!(
            history.retired_identities(),
            &[first.identity(), second.identity()]
        );
    }

    #[test]
    fn history_rejects_duplicate_retired_identity() {
        let first = SessionSigner::from_seed(7);
        let second = SessionSigner::from_seed(8);
        let mut history = SigningKeyHistory {
            current: second.identity(),
            retired: vec![first.identity(), first.identity()],
        };

        assert!(matches!(
            history.reconcile::<SessionRole>(&second.identity()),
            Err(SigningIdentityError::WrongKeyId)
        ));
    }

    #[test]
    fn history_schema_rejects_unrecognized_fields() {
        let signer = SessionSigner::from_seed(7);
        let mut value =
            serde_json::to_value(SigningKeyHistory::current(&signer)).expect("history serializes");
        value
            .as_object_mut()
            .expect("history is an object")
            .insert("private_key".to_owned(), serde_json::json!("must-not-pass"));

        assert!(serde_json::from_value::<SigningKeyHistory>(value).is_err());
    }

    #[test]
    fn public_role_protocols_reject_the_same_key_under_the_wrong_role() {
        let turn_read = TurnReadSigner::from_seed(17);
        let journal: JournalAttestationSigner = turn_read.relabel_for_test();
        let turn_read_trust = RoleTrustSet::<TurnReadRole>::current(&turn_read);
        let journal_trust = RoleTrustSet::<JournalAttestationRole>::current(&journal);
        let canonical = b"same canonical bytes";
        let turn_read_signature = turn_read.sign_turn_read_capability(canonical);
        let journal_signature = journal.sign_journal_root(canonical);

        assert!(turn_read_trust.verify_turn_read_capability(
            turn_read.identity().key_id(),
            canonical,
            &turn_read_signature,
        ));
        assert!(journal_trust.verify_journal_root(
            journal.identity().key_id(),
            canonical,
            &journal_signature,
        ));
        assert!(!turn_read_trust.verify_turn_read_capability(
            turn_read.identity().key_id(),
            canonical,
            &journal_signature,
        ));
        assert!(!journal_trust.verify_journal_root(
            journal.identity().key_id(),
            canonical,
            &turn_read_signature,
        ));
    }

    #[test]
    fn signer_debug_never_prints_private_material() {
        let signer = SessionSigner::from_key_bytes(&[0x0cu8; 32]).expect("valid seed");
        let debug = format!("{signer:?}");
        assert!(debug.contains(SessionRole::ISSUER));
        assert!(!debug.contains("0c0c0c0c"));
    }

    #[test]
    fn native_smoke_bootstrap_vectors_are_stable() {
        fn assert_identity<R: SigningRole>(
            seed: u8,
            expected_public_key: &str,
            expected_key_id: &str,
        ) {
            let signer = RoleSigner::<R>::from_key_bytes(&[seed; 32]).expect("valid seed");
            assert_eq!(
                crate::hex::lower(&signer.public_key_bytes()),
                expected_public_key
            );
            assert_eq!(signer.identity().key_id(), expected_key_id);
        }

        assert_identity::<ApprovalRole>(
            0x0b,
            "66be7e332c7a453332bd9d0a7f7db055f5c5ef1a06ada66d98b39fb6810c473a",
            "3957902d0fa1c0870ea038f7a4b11e3285138f241eb25ca7461252ffa32302dd",
        );
        assert_identity::<SessionRole>(
            0x0c,
            "0b513ad9b4924015ca0902ed079044d3ac5dbec2306f06948c10da8eb6e39f2d",
            "b8123f51278253aa6f42d45c176c5dbcc28de411185c4c4cf3a37b09be8afacc",
        );
        assert_identity::<TurnReadRole>(
            0x0d,
            "91a28a0b74381593a4d9469579208926afc8ad82c8839b7644359b9eba9a4b3a",
            "5f9b2a2076cbde4a81150c4d8b164b95053f35bcaae5780310a2936590e44672",
        );
        assert_identity::<WebSessionGrantRole>(
            0x0e,
            "0beef5a9e679e6a3e134fe27837bff32c7cb5f5d44ea09bcb0e542bad6a4c0cc",
            "69650566262e58960bc2aa618913468aed27aa5e60d0badb3906935065ba63d6",
        );
        assert_identity::<JournalAttestationRole>(
            0x0f,
            "d9bf2148748a85c89da5aad8ee0b0fc2d105fd39d41a4c796536354f0ae2900c",
            "430dad21c1b44d5872905d82907089116378d6866bb7ac5858c96090d7314435",
        );
        assert_identity::<HandoffRole>(
            0x10,
            "5c9c6df261c9cb840475776aaefcd944b405328fab28f9b3a95ef40490d3de84",
            "c46c8e3f82b40e38adc7ad36620d22dd245cfe62a398b85b294ee9dd288abc7a",
        );
        assert_identity::<SubagentRole>(
            0x11,
            "d04ab232742bb4ab3a1368bd4615e4e6d0224ab71a016baf8520a332c9778737",
            "3eb64fb1252c81f8faa7fa15f4e5ecb4acf5b2dc119a3795d7576465dab22180",
        );
    }

    /// Every signed artifact kind must reject every other kind's signature.
    ///
    /// The matrix uses one private key relabeled into both roles. That removes
    /// key separation as the reason a cross-kind check fails, so only the
    /// artifact domain can carry the property.
    #[test]
    fn each_signed_artifact_kind_rejects_every_other_kind() {
        type Sign = fn(&HandoffSigner, &SubagentSigner, &[u8]) -> Vec<u8>;
        type Classify = fn(
            &RoleTrustSet<HandoffRole>,
            &RoleTrustSet<SubagentRole>,
            &[u8],
            &[u8],
            &[u8],
        ) -> SignatureVerdict;

        let handoff_signer = HandoffSigner::from_seed(31);
        let subagent_signer: SubagentSigner = handoff_signer.relabel_for_test();
        let handoff_trust = RoleTrustSet::<HandoffRole>::current(&handoff_signer);
        let subagent_trust = RoleTrustSet::<SubagentRole>::current(&subagent_signer);
        let canonical = b"identical canonical bytes";
        let kinds: [(&str, Sign, Classify); 4] = [
            (
                "handoff",
                |handoff, _, bytes| handoff.sign_handoff(bytes),
                |handoff, _, key, bytes, signature| handoff.classify_handoff(key, bytes, signature),
            ),
            (
                "handoff-denied",
                |handoff, _, bytes| handoff.sign_handoff_denied(bytes),
                |handoff, _, key, bytes, signature| {
                    handoff.classify_handoff_denied(key, bytes, signature)
                },
            ),
            (
                "subagent-spawn",
                |_, subagent, bytes| subagent.sign_subagent_spawn(bytes),
                |_, subagent, key, bytes, signature| {
                    subagent.classify_subagent_spawn(key, bytes, signature)
                },
            ),
            (
                "subagent-result",
                |_, subagent, bytes| subagent.sign_subagent_result(bytes),
                |_, subagent, key, bytes, signature| {
                    subagent.classify_subagent_result(key, bytes, signature)
                },
            ),
        ];

        let public_key = handoff_signer.public_key_bytes();
        for (source_name, sign, _) in &kinds {
            let signature = sign(&handoff_signer, &subagent_signer, canonical);
            for (target_name, _, classify) in &kinds {
                let verdict = classify(
                    &handoff_trust,
                    &subagent_trust,
                    &public_key,
                    canonical,
                    &signature,
                );
                let expected = if source_name == target_name {
                    SignatureVerdict::Verified
                } else {
                    SignatureVerdict::Invalid
                };
                assert_eq!(
                    verdict, expected,
                    "a {source_name} signature checked as {target_name}",
                );
            }
        }
    }

    #[test]
    fn a_signature_from_an_untrusted_key_classifies_as_untrusted() {
        let deployment = HandoffSigner::from_seed(41);
        let stranger = HandoffSigner::from_seed(42);
        let trust = RoleTrustSet::<HandoffRole>::current(&deployment);
        let canonical = b"handoff canonical bytes";

        assert_eq!(
            trust.classify_handoff(
                &deployment.public_key_bytes(),
                canonical,
                &deployment.sign_handoff(canonical),
            ),
            SignatureVerdict::Verified
        );
        assert_eq!(
            trust.classify_handoff(
                &stranger.public_key_bytes(),
                canonical,
                &stranger.sign_handoff(canonical),
            ),
            SignatureVerdict::Untrusted
        );
        assert_eq!(
            trust.classify_handoff(
                &deployment.public_key_bytes(),
                b"tampered canonical bytes",
                &deployment.sign_handoff(canonical),
            ),
            SignatureVerdict::Invalid
        );
    }

    #[test]
    fn a_retired_key_stays_trusted_for_its_role() {
        let current = SubagentSigner::from_seed(43);
        let retired = SubagentSigner::from_seed(44);
        let trust =
            RoleTrustSet::<SubagentRole>::checked(vec![current.identity(), retired.identity()])
                .expect("valid role history");
        let canonical = b"subagent result canonical bytes";

        for signer in [&current, &retired] {
            assert_eq!(
                trust.classify_subagent_result(
                    &signer.public_key_bytes(),
                    canonical,
                    &signer.sign_subagent_result(canonical),
                ),
                SignatureVerdict::Verified
            );
        }
    }

    #[test]
    fn a_malformed_embedded_key_classifies_as_invalid() {
        let signer = HandoffSigner::from_seed(45);
        let trust = RoleTrustSet::<HandoffRole>::current(&signer);
        let canonical = b"handoff canonical bytes";

        assert_eq!(
            trust.classify_handoff(b"not-a-key", canonical, &signer.sign_handoff(canonical)),
            SignatureVerdict::Invalid
        );
    }

    #[test]
    fn verdict_names_are_stable() {
        assert_eq!(SignatureVerdict::Verified.as_str(), "verified");
        assert_eq!(SignatureVerdict::Invalid.as_str(), "invalid");
        assert_eq!(SignatureVerdict::Untrusted.as_str(), "untrusted");
        assert_eq!(SignatureVerdict::Untrusted.to_string(), "untrusted");
    }
}