Skip to main content

acl_core/
lib.rs

1//! ACL — Agent Communication Language, core codec (spec v0.1).
2//!
3//! Implements L1–L4 of SPEC.md: MessagePack envelope, performatives,
4//! body variants, Ed25519 signing, AgentCard, stream framing.
5
6use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
7pub mod bridge;
8pub mod cl;
9pub mod batch;
10pub mod cnp;
11pub mod did;
12pub mod dialogue;
13pub mod idl;
14pub mod protocol;
15pub mod codegen;
16pub mod runtime;
17pub mod session;
18pub mod scenario;
19pub mod stdlib;
20pub mod schema;
21pub mod semantics;
22pub mod sealed;
23pub mod idempotency;
24pub mod registry;
25pub mod registry_protocols;
26pub mod replay;
27pub mod rdf;
28use serde::{Deserialize, Serialize};
29use serde_repr::{Deserialize_repr, Serialize_repr};
30use std::io::Read;
31
32pub const ACL_VERSION: u8 = 1;
33pub const MAX_HOP_COUNT: u8 = 8;
34pub const DEFAULT_TTL_MS: u32 = 300_000;
35
36// ---------------------------------------------------------------- performatives
37
38/// Speech acts (spec §5). Wire representation: u8 discriminant.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize_repr, Deserialize_repr)]
40#[repr(u8)]
41pub enum Performative {
42    Request = 1,
43    Inform = 2,
44    Query = 3,
45    Propose = 4,
46    Accept = 5,
47    Reject = 6,
48    Cancel = 7,
49    Progress = 8,
50    InputRequired = 9,
51    Failure = 10,
52    Delegate = 11,
53    Error = 12,
54    Hello = 13,
55    Bye = 14,
56    /// §32: retract a prior inform/fact (belief revision)
57    Retract = 15,
58    /// §32: ongoing interest in a predicate (push instead of poll)
59    Subscribe = 16,
60    /// §32: cancel a prior subscription
61    Unsubscribe = 17,
62}
63
64/// Artifact attached to a `Result` body.
65#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
66pub struct Artifact {
67    pub name: String,
68    pub mime: String,
69    /// Raw bytes, encoded as msgpack bin on the wire.
70    #[serde(with = "serde_bytes")]
71    pub bytes: Vec<u8>,
72}
73
74/// §32: structured error taxonomy — machine-actionable failure kinds.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum ErrorKind {
78    UnknownPredicate,
79    SchemaViolation,
80    MailboxFull,
81    RateLimited,
82    Unauthorized,
83    UnknownAgent,
84    DecodeFailed,
85    Expired,
86}
87
88/// Body variants (spec §6).
89#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
90#[serde(tag = "t", content = "v")]
91pub enum Body {
92    Task {
93        description: String,
94        input: serde_json::Value,
95        #[serde(skip_serializing_if = "Option::is_none")]
96        deadline_ms: Option<u32>,
97        #[serde(skip_serializing_if = "Option::is_none")]
98        priority: Option<u8>,
99    },
100    Result {
101        output: serde_json::Value,
102        #[serde(default)]
103        artifacts: Vec<Artifact>,
104    },
105    Text {
106        text: String,
107    },
108    Query {
109        subject: String,
110        #[serde(skip_serializing_if = "Option::is_none")]
111        parameters: Option<serde_json::Value>,
112    },
113    Proposal {
114        terms: serde_json::Value,
115        #[serde(skip_serializing_if = "Option::is_none")]
116        price: Option<String>,
117        #[serde(skip_serializing_if = "Option::is_none")]
118        valid_until: Option<i64>,
119    },
120    Ref {
121        target_msg_id: String,
122    },
123    Progress {
124        target_msg_id: String,
125        #[serde(skip_serializing_if = "Option::is_none")]
126        percent: Option<u8>,
127        #[serde(skip_serializing_if = "Option::is_none")]
128        note: Option<String>,
129    },
130    InputNeeded {
131        target_msg_id: String,
132        what: String,
133        #[serde(skip_serializing_if = "Option::is_none")]
134        schema: Option<serde_json::Value>,
135    },
136    Failure {
137        target_msg_id: String,
138        code: u16,
139        reason: String,
140        recoverable: bool,
141    },
142    Error {
143        code: u16,
144        message: String,
145        /// §32: machine-actionable failure kind (replaces string parsing)
146        #[serde(default, skip_serializing_if = "Option::is_none")]
147        taxonomy: Option<ErrorKind>,
148        #[serde(skip_serializing_if = "Option::is_none")]
149        details: Option<serde_json::Value>,
150    },
151    Hello {
152        agent_card: Option<AgentCard>,
153        card_hash: Option<String>,
154        nonce: Vec<u8>,
155    },
156    Delegate {
157        task: Box<Body>, // must be Body::Task
158        chain: Vec<String>,
159    },
160    /// §10.1: encrypted inner envelope (X25519 + ChaCha20-Poly1305)
161    Sealed {
162        sender_pub: Vec<u8>,
163        salt: Vec<u8>,
164        ciphertext: Vec<u8>,
165    },
166    /// §6.2: content-language expressions (shared grammar for
167    /// facts/actions/queries/commitments). Grammar matrix in cl::well_formed.
168    Cl {
169        expressions: Vec<crate::cl::ClExpr>,
170    },
171    /// §32: ongoing interest — watch a declarative matcher until `until_ms`.
172    #[serde(rename = "subscribe")]
173    Subscribe { watch: Box<crate::Matcher>, until_ms: Option<i64> },
174    /// §32: cancel a prior subscription.
175    #[serde(rename = "unsubscribe")]
176    Unsubscribe { target_msg_id: String },
177    /// §37: identity rotation — SIGNED BY THE OLD KEY, carries the new
178    /// did:key. Receivers update their registry; continuity is provable
179    /// because the rotation itself verifies under the old identity.
180    #[serde(rename = "key_rotation")]
181    KeyRotation {
182        new_did: String,
183        valid_from_ms: i64,
184        #[serde(default, skip_serializing_if = "Option::is_none")]
185        reason: Option<String>,
186    },
187}
188
189/// §32: declarative message matcher — the filter construct that
190/// subscriptions and routers share.
191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
192pub struct Matcher {
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub performative: Option<Performative>,
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub from: Option<String>,
197    /// predicate name the body must reference (fact/query/action/commitment)
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub predicate: Option<String>,
200}
201
202// ---------------------------------------------------------------- identity
203
204/// Agent ID (spec §4.1): `scheme:opaque`.
205#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
206pub struct Aid(pub String);
207
208impl Aid {
209    pub fn new(s: impl Into<String>) -> Self {
210        Aid(s.into())
211    }
212    pub fn scheme(&self) -> Option<&str> {
213        self.0.split(':').next()
214    }
215    pub fn local(pid: u32, session: &str) -> Self {
216        Aid(format!("local:{pid}:{session}"))
217    }
218}
219
220// ---------------------------------------------------------------- envelope
221
222/// The ACL envelope (spec §4). Field order is wire order.
223#[derive(Debug, Clone, Serialize, Deserialize)]
224pub struct Envelope {
225    pub acl: u8,
226    /// 128-bit id, hex-encoded (32 chars).
227    pub msg_id: String,
228    #[serde(skip_serializing_if = "Option::is_none")]
229    pub in_reply_to: Option<String>,
230    pub from: Aid,
231    pub to: Aid,
232    /// unix milliseconds UTC
233    pub ts: i64,
234    #[serde(default = "default_ttl")]
235    pub ttl: u32,
236    #[serde(skip_serializing_if = "Option::is_none")]
237    pub reply_with: Option<String>,
238    #[serde(default, skip_serializing_if = "is_zero")]
239    pub hop_count: u8,
240    pub performative: Performative,
241    pub body: Body,
242    /// Ed25519 signature over the encoded envelope with `sig` absent.
243    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_serde_bytes")]
244    pub sig: Option<Vec<u8>>,
245    /// §30: what the sender EXPECTS to happen in the world if the message
246    /// is honoured (rational effect). Machine-checkable against the
247    /// sender's declared semantics.
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub rational_effect: Option<String>,
250    /// §30: what must have been true of the sender for this message to be
251    /// sincere (feasibility precondition).
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub feasibility_precondition: Option<String>,
254}
255
256fn default_ttl() -> u32 {
257    DEFAULT_TTL_MS
258}
259
260fn is_zero(v: &u8) -> bool {
261    *v == 0
262}
263
264/// Generate a random 128-bit hex msg_id.
265pub fn new_msg_id() -> String {
266    use rand::Rng;
267    let mut b = [0u8; 16];
268    rand::rng().fill_bytes(&mut b);
269    hex(&b)
270}
271
272fn hex(b: &[u8]) -> String {
273    b.iter().map(|x| format!("{x:02x}")).collect()
274}
275
276mod opt_serde_bytes {
277    use serde::{Deserializer, Serializer};
278
279    pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
280        match v {
281            Some(b) => serde_bytes::serialize(b, s),
282            None => s.serialize_none(),
283        }
284    }
285    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
286        let opt: Option<serde_bytes::ByteBuf> = serde_bytes::deserialize(d)?;
287        Ok(opt.map(|b| b.into_vec()))
288    }
289}
290
291impl Envelope {
292    pub fn new(from: Aid, to: Aid, performative: Performative, body: Body) -> Self {
293        Envelope {
294            acl: ACL_VERSION,
295            msg_id: new_msg_id(),
296            in_reply_to: None,
297            from,
298            to,
299            ts: now_ms(),
300            ttl: DEFAULT_TTL_MS,
301            reply_with: None,
302            hop_count: 0,
303            performative,
304            body,
305            sig: None,
306            rational_effect: None,
307            feasibility_precondition: None,
308        }
309    }
310
311    /// §30: declare the intent pair (FP/RE) on this envelope.
312    pub fn with_intent(mut self, fp: &str, re: &str) -> Self {
313        self.feasibility_precondition = Some(fp.into());
314        self.rational_effect = Some(re.into());
315        self
316    }
317
318    /// Serialize the unsigned envelope (what the signature covers).
319    pub fn encode_unsigned(&self) -> Result<Vec<u8>, AclError> {
320        let mut copy = self.clone();
321        copy.sig = None;
322        rmp_serde::to_vec_named(&copy).map_err(AclError::Encode)
323    }
324
325    /// Full wire encoding.
326    pub fn encode(&self) -> Result<Vec<u8>, AclError> {
327        rmp_serde::to_vec_named(self).map_err(AclError::Encode)
328    }
329
330    pub fn decode(bytes: &[u8]) -> Result<Self, AclError> {
331        let env: Envelope = rmp_serde::from_slice(bytes).map_err(AclError::Decode)?;
332        if env.acl != ACL_VERSION {
333            return Err(AclError::Version(env.acl));
334        }
335        Ok(env)
336    }
337
338    /// Sign with an Ed25519 key. `sig` covers the envelope without `sig`.
339    pub fn sign(&mut self, key: &SigningKey) -> Result<(), AclError> {
340        let unsigned = self.encode_unsigned()?;
341        self.sig = Some(key.sign(&unsigned).to_bytes().to_vec());
342        Ok(())
343    }
344
345    /// Verify the signature against a public key.
346    pub fn verify(&self, vk: &VerifyingKey) -> Result<bool, AclError> {
347        let Some(sig_bytes) = self.sig.clone() else {
348            return Ok(false);
349        };
350        let sig = Signature::from_bytes(
351            <&[u8; 64]>::try_from(&sig_bytes[..]).map_err(|_| AclError::BadKey)?,
352        );
353        let unsigned = self.encode_unsigned()?;
354        Ok(vk.verify(&unsigned, &sig).is_ok())
355    }
356
357    pub fn is_expired(&self, now_ms: i64) -> bool {
358        now_ms.saturating_sub(self.ts) > self.ttl as i64
359    }
360}
361
362fn now_ms() -> i64 {
363    std::time::SystemTime::now()
364        .duration_since(std::time::UNIX_EPOCH)
365        .map(|d| d.as_millis() as i64)
366        .unwrap_or(0)
367}
368
369// ---------------------------------------------------------------- agent card
370
371/// Signed capability descriptor (spec §7).
372#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
373pub struct AgentCard {
374    pub name: String,
375    pub version: String,
376    pub description: String,
377    pub endpoint: Aid,
378    pub capabilities: Vec<Capability>,
379    pub auth_scheme: String, // "ed25519" | "none"
380    #[serde(skip_serializing_if = "Option::is_none")]
381    pub key_id: Option<String>,
382    /// Ed25519 public key (32 bytes) when auth_scheme == "ed25519".
383    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_serde_bytes")]
384    pub public_key: Option<Vec<u8>>,
385    #[serde(skip_serializing_if = "Option::is_none")]
386    pub rate_hint: Option<u32>,
387    #[serde(skip_serializing_if = "Option::is_none")]
388    pub valid_until: Option<i64>,
389    /// Signature of the card by its own key (covers all fields above).
390    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_serde_bytes")]
391    pub sig: Option<Vec<u8>>,
392}
393
394#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
395pub struct Capability {
396    pub name: String,
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub input_schema: Option<serde_json::Value>,
399    #[serde(skip_serializing_if = "Option::is_none")]
400    pub output_schema: Option<serde_json::Value>,
401    #[serde(skip_serializing_if = "Option::is_none")]
402    pub examples: Option<Vec<String>>,
403}
404
405impl AgentCard {
406    pub fn encode_unsigned(&self) -> Result<Vec<u8>, AclError> {
407        let mut copy = self.clone();
408        copy.sig = None;
409        rmp_serde::to_vec_named(&copy).map_err(AclError::Encode)
410    }
411
412    pub fn sign(&mut self, key: &SigningKey) -> Result<(), AclError> {
413        self.public_key = Some(key.verifying_key().to_bytes().to_vec());
414        let unsigned = self.encode_unsigned()?;
415        self.sig = Some(key.sign(&unsigned).to_bytes().to_vec());
416        Ok(())
417    }
418
419    pub fn verify(&self) -> Result<bool, AclError> {
420        let (Some(sig_bytes), Some(pk)) = (self.sig.clone(), self.public_key.clone()) else {
421            return Ok(false);
422        };
423        let vk = VerifyingKey::from_bytes(
424            <&[u8; 32]>::try_from(&pk[..]).map_err(|_| AclError::BadKey)?,
425        )
426        .map_err(|_| AclError::BadKey)?;
427        let sig = Signature::from_bytes(
428            <&[u8; 64]>::try_from(&sig_bytes[..]).map_err(|_| AclError::BadKey)?,
429        );
430        Ok(vk.verify(&self.encode_unsigned()?, &sig).is_ok())
431    }
432}
433
434// ---------------------------------------------------------------- framing
435
436/// Length-prefixed stream framing (spec §3): 4-byte BE length + payload.
437/// Reads one framed message; returns Ok(None) on EOF at a frame boundary.
438pub fn read_frame<R: Read>(mut r: R) -> std::io::Result<Option<Vec<u8>>> {
439    let mut len_buf = [0u8; 4];
440    match r.read_exact(&mut len_buf) {
441        Ok(()) => {}
442        Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
443        Err(e) => return Err(e),
444    }
445    let len = u32::from_be_bytes(len_buf) as usize;
446    if len > 16 * 1024 * 1024 {
447        return Err(std::io::Error::new(
448            std::io::ErrorKind::InvalidData,
449            "frame too large",
450        ));
451    }
452    let mut buf = vec![0u8; len];
453    r.read_exact(&mut buf)?;
454    Ok(Some(buf))
455}
456
457pub fn write_frame(buf: &mut Vec<u8>, payload: &[u8]) {
458    buf.extend_from_slice(&(payload.len() as u32).to_be_bytes());
459    buf.extend_from_slice(payload);
460}
461
462// ---------------------------------------------------------------- errors
463
464#[derive(Debug)]
465pub enum AclError {
466    Encode(rmp_serde::encode::Error),
467    Decode(rmp_serde::decode::Error),
468    Version(u8),
469    BadKey,
470}
471
472impl std::fmt::Display for AclError {
473    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474        match self {
475            AclError::Encode(e) => write!(f, "encode: {e}"),
476            AclError::Decode(e) => write!(f, "decode: {e}"),
477            AclError::Version(v) => write!(f, "unsupported ACL version {v}"),
478            AclError::BadKey => write!(f, "bad ed25519 key"),
479        }
480    }
481}
482impl std::error::Error for AclError {}
483
484// ---------------------------------------------------------------- tests
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489    use rand::Rng;
490
491    fn key() -> SigningKey {
492        let mut seed = [0u8; 32];
493        rand::rng().fill_bytes(&mut seed);
494        SigningKey::from_bytes(&seed)
495    }
496
497    fn sample() -> Envelope {
498        Envelope::new(
499            Aid::local(4211, "a1"),
500            Aid::new("did:example:agent-b"),
501            Performative::Request,
502            Body::Task {
503                description: "summarize report".into(),
504                input: serde_json::json!({"file": "q3.pdf", "lang": "pt"}),
505                deadline_ms: Some(60_000),
506                priority: Some(5),
507            },
508        )
509    }
510
511    #[test]
512    fn roundtrip_all_performatives() {
513        let bodies = vec![
514            (Performative::Request, Body::Task { description: "t".into(), input: serde_json::json!({"x": 1}), deadline_ms: None, priority: None }),
515            (Performative::Inform, Body::Result { output: serde_json::json!("done"), artifacts: vec![Artifact { name: "a.txt".into(), mime: "text/plain".into(), bytes: b"hi".to_vec() }] }),
516            (Performative::Inform, Body::Text { text: "hello".into() }),
517            (Performative::Query, Body::Query { subject: "agent.card".into(), parameters: None }),
518            (Performative::Propose, Body::Proposal { terms: serde_json::json!({"split": "50/50"}), price: Some("2 credits".into()), valid_until: None }),
519            (Performative::Accept, Body::Ref { target_msg_id: "abc".into() }),
520            (Performative::Reject, Body::Ref { target_msg_id: "abc".into() }),
521            (Performative::Cancel, Body::Ref { target_msg_id: "abc".into() }),
522            (Performative::Progress, Body::Progress { target_msg_id: "abc".into(), percent: Some(50), note: Some("halfway".into()) }),
523            (Performative::InputRequired, Body::InputNeeded { target_msg_id: "abc".into(), what: "missing column".into(), schema: None }),
524            (Performative::Failure, Body::Failure { target_msg_id: "abc".into(), code: 500, reason: "no data".into(), recoverable: false }),
525            (Performative::Error, Body::Error {
526 code: 400, message: "bad".into(), taxonomy: None, details: None }),
527            (Performative::Hello, Body::Hello { agent_card: None, card_hash: None, nonce: vec![7u8; 16] }),
528            (Performative::Bye, Body::Ref { target_msg_id: "abc".into() }),
529            (Performative::Delegate, Body::Delegate { task: Box::new(Body::Task { description: "sub".into(), input: serde_json::json!(null), deadline_ms: None, priority: None }), chain: vec!["did:example:a".into(), "did:example:b".into()] }),
530        ];
531        for (perf, body) in bodies {
532            let env = Envelope::new(Aid::local(1, "s"), Aid::new("did:x:y"), perf, body);
533            let bytes = env.encode().expect("encode");
534            let back = Envelope::decode(&bytes).expect("decode");
535            assert_eq!(back.performative, perf);
536            assert_eq!(back.msg_id, env.msg_id);
537        }
538    }
539
540    #[test]
541    fn sign_verify() {
542        let key = key();
543        let mut env = sample();
544        env.sign(&key).unwrap();
545        assert!(env.verify(&key.verifying_key()).unwrap());
546        // tamper: change field → verify must fail
547        env.ttl = 1;
548        assert!(!env.verify(&key.verifying_key()).unwrap());
549    }
550
551    #[test]
552    fn wrong_key_fails() {
553        let mut env = sample();
554        env.sign(&key()).unwrap();
555        assert!(!env.verify(&key().verifying_key()).unwrap());
556    }
557
558    #[test]
559    fn framing_roundtrip() {
560        let env = sample();
561        let payload = env.encode().unwrap();
562        let mut stream = Vec::new();
563        write_frame(&mut stream, &payload);
564        write_frame(&mut stream, &payload);
565        let mut cursor = &stream[..];
566        let f1 = read_frame(&mut cursor).unwrap().unwrap();
567        let f2 = read_frame(&mut cursor).unwrap().unwrap();
568        let eof = read_frame(&mut cursor).unwrap();
569        assert_eq!(f1, payload);
570        assert_eq!(f2, payload);
571        assert!(eof.is_none());
572    }
573
574    #[test]
575    fn agent_card_sign_verify() {
576        let key = key();
577        let mut card = AgentCard {
578            name: "argus".into(),
579            version: "1.0".into(),
580            description: "watchdog agent".into(),
581            endpoint: Aid::local(4211, "a1"),
582            capabilities: vec![Capability {
583                name: "log.watch".into(),
584                input_schema: None,
585                output_schema: None,
586                examples: None,
587            }],
588            auth_scheme: "ed25519".into(),
589            key_id: None,
590            public_key: None,
591            rate_hint: Some(60),
592            valid_until: None,
593            sig: None,
594        };
595        card.sign(&key).unwrap();
596        assert!(card.verify().unwrap());
597        card.name = "tampered".into();
598        assert!(!card.verify().unwrap());
599    }
600
601    #[test]
602    fn compactness() {
603        let env = sample();
604        let mp = env.encode().unwrap();
605        let js = serde_json::to_vec(&env).unwrap();
606        println!("msgpack {} bytes vs json {} bytes", mp.len(), js.len());
607        assert!(mp.len() < js.len());
608    }
609}
610
611
612/// §37: identity rotation — build a rotation statement signed by the OLD
613/// key. Continuity is provable: the message verifies under the old
614/// did:key and announces the new one; receivers update their registries.
615pub fn rotate_identity(
616    from: &Aid,
617    old_key: &ed25519_dalek::SigningKey,
618    new_key: &ed25519_dalek::SigningKey,
619    reason: Option<&str>,
620    now_ms: i64,
621) -> Result<Envelope, AclError> {
622    let new_did = crate::did::verifying_key_to_did_key(&new_key.verifying_key());
623    let mut env = Envelope::new(
624        from.clone(),
625        Aid::new("local:registry:identity"),
626        Performative::Inform,
627        Body::KeyRotation {
628            new_did: new_did.to_string(),
629            valid_from_ms: now_ms,
630            reason: reason.map(|r| r.to_string()),
631        },
632    );
633    env.msg_id = new_msg_id();
634    env.ts = now_ms;
635    env.sign(old_key)?;
636    Ok(env)
637}
638
639
640#[cfg(test)]
641mod rotation_tests {
642    use super::*;
643    use ed25519_dalek::SigningKey;
644    use rand::Rng;
645
646    #[test]
647    fn key_rotation_verifies_with_old_key_and_announces_new_did() {
648        let mut old_seed = [0u8; 32];
649        rand::rng().fill_bytes(&mut old_seed);
650        let mut new_seed = [0u8; 32];
651        rand::rng().fill_bytes(&mut new_seed);
652        let old_key = SigningKey::from_bytes(&old_seed);
653        let new_key = SigningKey::from_bytes(&new_seed);
654
655        let from = Aid::new("did:key:z6old");
656        let env = rotate_identity(&from, &old_key, &new_key, Some("scheduled rotation"), 1_700_000_000_000)
657            .expect("rotation envelope");
658
659        // 1. verifies under the OLD key (continuity proof)
660        env.verify(&old_key.verifying_key()).expect("rotation must verify with old key");
661        // 2. carries the NEW did:key
662        match &env.body {
663            Body::KeyRotation { new_did, .. } => {
664                let expected = crate::did::verifying_key_to_did_key(&new_key.verifying_key());
665                assert_eq!(new_did, &expected);
666            }
667            other => panic!("expected KeyRotation, got {other:?}"),
668        }
669        // 3. roundtrip on the wire
670        let decoded = Envelope::decode(&env.encode().unwrap()).unwrap();
671        decoded.verify(&old_key.verifying_key()).unwrap();
672    }
673}