Skip to main content

vouch_core/
robotics.rs

1//! Robotics primitives (Phase 5), one byte-exact implementation in the core.
2//!
3//! Mirrors the Python `vouch.robotics` package and the TypeScript/Go SDKs so that
4//! a robotics credential built in any language verifies in every other. Exposing
5//! this module through the UniFFI and WASM wrappers gives Swift, Kotlin/JVM,
6//! .NET, C/C++, and the browser the same robotics surface without re-deriving it.
7//!
8//! This file covers hardware-rooted robot identity (Phase 5.1). The remaining
9//! capabilities (provenance, capability scope, handshake, black box, passport)
10//! are added alongside it.
11//!
12//! Design: the core is hardware-agnostic and deterministic. A robot self-issues
13//! its `RobotIdentityCredential` with its own Ed25519 key; the hardware root (a
14//! TPM, secure element, or a software root in development) signs a binding over
15//! the robot DID and key, supplied to [`mint_robot_identity`] as the attestation
16//! bytes. Timestamps are caller-supplied, matching the rest of the core, so the
17//! output is reproducible and the wrappers control the clock.
18
19#[allow(unused_imports)]
20use crate::prelude::*;
21
22use serde_json::{json, Map, Value};
23
24use crate::data_integrity::{self, BuildProofOptions};
25use crate::error::{CoreError, Result};
26use crate::keys;
27use crate::pq::{MlDsa44KeyPair, MLDSA44_PUBLIC_LEN};
28use crate::robotics_verify::{self as rv, Keys, VerifyOptions, Window};
29use crate::root_of_trust::{self, ACTION_ISSUE_ROBOT_IDENTITY};
30use crate::{hybrid, jcs, multikey};
31
32use crate::collections::HashSet;
33use aes_gcm::aead::{Aead, Payload};
34use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
35use base64::engine::general_purpose::URL_SAFE_NO_PAD;
36use base64::Engine;
37use sha2::{Digest, Sha256};
38
39pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
40pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
41pub const ROBOT_IDENTITY_TYPE: &str = "RobotIdentityCredential";
42
43/// Multibase ('u') base64url-no-pad encoding, matching the Python/TS/Go `mb64`.
44pub(crate) fn mb64(bytes: &[u8]) -> String {
45    format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
46}
47
48/// Decode a multibase ('u') base64url-no-pad string.
49pub(crate) fn unmb64(s: &str) -> Result<Vec<u8>> {
50    let body = s
51        .strip_prefix('u')
52        .ok_or_else(|| CoreError::Json("expected multibase 'u' prefix".into()))?;
53    URL_SAFE_NO_PAD
54        .decode(body)
55        .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))
56}
57
58/// The canonical bytes a hardware root signs to bind a robot's identity key to
59/// its hardware: JCS of `{"key": robot_key_multibase, "robotDid": robot_did}`.
60pub fn robot_identity_binding(robot_did: &str, robot_key_multibase: &str) -> Vec<u8> {
61    jcs::canonicalize(&json!({
62        "key": robot_key_multibase,
63        "robotDid": robot_did,
64    }))
65}
66
67/// Parameters for [`mint_robot_identity`]. Timestamps are ISO-8601 strings the
68/// caller supplies. `attestation` is the hardware root's signature over
69/// [`robot_identity_binding`]; `root_public_multibase` is that root's public key.
70#[derive(Debug, Clone)]
71pub struct MintRobotIdentity {
72    pub robot_did: String,
73    pub make: String,
74    pub model: String,
75    pub serial: String,
76    pub owner: Option<String>,
77    pub root_kind: String,
78    pub root_public_multibase: String,
79    pub attestation: Vec<u8>,
80    /// Optional explicit lifecycle array; defaults to a single "commissioned" entry.
81    pub lifecycle: Option<Value>,
82    pub valid_from: String,
83    pub valid_until: Option<String>,
84}
85
86/// Mint a hardware-attested `RobotIdentityCredential`, signed by the robot's own
87/// Ed25519 seed. The hardware-root attestation is embedded as
88/// `credentialSubject.hardwareRoot.attestation`.
89pub fn mint_robot_identity(robot_seed: &[u8], params: &MintRobotIdentity) -> Result<Value> {
90    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
91    let lifecycle = params
92        .lifecycle
93        .clone()
94        .unwrap_or_else(|| json!([{ "event": "commissioned", "timestamp": params.valid_from }]));
95
96    let mut subject = Map::new();
97    subject.insert("id".into(), json!(params.robot_did));
98    subject.insert("make".into(), json!(params.make));
99    subject.insert("model".into(), json!(params.model));
100    subject.insert("serial".into(), json!(params.serial));
101    subject.insert(
102        "hardwareRoot".into(),
103        json!({
104            "kind": params.root_kind,
105            "publicKeyMultibase": params.root_public_multibase,
106            "attestation": mb64(&params.attestation),
107        }),
108    );
109    subject.insert("lifecycle".into(), lifecycle);
110    if let Some(owner) = &params.owner {
111        subject.insert("owner".into(), json!(owner));
112    }
113
114    let mut cred = Map::new();
115    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
116    cred.insert(
117        "type".into(),
118        json!(["VerifiableCredential", ROBOT_IDENTITY_TYPE]),
119    );
120    cred.insert("issuer".into(), json!(params.robot_did));
121    cred.insert("validFrom".into(), json!(params.valid_from));
122    cred.insert("credentialSubject".into(), Value::Object(subject));
123    // After the subject, as the reference writes it (the shared vectors keep
124    // that member order; JCS signing does not depend on it).
125    if let Some(vu) = &params.valid_until {
126        cred.insert("validUntil".into(), json!(vu));
127    }
128
129    let opts = BuildProofOptions::new(
130        crate::verification_method::ed25519_method(&params.robot_did),
131        params.valid_from.clone(),
132    );
133    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
134}
135
136/// Verify a credential through the shared issuer-binding helper
137/// ([`crate::robotics_verify`]) at `now_iso`. Errors only on a malformed
138/// `now_iso`; any problem with the credential itself is `Ok(None)`.
139pub(crate) fn bound(
140    credential: &Value,
141    keys: Keys<'_>,
142    expected_type: &str,
143    now_iso: &str,
144    window: Window,
145) -> Result<Option<rv::Verified>> {
146    let now = rv::require_now(now_iso)?;
147    Ok(rv::verify_robotics_credential(
148        credential,
149        keys,
150        Some(expected_type),
151        now,
152        VerifyOptions::window(window),
153    )
154    .ok())
155}
156
157/// True when a self-attestation names its issuer as `credentialSubject.id`.
158pub(crate) fn issuer_is_subject(v: &rv::Verified) -> bool {
159    v.subject.get("id").and_then(|x| x.as_str()) == Some(v.issuer.as_str())
160}
161
162/// Verify a `RobotIdentityCredential`: the credential proof bound to the robot
163/// as issuer (which must also be `credentialSubject.id`), the validity window
164/// at `now_iso` (validFrom required), AND the hardware-root attestation binding
165/// the robot key to the hardware. `robot_keys` is a `{robot_did: key}` source
166/// (or, for a did:key robot, the bare key). When `hardware_root_key` is given,
167/// the credential's hardware-root key must be exactly that key. Returns the
168/// credentialSubject on success, `None` if invalid.
169pub fn verify_robot_identity(
170    credential: &Value,
171    robot_keys: Keys<'_>,
172    hardware_root_key: Option<&[u8]>,
173    now_iso: &str,
174) -> Result<Option<Value>> {
175    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
176    let v = match bound(
177        credential,
178        robot_keys,
179        ROBOT_IDENTITY_TYPE,
180        now_iso,
181        Window::FromRequired,
182    )? {
183        Some(v) if issuer_is_subject(&v) => v,
184        _ => return Ok(None),
185    };
186    let robot_key =
187        match rv::resolve_issuer_key(&v.issuer, rv::pin_if_keyless(robot_keys, Some(&v.issuer))) {
188            Ok(k) => k,
189            Err(_) => return Ok(None),
190        };
191    let subject = match v.subject.as_object() {
192        Some(s) => s,
193        None => return Ok(None),
194    };
195    let hw = match subject.get("hardwareRoot").and_then(|h| h.as_object()) {
196        Some(h) => h,
197        None => return Ok(None),
198    };
199    let hw_mb = match hw.get("publicKeyMultibase").and_then(|v| v.as_str()) {
200        Some(s) => s,
201        None => return Ok(None),
202    };
203    let attestation_mb = match hw.get("attestation").and_then(|v| v.as_str()) {
204        Some(s) => s,
205        None => return Ok(None),
206    };
207
208    let decoded = match multikey::decode(hw_mb) {
209        Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => d,
210        _ => return Ok(None),
211    };
212    if let Some(pin) = hardware_root_key {
213        if pin != decoded.raw_key.as_slice() {
214            return Ok(None);
215        }
216    }
217    let attestation = match unmb64(attestation_mb) {
218        Ok(a) => a,
219        Err(_) => return Ok(None),
220    };
221
222    let robot_key_mb = multikey::encode_ed25519_public(&robot_key)?;
223    let binding = robot_identity_binding(&v.issuer, &robot_key_mb);
224
225    if !matches!(
226        keys::verify(&decoded.raw_key, &binding, &attestation),
227        Ok(true)
228    ) {
229        return Ok(None);
230    }
231    Ok(Some(v.subject))
232}
233
234// ---------------------------------------------------------------------------
235// Root of Trust for robot identity (Phase 5.1, authority binding)
236// ---------------------------------------------------------------------------
237//
238// Byte-exact port of the Python reference `vouch/robotics/root_identity.py`.
239//
240// The Root of Trust for Machine Identity lets one pinned Vouch root recognize
241// issuers, and a recognized issuer bind a subject DID to attributes, verified
242// offline against that one pinned root. This extends it to robots. A recognized
243// manufacturer (an issuer the root granted the `issueRobotIdentity` action)
244// issues an identity that binds a robot's DID and its hardware-rooted key to
245// attributes such as make, model, serial, and owner. The robot separately holds
246// a hardware-attested `RobotIdentityCredential` proving its key is bound to a
247// secure element.
248//
249// [`verify_robot_identity_chain`] closes the loop: from one pinned root a
250// verifier confirms both that the robot is a legitimate robot from a recognized
251// manufacturer (the authority chain via [`root_of_trust::verify_identity_chain`])
252// and that the key the manufacturer vouched for is genuinely hardware-rooted (the
253// secure-element attestation via [`verify_robot_identity`]), and that the two
254// name the same robot and the same key. It follows the anchor-once model and the
255// reason-code style of the underlying root_of_trust.
256
257/// Outcome of [`verify_robot_identity_chain`].
258///
259/// `ok` is true only if the authority chain verified against the pinned root AND
260/// the robot's own credential names the same robot and the vouched key.
261/// `hardware_rooted` is true only when the manufacturer also bound the
262/// hardware-root key and the attestation was made by exactly that key. On failure `reason`
263/// carries a structured code matching the Python reference exactly.
264#[derive(Debug, Clone, PartialEq, Eq)]
265pub struct RobotIdentityChainResult {
266    pub ok: bool,
267    pub reason: Option<String>,
268    pub robot_did: Option<String>,
269    pub issuer_did: Option<String>,
270    pub root_did: Option<String>,
271    pub attributes: Option<Value>,
272    pub hardware_rooted: bool,
273}
274
275impl RobotIdentityChainResult {
276    /// A failure result carrying the reason code and the pinned root that was in
277    /// force when the check failed.
278    fn fail(reason: impl Into<String>, root_did: &str) -> Self {
279        Self {
280            ok: false,
281            reason: Some(reason.into()),
282            robot_did: None,
283            issuer_did: None,
284            root_did: Some(root_did.to_string()),
285            attributes: None,
286            hardware_rooted: false,
287        }
288    }
289}
290
291/// Issue an authority robot identity: a recognized manufacturer binds `robot_did`,
292/// its hardware-rooted key (`hardware_key_multibase`, the robot's Ed25519 key as a
293/// multikey), and identity `attributes` (make, model, serial, owner). The
294/// manufacturer (derived from `issuer_seed`) must be a recognized issuer for the
295/// `issueRobotIdentity` action.
296///
297/// The credential is an `AgentIdentityCredential` so the shared identity-chain
298/// verification applies, with a `kind` of "robot" and the hardware key carried in
299/// the bound identity attributes.
300///
301/// `hardware_root_key_multibase` is the public key of the robot's secure element
302/// as the manufacturer recorded it. Bound as `hardwareRootKey`, it lets a
303/// verifier tell the robot's hardware attestation comes from that exact
304/// hardware; without it the chain verifies but is never hardware-rooted.
305#[allow(clippy::too_many_arguments)]
306pub fn build_robot_identity(
307    issuer_seed: &[u8],
308    robot_did: &str,
309    hardware_key_multibase: &str,
310    attributes: &Value,
311    valid_seconds: i64,
312    valid_from: &str,
313    created: &str,
314    credential_status: Option<Value>,
315    credential_id: &str,
316    hardware_root_key_multibase: Option<&str>,
317) -> Result<Value> {
318    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attributes; drop credential_status);
319    if robot_did.is_empty() {
320        return Err(CoreError::Json("robot_did is required".into()));
321    }
322    if hardware_key_multibase.is_empty() {
323        return Err(CoreError::Json("hardware_key_multibase is required".into()));
324    }
325    let bound = match attributes.as_object() {
326        Some(o) if !o.is_empty() => {
327            let mut m = o.clone();
328            m.insert("kind".into(), json!("robot"));
329            m.insert("hardwareKey".into(), json!(hardware_key_multibase));
330            if let Some(root) = hardware_root_key_multibase {
331                if root.is_empty() {
332                    return Err(CoreError::Json(
333                        "hardware_root_key_multibase must be a multikey string".into(),
334                    ));
335                }
336                m.insert("hardwareRootKey".into(), json!(root));
337            }
338            Value::Object(m)
339        }
340        _ => {
341            return Err(CoreError::Json(
342                "attributes must be a non-empty object".into(),
343            ))
344        }
345    };
346    root_of_trust::build_agent_identity(
347        issuer_seed,
348        robot_did,
349        &bound,
350        valid_seconds,
351        valid_from,
352        created,
353        credential_status,
354        credential_id,
355    )
356}
357
358/// Verify a robot's identity against a single pinned Vouch root, confirming both
359/// provenance and hardware-rooting.
360///
361/// From `trusted_root`, the pinned root DID:
362///
363///   1. The authority chain: the recognized manufacturer must be recognized by
364///      the pinned root for the `issueRobotIdentity` action, and the authority
365///      identity must be signed by that manufacturer (shared identity-chain verify).
366///   2. The vouched key: the authority identity must carry a hardware key.
367///   3. The robot credential: the robot's own `RobotIdentityCredential` must
368///      verify under the key the manufacturer vouched for, name the same robot,
369///      and carry a valid secure-element attestation.
370///   4. The hardware root: when the manufacturer bound a `hardwareRootKey`, the
371///      attestation's hardware key must be exactly that key (else
372///      `hardware_root_mismatch`), and only then is `hardware_rooted` true.
373///
374/// `robot_public_key` is the robot's raw 32-byte Ed25519 public key. `now_iso` is
375/// the current instant used for the temporal window; `clock_skew_seconds` is the
376/// allowed drift. Reason codes on failure match the Python reference exactly.
377#[allow(clippy::too_many_arguments)]
378pub fn verify_robot_identity_chain(
379    authority_identity: &Value,
380    recognized_issuer_credential: &Value,
381    robot_hardware_credential: &Value,
382    trusted_root: &str,
383    robot_public_key: &[u8],
384    root_credential: Option<&Value>,
385    now_iso: &str,
386    clock_skew_seconds: i64,
387) -> RobotIdentityChainResult {
388    crate::nesting::deep_guard!(RobotIdentityChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()), robot_did: None, issuer_did: None, root_did: None, attributes: None, hardware_rooted: false }; authority_identity, recognized_issuer_credential, robot_hardware_credential, root_credential);
389    let chain = root_of_trust::verify_identity_chain(
390        authority_identity,
391        recognized_issuer_credential,
392        trusted_root,
393        root_credential,
394        None,
395        ACTION_ISSUE_ROBOT_IDENTITY,
396        now_iso,
397        clock_skew_seconds,
398    );
399    robot_identity_chain_tail(
400        chain,
401        robot_hardware_credential,
402        trusted_root,
403        robot_public_key,
404        now_iso,
405    )
406}
407
408/// The robot half of [`verify_robot_identity_chain`], after the authority
409/// chain (`chain`, walked for `issueRobotIdentity`): the vouched hardware key,
410/// the robot's own credential under `robot_public_key`, its subject and key,
411/// and the hardware root.
412pub fn robot_identity_chain_tail(
413    chain: root_of_trust::IdentityChainResult,
414    robot_hardware_credential: &Value,
415    trusted_root: &str,
416    robot_public_key: &[u8],
417    now_iso: &str,
418) -> RobotIdentityChainResult {
419    // `chain` is the caller's and is dropped here: a deep `attributes` is
420    // taken apart without recursion before the refusal.
421    if crate::nesting::too_deep_here(robot_hardware_credential)
422        || crate::nesting::too_deep_here(&chain.attributes)
423    {
424        if let Some(attributes) = chain.attributes {
425            crate::nesting::drop_flat(attributes);
426        }
427        return RobotIdentityChainResult::fail(crate::nesting::TOO_DEEP, trusted_root);
428    }
429    if !chain.ok {
430        return RobotIdentityChainResult {
431            ok: false,
432            reason: chain.reason,
433            robot_did: None,
434            issuer_did: None,
435            root_did: Some(trusted_root.to_string()),
436            attributes: None,
437            hardware_rooted: false,
438        };
439    }
440
441    let attributes = match &chain.attributes {
442        Some(v @ Value::Object(_)) => v.clone(),
443        _ => json!({}),
444    };
445    let hardware_key = match attributes.get("hardwareKey").and_then(|v| v.as_str()) {
446        Some(s) if !s.is_empty() => s.to_string(),
447        _ => return RobotIdentityChainResult::fail("identity_no_hardware_key", trusted_root),
448    };
449
450    // The robot's own credential must verify under the supplied key, accepted
451    // for whatever DID the credential names; the next two checks pin that DID
452    // to the manufacturer's subject and the key to the vouched key.
453    let any_did = |_: &str| Some(robot_public_key.to_vec());
454    let hw_subject = match verify_robot_identity(
455        robot_hardware_credential,
456        Keys::Resolver(&any_did),
457        None,
458        now_iso,
459    ) {
460        Ok(Some(s)) => s,
461        _ => return RobotIdentityChainResult::fail("hardware_root_invalid", trusted_root),
462    };
463    if hw_subject.get("id").and_then(|v| v.as_str()) != chain.agent_did.as_deref() {
464        return RobotIdentityChainResult::fail("hardware_subject_mismatch", trusted_root);
465    }
466
467    let robot_key_mb = match multikey::encode_ed25519_public(robot_public_key) {
468        Ok(mb) => mb,
469        Err(_) => return RobotIdentityChainResult::fail("hardware_key_unresolvable", trusted_root),
470    };
471    if robot_key_mb != hardware_key {
472        return RobotIdentityChainResult::fail("hardware_key_mismatch", trusted_root);
473    }
474
475    // Hardware-rooted only when the manufacturer bound the hardware-root key and
476    // the robot's attestation was made by exactly that key.
477    let mut hardware_rooted = false;
478    if let Some(pinned) = attributes.get("hardwareRootKey") {
479        let claimed = hw_subject
480            .get("hardwareRoot")
481            .and_then(|h| h.get("publicKeyMultibase"))
482            .and_then(|v| v.as_str());
483        if pinned.as_str().is_none() || claimed != pinned.as_str() {
484            return RobotIdentityChainResult::fail("hardware_root_mismatch", trusted_root);
485        }
486        hardware_rooted = true;
487    }
488
489    RobotIdentityChainResult {
490        ok: true,
491        reason: None,
492        robot_did: chain.agent_did,
493        issuer_did: chain.issuer_did,
494        root_did: Some(trusted_root.to_string()),
495        attributes: Some(attributes),
496        hardware_rooted,
497    }
498}
499
500// ---------------------------------------------------------------------------
501// Model and config provenance (Phase 5.2)
502// ---------------------------------------------------------------------------
503
504pub const MODEL_PROVENANCE_TYPE: &str = "ModelProvenanceAttestation";
505
506/// Multibase SHA-256 of the JCS-canonical config object. Python, TypeScript, Go,
507/// and Rust all canonicalize identically, so the digest is the same byte string
508/// in every language.
509pub fn config_hash(config: &Value) -> String {
510    let digest = Sha256::digest(jcs::canonicalize(config));
511    mb64(&digest)
512}
513
514/// Parameters for [`build_provenance_attestation`]. The issuer is the signer (the
515/// robot itself or an authority); `robot_did` names the robot the attestation is
516/// about.
517#[derive(Debug, Clone)]
518pub struct BuildProvenance {
519    pub issuer_did: String,
520    pub robot_did: String,
521    pub model_name: String,
522    pub weights_hash: String,
523    pub safety_policy: String,
524    pub config: Option<Value>,
525    pub version: Option<String>,
526    pub supersedes: Option<String>,
527    pub valid_from: String,
528    pub valid_until: Option<String>,
529}
530
531/// Build a signed `ModelProvenanceAttestation` for the software on a robot.
532pub fn build_provenance_attestation(signer_seed: &[u8], params: &BuildProvenance) -> Result<Value> {
533    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
534    let mut vla = Map::new();
535    vla.insert("modelName".into(), json!(params.model_name));
536    vla.insert("weightsHash".into(), json!(params.weights_hash));
537    vla.insert("safetyPolicy".into(), json!(params.safety_policy));
538    if let Some(v) = &params.version {
539        vla.insert("version".into(), json!(v));
540    }
541    if let Some(cfg) = &params.config {
542        vla.insert("configHash".into(), json!(config_hash(cfg)));
543    }
544
545    let mut subject = Map::new();
546    subject.insert("id".into(), json!(params.robot_did));
547    subject.insert("vla".into(), Value::Object(vla));
548    if let Some(s) = &params.supersedes {
549        subject.insert("supersedes".into(), json!(s));
550    }
551
552    let mut cred = Map::new();
553    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
554    cred.insert(
555        "type".into(),
556        json!(["VerifiableCredential", MODEL_PROVENANCE_TYPE]),
557    );
558    cred.insert("issuer".into(), json!(params.issuer_did));
559    cred.insert("validFrom".into(), json!(params.valid_from));
560    if let Some(vu) = &params.valid_until {
561        cred.insert("validUntil".into(), json!(vu));
562    }
563    cred.insert("credentialSubject".into(), Value::Object(subject));
564
565    let opts = BuildProofOptions::new(
566        crate::verification_method::ed25519_method(&params.issuer_did),
567        params.valid_from.clone(),
568    );
569    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
570}
571
572/// Verify a `ModelProvenanceAttestation`. When `config` is supplied, also check
573/// the recorded configHash reproduces. Returns the subject on success, `None`
574/// otherwise.
575pub fn verify_provenance_attestation(
576    attestation: &Value,
577    keys: Keys<'_>,
578    config: Option<&Value>,
579    now_iso: &str,
580) -> Result<Option<Value>> {
581    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attestation, config);
582    let v = match bound(
583        attestation,
584        keys,
585        MODEL_PROVENANCE_TYPE,
586        now_iso,
587        Window::FromRequired,
588    )? {
589        Some(v) => v,
590        None => return Ok(None),
591    };
592    if let Some(cfg) = config {
593        let want = config_hash(cfg);
594        let got = v
595            .subject
596            .get("vla")
597            .and_then(|v| v.as_object())
598            .and_then(|v| v.get("configHash"))
599            .and_then(|v| v.as_str());
600        if got != Some(want.as_str()) {
601            return Ok(None);
602        }
603    }
604    Ok(Some(v.subject))
605}
606
607/// The reference a superseding attestation uses: multibase SHA-256 of the JCS
608/// form of the whole signed attestation (proof included).
609pub fn provenance_attestation_id(attestation: &Value) -> String {
610    mb64(&Sha256::digest(jcs::canonicalize(attestation)))
611}
612
613/// Verify an ordered OTA history of provenance attestations for `robot_did`:
614/// every attestation verifies and is about `robot_did`; each one after the
615/// first names the previous by [`provenance_attestation_id`] as `supersedes`
616/// and is dated no earlier. Each earlier attestation must still have been valid
617/// when the next was made, and the last at `now_iso`. Returns the latest
618/// subject on success.
619pub fn verify_provenance_chain(
620    attestations: &[Value],
621    keys: Keys<'_>,
622    robot_did: &str,
623    now_iso: &str,
624) -> Result<Option<Value>> {
625    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attestations);
626    rv::require_now(now_iso)?;
627    if attestations.is_empty() || robot_did.is_empty() {
628        return Ok(None);
629    }
630    let mut prev: Option<&Value> = None;
631    let mut latest = None;
632    for (i, att) in attestations.iter().enumerate() {
633        let at: String = match attestations.get(i + 1) {
634            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
635                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
636                _ => return Ok(None),
637            },
638            None => now_iso.to_string(),
639        };
640        let subject = match verify_provenance_attestation(att, keys, None, &at)? {
641            Some(s) if s.get("id").and_then(|v| v.as_str()) == Some(robot_did) => s,
642            _ => return Ok(None),
643        };
644        if let Some(p) = prev {
645            if subject.get("supersedes").and_then(|v| v.as_str())
646                != Some(provenance_attestation_id(p).as_str())
647            {
648                return Ok(None);
649            }
650            if rv::time_ns(att.get("validFrom")) < rv::time_ns(p.get("validFrom")) {
651                return Ok(None);
652            }
653        }
654        prev = Some(att);
655        latest = Some(subject);
656    }
657    Ok(latest)
658}
659
660// ---------------------------------------------------------------------------
661// Physical capability scope (Phase 5.3)
662// ---------------------------------------------------------------------------
663
664pub const PHYSICAL_SCOPE_TYPE: &str = "PhysicalCapabilityScope";
665
666/// An allowed time-of-day window, "HH:MM" start and end.
667#[derive(Debug, Clone)]
668pub struct ShiftWindow {
669    pub start: String,
670    pub end: String,
671}
672
673/// A proposed actuation to check against a scope. `None` numerics mean "not
674/// specified" (a meaningful zero is still `Some(0.0)`).
675#[derive(Debug, Clone, Default)]
676pub struct PhysicalAction {
677    pub force_n: Option<f64>,
678    pub speed_mps: Option<f64>,
679    pub near_humans: bool,
680    pub zone: Option<String>,
681    pub time_hm: Option<String>,
682}
683
684/// The outcome of [`check_physical_action`].
685#[derive(Debug, Clone)]
686pub struct CheckResult {
687    pub ok: bool,
688    pub reasons: Vec<String>,
689}
690
691/// Parameters for [`build_physical_scope_credential`]. The issuer is the signer
692/// (a fleet authority); `subject_did` is the robot the scope is granted to.
693#[derive(Debug, Clone, Default)]
694pub struct BuildPhysicalScope {
695    pub issuer_did: String,
696    pub subject_did: String,
697    pub max_force_n: Option<f64>,
698    pub max_speed_mps: Option<f64>,
699    pub max_speed_near_humans_mps: Option<f64>,
700    pub allowed_zones: Option<Vec<String>>,
701    pub shift_windows: Option<Vec<ShiftWindow>>,
702    pub valid_from: String,
703    pub valid_until: Option<String>,
704}
705
706/// Build a signed `PhysicalCapabilityScope` credential.
707pub fn build_physical_scope_credential(
708    signer_seed: &[u8],
709    params: &BuildPhysicalScope,
710) -> Result<Value> {
711    let mut scope = Map::new();
712    if let Some(v) = params.max_force_n {
713        scope.insert("maxForceN".into(), json!(v));
714    }
715    if let Some(v) = params.max_speed_mps {
716        scope.insert("maxSpeedMps".into(), json!(v));
717    }
718    if let Some(v) = params.max_speed_near_humans_mps {
719        scope.insert("maxSpeedNearHumansMps".into(), json!(v));
720    }
721    if let Some(zones) = &params.allowed_zones {
722        scope.insert("allowedZones".into(), json!(zones));
723    }
724    if let Some(ws) = &params.shift_windows {
725        let arr: Vec<Value> = ws
726            .iter()
727            .map(|w| json!({"start": w.start, "end": w.end}))
728            .collect();
729        scope.insert("shiftWindows".into(), Value::Array(arr));
730    }
731
732    let mut subject = Map::new();
733    subject.insert("id".into(), json!(params.subject_did));
734    subject.insert("physicalScope".into(), Value::Object(scope));
735
736    let mut cred = Map::new();
737    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
738    cred.insert(
739        "type".into(),
740        json!(["VerifiableCredential", PHYSICAL_SCOPE_TYPE]),
741    );
742    cred.insert("issuer".into(), json!(params.issuer_did));
743    cred.insert("validFrom".into(), json!(params.valid_from));
744    if let Some(vu) = &params.valid_until {
745        cred.insert("validUntil".into(), json!(vu));
746    }
747    cred.insert("credentialSubject".into(), Value::Object(subject));
748
749    let opts = BuildProofOptions::new(
750        crate::verification_method::ed25519_method(&params.issuer_did),
751        params.valid_from.clone(),
752    );
753    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
754}
755
756/// The numeric caps a physical scope may set.
757pub const CAP_KEYS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
758/// Every dimension a physical scope may set.
759pub const SCOPE_KEYS: [&str; 5] = [
760    "maxForceN",
761    "maxSpeedMps",
762    "maxSpeedNearHumansMps",
763    "allowedZones",
764    "shiftWindows",
765];
766
767/// Minutes since midnight for a strict `HH:MM` string (00:00-23:59), else `None`.
768pub fn parse_hm(value: &str) -> Option<u32> {
769    let b = value.as_bytes();
770    if b.len() != 5
771        || b[2] != b':'
772        || !b
773            .iter()
774            .enumerate()
775            .all(|(i, c)| i == 2 || c.is_ascii_digit())
776    {
777        return None;
778    }
779    let h = u32::from(b[0] - b'0') * 10 + u32::from(b[1] - b'0');
780    let m = u32::from(b[3] - b'0') * 10 + u32::from(b[4] - b'0');
781    if h > 23 || m > 59 {
782        return None;
783    }
784    Some(h * 60 + m)
785}
786
787/// A usable physical cap: a finite, non-negative JSON number (never a boolean).
788pub fn valid_cap(v: &Value) -> bool {
789    v.is_number() && v.as_f64().is_some_and(|n| n.is_finite() && n >= 0.0)
790}
791
792/// `(start, end)` minutes of a `{"start", "end"}` window with start <= end.
793pub fn parse_window(w: &Value) -> Option<(u32, u32)> {
794    let o = w.as_object()?;
795    let start = parse_hm(o.get("start")?.as_str()?)?;
796    let end = parse_hm(o.get("end")?.as_str()?)?;
797    (start <= end).then_some((start, end))
798}
799
800/// Every window of a list, or `None` if the list or any window is malformed.
801pub fn parse_windows(v: &Value) -> Option<Vec<(u32, u32)>> {
802    v.as_array()?.iter().map(parse_window).collect()
803}
804
805/// The zone ids of a list of strings, or `None` if malformed.
806pub fn parse_zones(v: &Value) -> Option<Vec<&str>> {
807    v.as_array()?.iter().map(|z| z.as_str()).collect()
808}
809
810/// Reasons the scope itself cannot be read; empty when every set dimension is
811/// well-formed.
812pub fn scope_problems(scope: &Value) -> Vec<String> {
813    crate::nesting::deep_guard!(vec![crate::nesting::TOO_DEEP.into()]; scope);
814    let o = match scope.as_object() {
815        Some(o) => o,
816        None => return vec!["scope_malformed: not an object".into()],
817    };
818    let mut problems = Vec::new();
819    for key in CAP_KEYS {
820        if o.get(key).is_some_and(|v| !valid_cap(v)) {
821            problems.push(format!(
822                "scope_malformed: {key} is not a finite non-negative number"
823            ));
824        }
825    }
826    if o.get("allowedZones")
827        .is_some_and(|v| parse_zones(v).is_none())
828    {
829        problems.push("scope_malformed: allowedZones is not a list of strings".into());
830    }
831    if o.get("shiftWindows")
832        .is_some_and(|v| parse_windows(v).is_none())
833    {
834        problems.push("scope_malformed: shiftWindows is not a list of HH:MM windows".into());
835    }
836    problems
837}
838
839/// Verify a `PhysicalCapabilityScope` credential and return its physicalScope:
840/// the proof bound to the issuer, the window at `now_iso` (validFrom
841/// required), a well-formed scope with no unknown dimension (a misspelt cap
842/// would otherwise limit nothing), and (when given) the subject `subject_did`.
843pub fn verify_physical_scope_credential(
844    credential: &Value,
845    keys: Keys<'_>,
846    subject_did: Option<&str>,
847    now_iso: &str,
848) -> Result<Option<Value>> {
849    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
850    let v = match bound(
851        credential,
852        keys,
853        PHYSICAL_SCOPE_TYPE,
854        now_iso,
855        Window::FromRequired,
856    )? {
857        Some(v) => v,
858        None => return Ok(None),
859    };
860    if subject_did.is_some_and(|d| v.subject.get("id").and_then(|x| x.as_str()) != Some(d)) {
861        return Ok(None);
862    }
863    let scope = match v.subject.get("physicalScope") {
864        Some(sc @ Value::Object(o)) if o.keys().all(|k| SCOPE_KEYS.contains(&k.as_str())) => sc,
865        _ => return Ok(None),
866    };
867    if !scope_problems(scope).is_empty() {
868        return Ok(None);
869    }
870    Ok(Some(scope.clone()))
871}
872
873/// Check a proposed physical action against a physical scope object, returning
874/// ok plus a reason for each violation. A scope dimension that is set but
875/// malformed, and an action value that is not a finite non-negative number or
876/// not a strict `HH:MM`, are violations. An empty zone or shift-window list
877/// allows nothing. Near humans, the speed cap is the lower of `maxSpeedMps`
878/// and `maxSpeedNearHumansMps`.
879pub fn check_physical_action(scope: &Value, action: &PhysicalAction) -> CheckResult {
880    crate::nesting::deep_guard!(CheckResult { ok: false, reasons: vec![crate::nesting::TOO_DEEP.into()] }; scope);
881    let mut reasons = scope_problems(scope);
882    if !reasons.is_empty() {
883        return CheckResult { ok: false, reasons };
884    }
885    let o = scope
886        .as_object()
887        .expect("scope_problems checked it is an object");
888    for (name, value) in [("force_n", action.force_n), ("speed_mps", action.speed_mps)] {
889        if let Some(v) = value {
890            if !v.is_finite() || v < 0.0 {
891                reasons.push(format!(
892                    "action_malformed: {name} is not a finite non-negative number"
893                ));
894            }
895        }
896    }
897    if !reasons.is_empty() {
898        return CheckResult { ok: false, reasons };
899    }
900    let cap = |k: &str| o.get(k).and_then(|v| v.as_f64());
901
902    if let (Some(force), Some(c)) = (action.force_n, cap("maxForceN")) {
903        if force > c {
904            reasons.push(format!("force_exceeded: {force}N > {c}N"));
905        }
906    }
907    if let Some(speed) = action.speed_mps {
908        let mut c = cap("maxSpeedMps");
909        if action.near_humans {
910            if let Some(near) = cap("maxSpeedNearHumansMps") {
911                c = Some(c.map_or(near, |g| g.min(near)));
912            }
913        }
914        if let Some(c) = c {
915            if speed > c {
916                let label = if action.near_humans {
917                    "near_humans "
918                } else {
919                    ""
920                };
921                reasons.push(format!("{label}speed_exceeded: {speed} m/s > {c} m/s"));
922            }
923        }
924    }
925    if let (Some(zone), Some(zones)) = (&action.zone, o.get("allowedZones").and_then(parse_zones)) {
926        if !zones.contains(&zone.as_str()) {
927            reasons.push(format!("zone_not_allowed: {zone}"));
928        }
929    }
930    if let (Some(hm), Some(ws)) = (&action.time_hm, o.get("shiftWindows")) {
931        match parse_hm(hm) {
932            None => reasons.push(format!("action_malformed: time_hm {hm:?} is not HH:MM")),
933            Some(t) => {
934                let windows = parse_windows(ws).unwrap_or_default();
935                if !windows.iter().any(|(s, e)| *s <= t && t <= *e) {
936                    reasons.push(format!("outside_shift_window: {hm}"));
937                }
938            }
939        }
940    }
941    CheckResult {
942        ok: reasons.is_empty(),
943        reasons,
944    }
945}
946
947/// Report whether `child` is a valid attenuation of `parent`: never broader on
948/// any physical dimension. Both scopes must be well-formed; for every dimension
949/// the parent sets, the child must set it too and be no broader (a cap no
950/// higher, a NON-EMPTY subset of zones, a NON-EMPTY list of windows each inside
951/// some parent window). Leaving a dimension out, or an empty list, is never an
952/// attenuation of a parent that limits it.
953pub fn attenuates(parent: &Value, child: &Value) -> bool {
954    crate::nesting::deep_guard!(false; parent, child);
955    if !scope_problems(parent).is_empty() || !scope_problems(child).is_empty() {
956        return false;
957    }
958    let (p, c) = match (parent.as_object(), child.as_object()) {
959        (Some(p), Some(c)) => (p, c),
960        _ => return false,
961    };
962    for key in CAP_KEYS {
963        if let Some(pv) = p.get(key).and_then(|v| v.as_f64()) {
964            match c.get(key).and_then(|v| v.as_f64()) {
965                Some(cv) if cv <= pv => {}
966                _ => return false,
967            }
968        }
969    }
970    if let Some(pz) = p.get("allowedZones").and_then(parse_zones) {
971        match c.get("allowedZones").and_then(parse_zones) {
972            Some(cz) if !cz.is_empty() && cz.iter().all(|z| pz.contains(z)) => {}
973            _ => return false,
974        }
975    }
976    if let Some(pw) = p.get("shiftWindows").and_then(parse_windows) {
977        match c.get("shiftWindows").and_then(parse_windows) {
978            Some(cw) if !cw.is_empty() => {
979                for (cs, ce) in cw {
980                    if !pw.iter().any(|(ps, pe)| *ps <= cs && ce <= *pe) {
981                        return false;
982                    }
983                }
984            }
985            _ => return false,
986        }
987    }
988    true
989}
990
991// ---------------------------------------------------------------------------
992// Robot-to-robot trust handshake (Phase 5.4)
993// ---------------------------------------------------------------------------
994
995pub const HELLO: &str = "handshake_hello";
996pub const ACCEPT: &str = "handshake_accept";
997pub const CONFIRM: &str = "handshake_confirm";
998
999/// Decides whether a peer DID is trusted: its did:web or did:webvh name must
1000/// be allowed, or `accept_unknown` is set. The name is the domain plus any
1001/// path, colon-joined (`did:web:a.example:agents` is `a.example:agents`), so a
1002/// bare-domain entry trusts the bare domain only and a path is trusted only
1003/// when the policy names it.
1004#[derive(Debug, Clone, Default)]
1005pub struct TrustPolicy {
1006    pub trusted_domains: HashSet<String>,
1007    pub accept_unknown: bool,
1008}
1009
1010impl TrustPolicy {
1011    pub fn new(domains: impl IntoIterator<Item = String>, accept_unknown: bool) -> Self {
1012        Self {
1013            trusted_domains: domains.into_iter().collect(),
1014            accept_unknown,
1015        }
1016    }
1017
1018    pub fn is_trusted(&self, did: &str) -> bool {
1019        if self.accept_unknown {
1020            return true;
1021        }
1022        match did_web_domain(did) {
1023            Some(d) => self.trusted_domains.contains(&d),
1024            None => false,
1025        }
1026    }
1027}
1028
1029/// The agreed cooperation session after a successful handshake.
1030#[derive(Debug, Clone)]
1031pub struct BoundedSession {
1032    pub session_id: String,
1033    pub initiator: String,
1034    pub responder: String,
1035    pub scope: Vec<String>,
1036    pub nonce: String,
1037    pub valid_until: Option<String>,
1038}
1039
1040/// The name a did:web or did:webvh DID is trusted under, or None: the domain,
1041/// then each path segment after a colon. Each prefix keeps its trailing colon,
1042/// so a did:webvh DID never reads as did:web. A did:webvh DID is parsed
1043/// strictly ([`crate::did_webvh::parse`]) and gives its host (percent-decoded
1044/// and lower-cased) and its percent-decoded path; one that does not parse has
1045/// no name. A did:web with an empty segment has no name.
1046fn did_web_domain(did: &str) -> Option<String> {
1047    if crate::did_webvh::is_did_webvh(did) {
1048        return crate::did_webvh::parse(did).ok().map(|parsed| {
1049            core::iter::once(parsed.host)
1050                .chain(parsed.path)
1051                .collect::<Vec<_>>()
1052                .join(":")
1053        });
1054    }
1055    let rest = did.strip_prefix("did:web:")?;
1056    if rest.split(':').any(str::is_empty) {
1057        None
1058    } else {
1059        Some(rest.to_string())
1060    }
1061}
1062
1063/// Parameters for [`build_hello`]. `nonce` and `issued_at` are caller-supplied so
1064/// the core stays deterministic; the wrapper SDKs generate them.
1065#[derive(Debug, Clone, Default)]
1066pub struct BuildHello {
1067    pub from_did: String,
1068    pub proposed_scope: Vec<String>,
1069    pub nonce: String,
1070    pub peer_did: Option<String>,
1071    pub issued_at: String,
1072}
1073
1074/// Open the handshake (initiator A): a proposed scope and a fresh nonce, signed.
1075pub fn build_hello(signer_seed: &[u8], params: &BuildHello) -> Result<Value> {
1076    let mut hello = Map::new();
1077    hello.insert("type".into(), json!(HELLO));
1078    hello.insert("from".into(), json!(params.from_did));
1079    hello.insert(
1080        "to".into(),
1081        match &params.peer_did {
1082            Some(p) => json!(p),
1083            None => Value::Null,
1084        },
1085    );
1086    hello.insert("nonce".into(), json!(params.nonce));
1087    hello.insert("proposedScope".into(), json!(params.proposed_scope));
1088    hello.insert("issuedAt".into(), json!(params.issued_at));
1089    let opts = BuildProofOptions::new(
1090        crate::verification_method::ed25519_method(&params.from_did),
1091        &params.issued_at,
1092    );
1093    data_integrity::sign(&Value::Object(hello), signer_seed, &opts)
1094}
1095
1096/// The default clock skew for handshake freshness checks (seconds).
1097pub const DEFAULT_HANDSHAKE_SKEW_SECONDS: i64 = 30;
1098/// The oldest HELLO a responder answers (seconds).
1099pub const DEFAULT_MAX_HELLO_AGE_SECONDS: i64 = 300;
1100/// The longest session an ACCEPT may grant (validUntil - issuedAt).
1101pub const DEFAULT_MAX_SESSION_SECONDS: i64 = 3600;
1102
1103/// The message is `expected_type` and its proof is bound to the DID in `from`
1104/// (assertionMethod, verification method of that DID, key resolved from it).
1105fn handshake_message_ok(obj: &Value, keys: Keys<'_>, expected_type: &str) -> bool {
1106    if obj.get("type").and_then(|v| v.as_str()) != Some(expected_type) {
1107        return false;
1108    }
1109    if rv::input_too_large(obj, rv::MAX_CREDENTIAL_BYTES).is_some() {
1110        return false;
1111    }
1112    let sender = match obj.get("from").and_then(|v| v.as_str()) {
1113        Some(s) if s.starts_with("did:") => s,
1114        _ => return false,
1115    };
1116    if rv::proof_unbound_reason(obj.get("proof").unwrap_or(&Value::Null), sender).is_some() {
1117        return false;
1118    }
1119    // The handshake binds each message to the DID in `from`; whether that
1120    // party is trusted is the policy's decision (or the caller's own HELLO or
1121    // ACCEPT pins it), so `from` is the pinned issuer here.
1122    let key = match rv::resolve_issuer_key(sender, rv::pin_if_keyless(keys, Some(sender))) {
1123        Ok(k) => k,
1124        Err(_) => return false,
1125    };
1126    matches!(data_integrity::verify_proof(obj, &key), Ok(true))
1127}
1128
1129fn scope_list(v: Option<&Value>) -> Option<Vec<String>> {
1130    v?.as_array()?
1131        .iter()
1132        .map(|x| x.as_str().map(String::from))
1133        .collect()
1134}
1135
1136fn issued_recently(v: Option<&Value>, now_ns: i128, skew: i64, max_age: i64) -> bool {
1137    let issued = match rv::time_ns(v) {
1138        Some(t) => t,
1139        None => return false,
1140    };
1141    let second: i128 = 1_000_000_000;
1142    now_ns - i128::from(max_age.saturating_add(skew)) * second <= issued
1143        && issued <= now_ns + i128::from(skew) * second
1144}
1145
1146impl BoundedSession {
1147    /// True while `now_iso` is at or before the session's validUntil (required).
1148    pub fn is_current(&self, now_iso: &str) -> bool {
1149        match (
1150            self.valid_until
1151                .as_deref()
1152                .and_then(|u| crate::time::parse_protocol_time_ns(u).ok()),
1153            crate::time::parse_protocol_time_ns(now_iso).ok(),
1154        ) {
1155            (Some(u), Some(n)) => n <= u,
1156            _ => false,
1157        }
1158    }
1159}
1160
1161/// Parameters for [`build_accept`]. `issued_at` is the responder's clock (it
1162/// also judges the HELLO's age); `valid_until` bounds the session.
1163#[derive(Debug, Clone, Default)]
1164pub struct BuildAccept {
1165    pub from_did: String,
1166    pub offered_scope: Vec<String>,
1167    pub session_id: String,
1168    pub valid_until: String,
1169    pub created: String,
1170}
1171
1172/// Verify A's HELLO, check A's domain, intersect the scope, and sign an
1173/// acceptance (responder B). The HELLO's proof must be bound to its `from` DID
1174/// (`hello_keys` is a `{did: key}` source, or the bare key of a did:key
1175/// initiator); it must be addressed to this responder (`to` unset or this
1176/// responder's DID) and its `issuedAt` within [`DEFAULT_MAX_HELLO_AGE_SECONDS`]
1177/// (plus [`DEFAULT_HANDSHAKE_SKEW_SECONDS`]) of `params.created`. The trust
1178/// policy is applied to the verified `from`. The ACCEPT carries `issuedAt`.
1179pub fn build_accept(
1180    signer_seed: &[u8],
1181    hello: &Value,
1182    hello_keys: Keys<'_>,
1183    policy: &TrustPolicy,
1184    params: &BuildAccept,
1185) -> Result<Value> {
1186    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); hello);
1187    build_accept_with(
1188        signer_seed,
1189        hello,
1190        hello_keys,
1191        policy,
1192        params,
1193        HandshakeLimits::default(),
1194    )
1195}
1196
1197/// The time limits of the handshake: the clock skew allowed either way, the
1198/// oldest HELLO (for [`build_accept_with`]) or ACCEPT (for
1199/// [`verify_accept_with`]) accepted, and the longest session an ACCEPT may
1200/// grant.
1201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1202pub struct HandshakeLimits {
1203    pub clock_skew_seconds: i64,
1204    pub max_age_seconds: i64,
1205    pub max_session_seconds: i64,
1206}
1207
1208impl Default for HandshakeLimits {
1209    fn default() -> Self {
1210        Self {
1211            clock_skew_seconds: DEFAULT_HANDSHAKE_SKEW_SECONDS,
1212            max_age_seconds: DEFAULT_MAX_HELLO_AGE_SECONDS,
1213            max_session_seconds: DEFAULT_MAX_SESSION_SECONDS,
1214        }
1215    }
1216}
1217
1218impl HandshakeLimits {
1219    fn check(&self) -> Result<()> {
1220        if !(0..=120).contains(&self.clock_skew_seconds) {
1221            return Err(CoreError::Json(
1222                "clock skew must be between 0 and 120 seconds".into(),
1223            ));
1224        }
1225        if self.max_age_seconds < 0 || self.max_session_seconds < 1 {
1226            return Err(CoreError::Json(
1227                "handshake age and session limits must be positive".into(),
1228            ));
1229        }
1230        Ok(())
1231    }
1232}
1233
1234/// [`build_accept`] with the caller's [`HandshakeLimits`].
1235pub fn build_accept_with(
1236    signer_seed: &[u8],
1237    hello: &Value,
1238    hello_keys: Keys<'_>,
1239    policy: &TrustPolicy,
1240    params: &BuildAccept,
1241    limits: HandshakeLimits,
1242) -> Result<Value> {
1243    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); hello);
1244    limits.check()?;
1245    let now = rv::require_now(&params.created)?;
1246    if !handshake_message_ok(hello, hello_keys, HELLO) {
1247        return Err(CoreError::Json(
1248            "HELLO is not signed by the DID it is from".into(),
1249        ));
1250    }
1251    match hello.get("to") {
1252        None | Some(Value::Null) => {}
1253        Some(Value::String(t)) if *t == params.from_did => {}
1254        _ => return Err(CoreError::Json("HELLO is addressed to another node".into())),
1255    }
1256    if !issued_recently(
1257        hello.get("issuedAt"),
1258        now,
1259        limits.clock_skew_seconds,
1260        limits.max_age_seconds,
1261    ) {
1262        return Err(CoreError::Json(
1263            "HELLO is stale, from the future, or has no valid issuedAt".into(),
1264        ));
1265    }
1266    let proposed = scope_list(hello.get("proposedScope"));
1267    let nonce = hello
1268        .get("nonce")
1269        .and_then(|v| v.as_str())
1270        .filter(|n| !n.is_empty());
1271    let (proposed, nonce) = match (proposed, nonce) {
1272        (Some(p), Some(n)) => (p, n),
1273        _ => return Err(CoreError::Json("HELLO is malformed".into())),
1274    };
1275    let initiator = hello.get("from").and_then(|v| v.as_str()).unwrap_or("");
1276    if !policy.is_trusted(initiator) {
1277        return Err(CoreError::Json(format!(
1278            "peer {initiator} is not in this trust domain's policy"
1279        )));
1280    }
1281    if rv::time_ns(Some(&json!(params.valid_until))).is_none_or(|u| u <= now) {
1282        return Err(CoreError::Json(
1283            "valid_until must be a protocol time after created".into(),
1284        ));
1285    }
1286
1287    let offered: HashSet<&str> = params.offered_scope.iter().map(|s| s.as_str()).collect();
1288    let mut bounded: Vec<String> = proposed
1289        .into_iter()
1290        .filter(|s| offered.contains(s.as_str()))
1291        .collect::<HashSet<_>>()
1292        .into_iter()
1293        .collect();
1294    bounded.sort();
1295
1296    let mut accept = Map::new();
1297    accept.insert("type".into(), json!(ACCEPT));
1298    accept.insert("from".into(), json!(params.from_did));
1299    accept.insert("to".into(), json!(initiator));
1300    accept.insert("sessionId".into(), json!(params.session_id));
1301    accept.insert("nonce".into(), json!(nonce));
1302    accept.insert("boundedScope".into(), json!(bounded));
1303    accept.insert("issuedAt".into(), json!(params.created));
1304    accept.insert("validUntil".into(), json!(params.valid_until));
1305    let opts = BuildProofOptions::new(
1306        crate::verification_method::ed25519_method(&params.from_did),
1307        &params.created,
1308    );
1309    data_integrity::sign(&Value::Object(accept), signer_seed, &opts)
1310}
1311
1312/// Verify B's ACCEPT against the HELLO that A sent (initiator A). The ACCEPT's
1313/// proof must be bound to its `from` DID; it must be addressed to A (`to` ==
1314/// the HELLO's `from`), come from the node the HELLO was addressed to (a HELLO
1315/// addressed to nobody needs a `policy` that trusts the responder), echo the
1316/// HELLO's nonce (and `expected_nonce` when given), carry a bounded scope that
1317/// is a subset of what A proposed, and not have expired at `now_iso`.
1318pub fn verify_accept(
1319    accept: &Value,
1320    accept_keys: Keys<'_>,
1321    hello: &Value,
1322    expected_nonce: Option<&str>,
1323    policy: Option<&TrustPolicy>,
1324    now_iso: &str,
1325) -> Result<Option<BoundedSession>> {
1326    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); accept, hello);
1327    verify_accept_with(
1328        accept,
1329        accept_keys,
1330        hello,
1331        expected_nonce,
1332        policy,
1333        HandshakeLimits::default(),
1334        now_iso,
1335    )
1336}
1337
1338/// [`verify_accept`] with the caller's [`HandshakeLimits`].
1339pub fn verify_accept_with(
1340    accept: &Value,
1341    accept_keys: Keys<'_>,
1342    hello: &Value,
1343    expected_nonce: Option<&str>,
1344    policy: Option<&TrustPolicy>,
1345    limits: HandshakeLimits,
1346    now_iso: &str,
1347) -> Result<Option<BoundedSession>> {
1348    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); accept, hello);
1349    limits.check()?;
1350    let now = rv::require_now(now_iso)?;
1351    if !hello.is_object() || !handshake_message_ok(accept, accept_keys, ACCEPT) {
1352        return Ok(None);
1353    }
1354    let responder = accept
1355        .get("from")
1356        .and_then(|v| v.as_str())
1357        .unwrap_or("")
1358        .to_string();
1359    if accept.get("to") != hello.get("from") {
1360        return Ok(None);
1361    }
1362    match hello.get("to") {
1363        Some(Value::String(t)) if *t != responder => return Ok(None),
1364        Some(Value::String(_)) => {}
1365        _ if policy.is_none() => return Ok(None),
1366        _ => {}
1367    }
1368    if let Some(p) = policy {
1369        if !p.is_trusted(&responder) {
1370            return Ok(None);
1371        }
1372    }
1373    let nonce = match accept.get("nonce").and_then(|v| v.as_str()) {
1374        Some(n) if Some(n) == hello.get("nonce").and_then(|v| v.as_str()) => n.to_string(),
1375        _ => return Ok(None),
1376    };
1377    if expected_nonce.is_some_and(|e| e != nonce) {
1378        return Ok(None);
1379    }
1380    let (bounded, proposed) = match (
1381        scope_list(accept.get("boundedScope")),
1382        scope_list(hello.get("proposedScope")),
1383    ) {
1384        (Some(b), Some(p)) if b.iter().all(|x| p.contains(x)) => (b, p),
1385        _ => return Ok(None),
1386    };
1387    let _ = proposed;
1388    let sid = match non_empty_str(accept, "sessionId") {
1389        Some(s) => s.to_string(),
1390        None => return Ok(None),
1391    };
1392    let session = BoundedSession {
1393        session_id: sid,
1394        initiator: accept
1395            .get("to")
1396            .and_then(|v| v.as_str())
1397            .unwrap_or("")
1398            .to_string(),
1399        responder,
1400        scope: bounded,
1401        nonce,
1402        valid_until: accept
1403            .get("validUntil")
1404            .and_then(|v| v.as_str())
1405            .map(String::from),
1406    };
1407    if !session.is_current(now_iso) {
1408        return Ok(None);
1409    }
1410    // issuedAt is required: no older than the HELLO age limit, not ahead of
1411    // the clock beyond the skew, and the session it grants is bounded.
1412    if !issued_recently(
1413        accept.get("issuedAt"),
1414        now,
1415        limits.clock_skew_seconds,
1416        limits.max_age_seconds,
1417    ) {
1418        return Ok(None);
1419    }
1420    match (
1421        rv::time_ns(accept.get("issuedAt")),
1422        rv::time_ns(accept.get("validUntil")),
1423    ) {
1424        (Some(i), Some(u))
1425            if u > i && u - i <= i128::from(limits.max_session_seconds) * 1_000_000_000 => {}
1426        _ => return Ok(None),
1427    }
1428    Ok(Some(session))
1429}
1430
1431/// Sign A's confirmation of the bounded session to B. Refuses an expired
1432/// session (checked at `created`).
1433pub fn build_confirm(
1434    signer_seed: &[u8],
1435    from_did: &str,
1436    session: &BoundedSession,
1437    created: &str,
1438) -> Result<Value> {
1439    rv::require_now(created)?;
1440    if !session.is_current(created) {
1441        return Err(CoreError::Json("the session has expired".into()));
1442    }
1443    let mut confirm = Map::new();
1444    confirm.insert("type".into(), json!(CONFIRM));
1445    confirm.insert("from".into(), json!(from_did));
1446    confirm.insert("to".into(), json!(session.responder));
1447    confirm.insert("sessionId".into(), json!(session.session_id));
1448    confirm.insert("nonce".into(), json!(session.nonce));
1449    confirm.insert("acceptedScope".into(), json!(session.scope));
1450    let opts = BuildProofOptions::new(
1451        crate::verification_method::ed25519_method(from_did),
1452        created,
1453    );
1454    data_integrity::sign(&Value::Object(confirm), signer_seed, &opts)
1455}
1456
1457/// Verify A's CONFIRM closes the session B accepted (responder B). `accept` is
1458/// the ACCEPT B sent. The CONFIRM's proof must be bound to its `from` DID,
1459/// which must be the initiator (the ACCEPT's `to`); it must be addressed to
1460/// B, name the same session and nonce, accept a scope within the bounded
1461/// scope, and arrive while the session is still valid at `now_iso`.
1462pub fn verify_confirm(
1463    confirm: &Value,
1464    confirm_keys: Keys<'_>,
1465    accept: &Value,
1466    now_iso: &str,
1467) -> Result<bool> {
1468    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); confirm, accept);
1469    let now = rv::require_now(now_iso)?;
1470    if !accept.is_object() || !handshake_message_ok(confirm, confirm_keys, CONFIRM) {
1471        return Ok(false);
1472    }
1473    if confirm.get("from") != accept.get("to") || confirm.get("to") != accept.get("from") {
1474        return Ok(false);
1475    }
1476    if confirm.get("sessionId") != accept.get("sessionId")
1477        || confirm.get("nonce") != accept.get("nonce")
1478    {
1479        return Ok(false);
1480    }
1481    match (
1482        scope_list(confirm.get("acceptedScope")),
1483        scope_list(accept.get("boundedScope")),
1484    ) {
1485        (Some(a), Some(b)) if a.iter().all(|x| b.contains(x)) => {}
1486        _ => return Ok(false),
1487    }
1488    Ok(rv::time_ns(accept.get("validUntil")).is_some_and(|u| now <= u))
1489}
1490
1491// ---------------------------------------------------------------------------
1492// Black box and kill switch (Phase 5.5)
1493// ---------------------------------------------------------------------------
1494
1495/// Version 1.1 entries bind their header (every field but the ciphertext and
1496/// the hash) into AES-GCM as associated data; 1.0 entries do not.
1497pub const BLACKBOX_VERSION: &str = "1.1";
1498/// The pre-1.1 entry version, still opened (without associated data).
1499pub const BLACKBOX_LEGACY_VERSION: &str = "1.0";
1500/// A signed black-box head: entry count plus last hash.
1501pub const BLACKBOX_HEAD_TYPE: &str = "BlackBoxHeadCredential";
1502/// Size cap for a log handed to a verifier (before canonicalization).
1503pub const MAX_LOG_BYTES: usize = 64 * 1024 * 1024;
1504pub const KILLSWITCH_TYPE: &str = "KillSwitchCredential";
1505pub const EMERGENCY_STOP: &str = "emergency_stop";
1506
1507/// The prevHash of the first entry: multibase of 32 zero bytes.
1508pub fn genesis_prev_hash() -> String {
1509    mb64(&[0u8; 32])
1510}
1511
1512/// The entry header bound into AES-GCM: JCS of every field but the ciphertext
1513/// and the entry hash.
1514fn entry_aad(entry: &Map<String, Value>) -> Vec<u8> {
1515    let mut header = entry.clone();
1516    header.remove("ciphertext");
1517    header.remove("entryHash");
1518    jcs::canonicalize(&Value::Object(header))
1519}
1520
1521fn entry_hash(body: &Map<String, Value>) -> Result<String> {
1522    let mut clean = body.clone();
1523    clean.remove("entryHash");
1524    let canonical = jcs::canonicalize(&Value::Object(clean));
1525    Ok(mb64(&Sha256::digest(canonical)))
1526}
1527
1528/// Build one black-box entry statelessly: encrypt `payload` under `key`, link it
1529/// to `prev_hash` at `seq`, and return the entry with its `entryHash`. The
1530/// stateful [`BlackBoxLog`] and the FFI layer both build on this. The encrypted
1531/// blob is nonce(12) || ciphertext || tag(16).
1532pub fn blackbox_append_entry(
1533    key: &[u8],
1534    seq: u64,
1535    event: &str,
1536    payload: &Value,
1537    timestamp: &str,
1538    prev_hash: &str,
1539) -> Result<Value> {
1540    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); payload);
1541    blackbox_append_entry_with_nonce(key, seq, event, payload, timestamp, prev_hash, None)
1542}
1543
1544/// [`blackbox_append_entry`] with the host's own 12-byte AES-GCM nonce (a
1545/// host with its own random source or a secure element). A nonce must never
1546/// be used twice under one key; without one the core draws a random nonce.
1547pub fn blackbox_append_entry_with_nonce(
1548    key: &[u8],
1549    seq: u64,
1550    event: &str,
1551    payload: &Value,
1552    timestamp: &str,
1553    prev_hash: &str,
1554    host_nonce: Option<&[u8]>,
1555) -> Result<Value> {
1556    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); payload);
1557    if key.len() != 32 {
1558        return Err(CoreError::Crypto(
1559            "black box key must be 32 bytes (AES-256)".into(),
1560        ));
1561    }
1562    let mut nonce = [0u8; 12];
1563    match host_nonce {
1564        Some(n) if n.len() == 12 => nonce.copy_from_slice(n),
1565        Some(_) => return Err(CoreError::Crypto("black box nonce must be 12 bytes".into())),
1566        None => {
1567            crate::random::fill(&mut nonce).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?
1568        }
1569    }
1570    let plaintext = jcs::canonicalize(payload);
1571    let mut body = Map::new();
1572    body.insert("version".into(), json!(BLACKBOX_VERSION));
1573    body.insert("seq".into(), json!(seq));
1574    body.insert("timestamp".into(), json!(timestamp));
1575    body.insert("event".into(), json!(event));
1576    body.insert("prevHash".into(), json!(prev_hash));
1577    let aad = entry_aad(&body);
1578    let cipher =
1579        Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
1580    let ct = cipher
1581        .encrypt(
1582            Nonce::from_slice(&nonce),
1583            Payload {
1584                msg: plaintext.as_ref(),
1585                aad: &aad,
1586            },
1587        )
1588        .map_err(|e| CoreError::Crypto(format!("encrypt: {e}")))?;
1589    let mut blob = Vec::with_capacity(nonce.len() + ct.len());
1590    blob.extend_from_slice(&nonce);
1591    blob.extend_from_slice(&ct);
1592    body.insert("ciphertext".into(), json!(mb64(&blob)));
1593    let h = entry_hash(&body)?;
1594    body.insert("entryHash".into(), json!(h));
1595    Ok(Value::Object(body))
1596}
1597
1598/// An append-only, AES-256-GCM-encrypted, JCS hash-linked event log. The key is
1599/// 32 bytes. The encrypted blob is nonce(12) || ciphertext || tag(16), matching
1600/// Python, TypeScript, and Go.
1601pub struct BlackBoxLog {
1602    key: Vec<u8>,
1603    genesis: String,
1604    entries: Vec<Value>,
1605    head: String,
1606}
1607
1608impl BlackBoxLog {
1609    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
1610    pub fn new(key: &[u8], genesis_prev_hash_override: Option<&str>) -> Result<Self> {
1611        if key.len() != 32 {
1612            return Err(CoreError::Crypto(
1613                "black box key must be 32 bytes (AES-256)".into(),
1614            ));
1615        }
1616        let genesis = genesis_prev_hash_override
1617            .map(String::from)
1618            .unwrap_or_else(genesis_prev_hash);
1619        Ok(Self {
1620            key: key.to_vec(),
1621            head: genesis.clone(),
1622            genesis,
1623            entries: Vec::new(),
1624        })
1625    }
1626
1627    /// Encrypt `payload`, link it to the chain head, and return the new entry.
1628    pub fn append(&mut self, event: &str, payload: &Value, timestamp: &str) -> Result<Value> {
1629        crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); payload);
1630        let entry = blackbox_append_entry(
1631            &self.key,
1632            self.entries.len() as u64,
1633            event,
1634            payload,
1635            timestamp,
1636            &self.head,
1637        )?;
1638        self.head = entry
1639            .get("entryHash")
1640            .and_then(|v| v.as_str())
1641            .unwrap_or("")
1642            .to_string();
1643        self.entries.push(entry.clone());
1644        Ok(entry)
1645    }
1646
1647    pub fn head(&self) -> &str {
1648        &self.head
1649    }
1650
1651    pub fn genesis(&self) -> &str {
1652        &self.genesis
1653    }
1654
1655    pub fn entries(&self) -> &[Value] {
1656        &self.entries
1657    }
1658
1659    /// The number of entries, the count a signed head carries.
1660    pub fn count(&self) -> usize {
1661        self.entries.len()
1662    }
1663
1664    pub fn open(&self, entry: &Value) -> Result<Value> {
1665        crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); entry);
1666        open_entry(entry, &self.key)
1667    }
1668}
1669
1670/// Decrypt a black-box entry payload with the log key.
1671pub fn open_entry(entry: &Value, key: &[u8]) -> Result<Value> {
1672    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); entry);
1673    let obj = entry
1674        .as_object()
1675        .ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
1676    let ct_mb = obj
1677        .get("ciphertext")
1678        .and_then(|v| v.as_str())
1679        .ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
1680    // 1.1 entries open with their header as associated data, so a changed
1681    // label, time, sequence number or link fails to decrypt. 1.0 entries were
1682    // written before the header was bound and open without it.
1683    let aad = match obj.get("version").and_then(|v| v.as_str()) {
1684        Some(BLACKBOX_VERSION) => entry_aad(obj),
1685        Some(BLACKBOX_LEGACY_VERSION) => Vec::new(),
1686        other => {
1687            return Err(CoreError::Json(format!(
1688                "unsupported black-box entry version {other:?}"
1689            )))
1690        }
1691    };
1692    let blob = unmb64(ct_mb)?;
1693    if blob.len() < 12 + 16 {
1694        return Err(CoreError::Crypto("ciphertext too short".into()));
1695    }
1696    let cipher =
1697        Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
1698    let (nonce, rest) = blob.split_at(12);
1699    let pt = cipher
1700        .decrypt(
1701            Nonce::from_slice(nonce),
1702            Payload {
1703                msg: rest,
1704                aad: &aad,
1705            },
1706        )
1707        .map_err(|_| CoreError::Crypto("decryption failed".into()))?;
1708    crate::nesting::check_text(&pt)?;
1709    serde_json::from_slice(&pt).map_err(|e| CoreError::Json(format!("payload decode: {e}")))
1710}
1711
1712/// The outcome of [`verify_blackbox_chain`].
1713#[derive(Debug, Clone)]
1714pub struct ChainResult {
1715    pub ok: bool,
1716    pub reason: Option<String>,
1717}
1718
1719/// Verify the hash chain over the (still-encrypted) entries. Tamper-evident
1720/// without the key. A `None` genesis uses [`genesis_prev_hash`].
1721pub fn verify_blackbox_chain(
1722    entries: &[Value],
1723    genesis_prev_hash_override: Option<&str>,
1724) -> ChainResult {
1725    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
1726    verify_blackbox_chain_capped(entries, genesis_prev_hash_override, MAX_LOG_BYTES)
1727}
1728
1729/// [`verify_blackbox_chain`] with the host's size limit for the log.
1730pub fn verify_blackbox_chain_capped(
1731    entries: &[Value],
1732    genesis_prev_hash_override: Option<&str>,
1733    max_bytes: usize,
1734) -> ChainResult {
1735    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
1736    let mut progress = ChainProgress::start(genesis_prev_hash_override);
1737    verify_chain_segment(&mut progress, entries, max_bytes);
1738    progress.result()
1739}
1740
1741/// Where a hash-chain check stands after the first entries of a log: the
1742/// number the next entry must carry, the hash it must link to, and the first
1743/// failure. A long log is checked one segment at a time by passing this from
1744/// one [`verify_chain_segment`] call to the next, so memory stays bounded by
1745/// one segment however long the log is. The verdict is the one
1746/// [`verify_blackbox_chain`] gives for the whole log.
1747#[derive(Debug, Clone, PartialEq, Eq)]
1748pub struct ChainProgress {
1749    /// The prevHash of entry 0.
1750    pub genesis: String,
1751    /// The number of entries checked so far (the next entry's seq).
1752    pub next_seq: u64,
1753    /// The entryHash of the last entry checked, or the genesis.
1754    pub last_hash: String,
1755    /// The first failure; once set, later segments are not read.
1756    pub failure: Option<String>,
1757}
1758
1759impl ChainProgress {
1760    /// The start of a log. A `None` genesis uses [`genesis_prev_hash`].
1761    pub fn start(genesis_prev_hash_override: Option<&str>) -> Self {
1762        let genesis = genesis_prev_hash_override
1763            .map(String::from)
1764            .unwrap_or_else(genesis_prev_hash);
1765        Self {
1766            last_hash: genesis.clone(),
1767            genesis,
1768            next_seq: 0,
1769            failure: None,
1770        }
1771    }
1772
1773    /// The verdict over every entry checked so far.
1774    pub fn result(&self) -> ChainResult {
1775        ChainResult {
1776            ok: self.failure.is_none(),
1777            reason: self.failure.clone(),
1778        }
1779    }
1780}
1781
1782/// The reason a segment of log entries nests too deeply or is larger than
1783/// `max_bytes`, measured as [`rv::input_too_large`] measures the same entries
1784/// in one list, without copying them.
1785fn entries_too_large(entries: &[Value], max_bytes: usize) -> Option<String> {
1786    use crate::attenuation::json_nesting_exceeds;
1787    if entries
1788        .iter()
1789        .any(|e| json_nesting_exceeds(e, rv::MAX_NESTING - 1))
1790    {
1791        return Some(format!("input nests more than {} levels", rv::MAX_NESTING));
1792    }
1793    let mut total = 2 + entries.len();
1794    for e in entries {
1795        if total > max_bytes {
1796            break;
1797        }
1798        total += rv::approx_size(e, max_bytes - total);
1799    }
1800    if total > max_bytes {
1801        return Some(format!("input larger than {max_bytes} bytes"));
1802    }
1803    None
1804}
1805
1806/// Check the next `entries` of a log (one segment) and move `progress` past
1807/// them. Every hash-linked log (black box, safety ledger, perception log)
1808/// verifies through here, whole or in segments.
1809pub fn verify_chain_segment(progress: &mut ChainProgress, entries: &[Value], max_bytes: usize) {
1810    #[cfg(not(feature = "std"))]
1811    if crate::nesting::Nested::nests_past(&entries, crate::nesting::NO_STD_MAX_NESTING) {
1812        progress
1813            .failure
1814            .get_or_insert_with(|| crate::nesting::TOO_DEEP.into());
1815        return;
1816    }
1817    #[cfg(not(feature = "std"))]
1818    if crate::nesting::Nested::nests_past(&entries, crate::nesting::NO_STD_MAX_NESTING) {
1819        progress
1820            .failure
1821            .get_or_insert_with(|| crate::nesting::TOO_DEEP.into());
1822        return;
1823    }
1824    if progress.failure.is_some() {
1825        return;
1826    }
1827    if let Some(big) = entries_too_large(entries, max_bytes) {
1828        progress.failure = Some(big);
1829        return;
1830    }
1831    for entry in entries {
1832        let i = progress.next_seq;
1833        let obj = match entry.as_object() {
1834            Some(o) => o,
1835            None => {
1836                progress.failure = Some(format!("entry {i} is not an object"));
1837                return;
1838            }
1839        };
1840        if entry.get("seq").and_then(|v| v.as_u64()) != Some(i) {
1841            progress.failure = Some(format!("entry {i} seq mismatch"));
1842            return;
1843        }
1844        if entry.get("prevHash").and_then(|v| v.as_str()).unwrap_or("") != progress.last_hash {
1845            progress.failure = Some(format!("entry {i} prevHash does not link"));
1846            return;
1847        }
1848        let want = match entry_hash(obj) {
1849            Ok(w) => w,
1850            Err(_) => {
1851                progress.failure = Some(format!("entry {i} hash error"));
1852                return;
1853            }
1854        };
1855        let eh = entry
1856            .get("entryHash")
1857            .and_then(|v| v.as_str())
1858            .unwrap_or("");
1859        if eh != want {
1860            progress.failure = Some(format!("entry {i} entryHash mismatch (tampered)"));
1861            return;
1862        }
1863        // A resumed state can carry any number; one past u64::MAX is no seq.
1864        let Some(next) = progress.next_seq.checked_add(1) else {
1865            progress.failure = Some(format!("entry {i} seq mismatch"));
1866            return;
1867        };
1868        progress.last_hash = want;
1869        progress.next_seq = next;
1870    }
1871}
1872
1873/// The end of a segmented check against a signed head: the same verdict
1874/// [`verify_chain_against_head`] gives for the whole log.
1875pub fn finish_chain_against_head(
1876    progress: &ChainProgress,
1877    head: Option<&Value>,
1878    count: Option<&Value>,
1879) -> ChainResult {
1880    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; head, count);
1881    if progress.failure.is_some() {
1882        return progress.result();
1883    }
1884    let fail = |r: String| ChainResult {
1885        ok: false,
1886        reason: Some(r),
1887    };
1888    let n = match count.and_then(|c| rv::strict_int(Some(c))) {
1889        Some(n) if n >= 0 => n,
1890        _ => return fail("anchored count is not a non-negative integer".into()),
1891    };
1892    if i128::from(progress.next_seq) != i128::from(n) {
1893        return fail(format!(
1894            "log has {} entries, the signed head says {n}",
1895            progress.next_seq
1896        ));
1897    }
1898    if head.and_then(|h| h.as_str()) != Some(progress.last_hash.as_str()) {
1899        return fail("log does not end at the signed head".into());
1900    }
1901    ChainResult {
1902        ok: true,
1903        reason: None,
1904    }
1905}
1906
1907/// Parameters for [`build_killswitch_credential`].
1908#[derive(Debug, Clone, Default)]
1909pub struct BuildKillswitch {
1910    pub issuer_did: String,
1911    pub target: String,
1912    pub reason: String,
1913    pub command: Option<String>,
1914    pub scope: Option<Vec<String>>,
1915    pub valid_from: String,
1916    pub valid_until: Option<String>,
1917}
1918
1919/// Build a signed `KillSwitchCredential` proving who issued an emergency stop.
1920pub fn build_killswitch_credential(
1921    authority_seed: &[u8],
1922    params: &BuildKillswitch,
1923) -> Result<Value> {
1924    let command = params
1925        .command
1926        .clone()
1927        .unwrap_or_else(|| EMERGENCY_STOP.to_string());
1928    let mut subject = Map::new();
1929    subject.insert("id".into(), json!(params.target));
1930    subject.insert("command".into(), json!(command));
1931    subject.insert("reason".into(), json!(params.reason));
1932    subject.insert("issuedBy".into(), json!(params.issuer_did));
1933    if let Some(scope) = &params.scope {
1934        subject.insert("scope".into(), json!(scope));
1935    }
1936
1937    let mut cred = Map::new();
1938    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1939    cred.insert(
1940        "type".into(),
1941        json!(["VerifiableCredential", KILLSWITCH_TYPE]),
1942    );
1943    cred.insert("issuer".into(), json!(params.issuer_did));
1944    cred.insert("validFrom".into(), json!(params.valid_from));
1945    if let Some(vu) = &params.valid_until {
1946        cred.insert("validUntil".into(), json!(vu));
1947    }
1948    cred.insert("credentialSubject".into(), Value::Object(subject));
1949
1950    let opts = BuildProofOptions::new(
1951        crate::verification_method::ed25519_method(&params.issuer_did),
1952        &params.valid_from,
1953    );
1954    data_integrity::sign(&Value::Object(cred), authority_seed, &opts)
1955}
1956
1957/// Verify a `KillSwitchCredential`. When `trusted_authorities` is supplied, the
1958/// issuer DID MUST be in it. Returns the subject on success.
1959pub fn verify_killswitch_credential(
1960    credential: &Value,
1961    keys: Keys<'_>,
1962    trusted_authorities: Option<&HashSet<String>>,
1963    now_iso: &str,
1964) -> Result<Option<Value>> {
1965    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
1966    let now = rv::require_now(now_iso)?;
1967    let opts = VerifyOptions {
1968        trusted_issuers: trusted_authorities,
1969        ..VerifyOptions::window(Window::FromRequired)
1970    };
1971    let v = match rv::verify_robotics_credential(credential, keys, Some(KILLSWITCH_TYPE), now, opts)
1972    {
1973        Ok(v) => v,
1974        Err(_) => return Ok(None),
1975    };
1976    // issuedBy, when present, must be the bound issuer.
1977    if let Some(by) = v.subject.get("issuedBy") {
1978        if by.as_str() != Some(v.issuer.as_str()) {
1979            return Ok(None);
1980        }
1981    }
1982    Ok(Some(v.subject))
1983}
1984
1985/// Verify the hash links AND that the log ends at a known head: `head` and
1986/// `count` come from something signed (a head credential, a safety-record
1987/// summary, a perception attestation). A log cut short, extended or rebuilt
1988/// does not end at that head with that many entries.
1989pub fn verify_chain_against_head(
1990    entries: &[Value],
1991    head: Option<&Value>,
1992    count: Option<&Value>,
1993    genesis_prev_hash_override: Option<&str>,
1994) -> ChainResult {
1995    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries, head, count);
1996    verify_chain_against_head_capped(
1997        entries,
1998        head,
1999        count,
2000        genesis_prev_hash_override,
2001        MAX_LOG_BYTES,
2002    )
2003}
2004
2005/// [`verify_chain_against_head`] with the host's size limit for the log.
2006pub fn verify_chain_against_head_capped(
2007    entries: &[Value],
2008    head: Option<&Value>,
2009    count: Option<&Value>,
2010    genesis_prev_hash_override: Option<&str>,
2011    max_bytes: usize,
2012) -> ChainResult {
2013    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries, head, count);
2014    let mut progress = ChainProgress::start(genesis_prev_hash_override);
2015    verify_chain_segment(&mut progress, entries, max_bytes);
2016    finish_chain_against_head(&progress, head, count)
2017}
2018
2019/// Sign the head of a black-box log (entry count plus last hash). The robot is
2020/// the issuer and the subject.
2021pub fn build_blackbox_head(
2022    robot_seed: &[u8],
2023    robot_did: &str,
2024    head: &str,
2025    entry_count: u64,
2026    valid_from: &str,
2027    valid_until: Option<&str>,
2028) -> Result<Value> {
2029    let mut cred = Map::new();
2030    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2031    cred.insert(
2032        "type".into(),
2033        json!(["VerifiableCredential", BLACKBOX_HEAD_TYPE]),
2034    );
2035    cred.insert("issuer".into(), json!(robot_did));
2036    cred.insert("validFrom".into(), json!(valid_from));
2037    if let Some(vu) = valid_until {
2038        cred.insert("validUntil".into(), json!(vu));
2039    }
2040    cred.insert(
2041        "credentialSubject".into(),
2042        json!({"id": robot_did, "logHead": head, "entryCount": entry_count}),
2043    );
2044    let opts = BuildProofOptions::new(
2045        crate::verification_method::ed25519_method(robot_did),
2046        valid_from,
2047    );
2048    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
2049}
2050
2051/// Verify a log against the robot's signed head: the head credential must
2052/// verify bound to the robot as issuer and subject, and the log must link and
2053/// end at the signed head with exactly the signed number of entries.
2054pub fn verify_blackbox_head(
2055    credential: &Value,
2056    robot_keys: Keys<'_>,
2057    entries: &[Value],
2058    genesis_prev_hash_override: Option<&str>,
2059    now_iso: &str,
2060) -> Result<ChainResult> {
2061    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, entries);
2062    let mut progress = ChainProgress::start(genesis_prev_hash_override);
2063    verify_chain_segment(&mut progress, entries, MAX_LOG_BYTES);
2064    finish_chain_against_head_credential(credential, robot_keys, &progress, now_iso)
2065}
2066
2067/// The end of a segmented check against the robot's signed head credential:
2068/// the same verdict [`verify_blackbox_head`] gives for the whole log.
2069pub fn finish_chain_against_head_credential(
2070    credential: &Value,
2071    robot_keys: Keys<'_>,
2072    progress: &ChainProgress,
2073    now_iso: &str,
2074) -> Result<ChainResult> {
2075    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
2076    let now = rv::require_now(now_iso)?;
2077    let v = match rv::verify_robotics_credential(
2078        credential,
2079        robot_keys,
2080        Some(BLACKBOX_HEAD_TYPE),
2081        now,
2082        VerifyOptions::window(Window::FromRequired),
2083    ) {
2084        Ok(v) => v,
2085        Err(r) => {
2086            return Ok(ChainResult {
2087                ok: false,
2088                reason: Some(r),
2089            })
2090        }
2091    };
2092    if !issuer_is_subject(&v) {
2093        return Ok(ChainResult {
2094            ok: false,
2095            reason: Some("head is not issued by the robot it describes".into()),
2096        });
2097    }
2098    Ok(finish_chain_against_head(
2099        progress,
2100        v.subject.get("logHead"),
2101        v.subject.get("entryCount"),
2102    ))
2103}
2104
2105// ---------------------------------------------------------------------------
2106// Halos safety-evidence recorder (NVIDIA Halos integration)
2107// ---------------------------------------------------------------------------
2108//
2109// Byte-exact port of the Python reference `vouch/robotics/halos.py`.
2110//
2111// Halos certifies that a robot's stack is functionally safe and secure by design.
2112// It does not, on its own, produce a verifiable record of what a specific robot
2113// did or bind that record to the robot's identity. This is the evidence layer
2114// under a Halos-certified stack: the robot seals its black-box chain head and
2115// entry count into a signed `HalosSafetyEvidenceCredential` that binds them to its
2116// identity, to the Halos stack elements it ran on, and to a time window. A
2117// verifier that holds the credential and the entries confirms, without the
2118// black-box key, that the record is unaltered, was not truncated or extended since
2119// it was sealed, and is attributable to that robot. This composes the existing
2120// black-box and credential primitives and adds no new cryptography.
2121
2122pub const HALOS_SAFETY_EVIDENCE_TYPE: &str = "HalosSafetyEvidenceCredential";
2123
2124/// Format Unix epoch seconds as "YYYY-MM-DDTHH:MM:SSZ" for a whole-second UTC
2125/// instant. Howard Hinnant's civil-from-days algorithm, matching the rest of the
2126/// core so a `valid_seconds` lifetime renders identically across languages.
2127fn halos_epoch_to_iso(epoch: i64) -> String {
2128    let days = epoch.div_euclid(86400);
2129    let secs = epoch.rem_euclid(86400);
2130    let z = days + 719468;
2131    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
2132    let doe = z - era * 146097;
2133    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2134    let y = yoe + era * 400;
2135    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2136    let mp = (5 * doy + 2) / 153;
2137    let d = doy - (153 * mp + 2) / 5 + 1;
2138    let m = if mp < 10 { mp + 3 } else { mp - 9 };
2139    let year = if m <= 2 { y + 1 } else { y };
2140    let hh = secs / 3600;
2141    let mm = (secs % 3600) / 60;
2142    let ss = secs % 60;
2143    format!("{year:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
2144}
2145
2146/// Parameters for [`build_safety_evidence`]. The robot DID is derived from
2147/// `signer_seed` (a did:key), mirroring the Python signer. `blackbox_head` and
2148/// `entry_count` seal the robot's black-box chain; `halos_stack` names the
2149/// certified configuration; `window` covers the recorded events. Timestamps are
2150/// caller-supplied ISO-8601 strings.
2151#[derive(Debug, Clone)]
2152pub struct BuildSafetyEvidence {
2153    pub halos_stack: Value,
2154    pub window_from: String,
2155    pub window_to: String,
2156    pub blackbox_head: String,
2157    pub entry_count: u64,
2158    pub robot_identity: Option<String>,
2159    pub valid_seconds: Option<i64>,
2160    pub valid_from: String,
2161    pub created: String,
2162    /// The robot's DID, when it is not the did:key of the signing key (a
2163    /// did:web robot); without it the issuer is that did:key.
2164    pub robot_did: Option<String>,
2165}
2166
2167/// Seal a robot's Halos safety-event record into a signed
2168/// `HalosSafetyEvidenceCredential`. The robot signs a credential binding the
2169/// black-box chain head and entry count to its identity, to the Halos stack
2170/// elements it ran on, and to the time window.
2171pub fn build_safety_evidence(signer_seed: &[u8], params: &BuildSafetyEvidence) -> Result<Value> {
2172    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
2173    match params.halos_stack.as_object() {
2174        Some(o) if !o.is_empty() => {}
2175        _ => return Err(CoreError::Json("halos_stack is required".into())),
2176    }
2177    if params.window_from.is_empty() || params.window_to.is_empty() {
2178        return Err(CoreError::Json(
2179            "window with 'from' and 'to' is required".into(),
2180        ));
2181    }
2182
2183    let robot_did = match params.robot_did.as_deref().filter(|d| !d.is_empty()) {
2184        Some(d) if d.starts_with("did:") => d.to_string(),
2185        Some(_) => return Err(CoreError::Json("robot_did must be a DID".into())),
2186        None => {
2187            let kp = keys::Ed25519KeyPair::from_seed_slice(signer_seed)?;
2188            keys::ed25519_to_did_key(&kp.public_key())?
2189        }
2190    };
2191
2192    let mut subject = Map::new();
2193    subject.insert("id".into(), json!(robot_did));
2194    subject.insert("blackboxHead".into(), json!(params.blackbox_head));
2195    subject.insert("entryCount".into(), json!(params.entry_count));
2196    subject.insert("halosStack".into(), params.halos_stack.clone());
2197    subject.insert(
2198        "window".into(),
2199        json!({ "from": params.window_from, "to": params.window_to }),
2200    );
2201    if let Some(robot_identity) = &params.robot_identity {
2202        subject.insert("robotIdentity".into(), json!(robot_identity));
2203    }
2204
2205    let mut cred = Map::new();
2206    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2207    cred.insert(
2208        "type".into(),
2209        json!(["VerifiableCredential", HALOS_SAFETY_EVIDENCE_TYPE]),
2210    );
2211    cred.insert("issuer".into(), json!(robot_did));
2212    cred.insert("validFrom".into(), json!(params.valid_from));
2213    if let Some(valid_seconds) = params.valid_seconds {
2214        let from = crate::time::iso_to_epoch_seconds(&params.valid_from)?;
2215        cred.insert(
2216            "validUntil".into(),
2217            json!(halos_epoch_to_iso(from + valid_seconds)),
2218        );
2219    }
2220    cred.insert("credentialSubject".into(), Value::Object(subject));
2221
2222    let opts = BuildProofOptions::new(
2223        crate::verification_method::ed25519_method(&robot_did),
2224        &params.created,
2225    );
2226    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2227}
2228
2229/// Verify a `HalosSafetyEvidenceCredential`: the robot's proof and that the issuer
2230/// is the robot (`credentialSubject.id`). When `entries` is supplied, also checks
2231/// that the black-box chain is intact, that its length matches the sealed entry
2232/// count, and that its head matches the sealed head, so a truncated, extended,
2233/// reordered, or tampered record is rejected. Returns `(ok, credentialSubject)`.
2234pub fn verify_safety_evidence(
2235    credential: &Value,
2236    robot_keys: Keys<'_>,
2237    entries: Option<&[Value]>,
2238    now_iso: &str,
2239) -> Result<(bool, Option<Value>)> {
2240    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, entries);
2241    let v = match bound(
2242        credential,
2243        robot_keys,
2244        HALOS_SAFETY_EVIDENCE_TYPE,
2245        now_iso,
2246        Window::FromRequired,
2247    )? {
2248        Some(v) if issuer_is_subject(&v) => v,
2249        _ => return Ok((false, None)),
2250    };
2251    let subject = v.subject;
2252    let count = match rv::strict_int(subject.get("entryCount")) {
2253        Some(n) if n >= 0 => n,
2254        _ => return Ok((false, None)),
2255    };
2256
2257    if let Some(entries) = entries {
2258        if !verify_blackbox_chain(entries, None).ok {
2259            return Ok((false, None));
2260        }
2261        if count != entries.len() as i64 {
2262            return Ok((false, None));
2263        }
2264        let head = match entries.last() {
2265            Some(last) => last
2266                .get("entryHash")
2267                .and_then(|v| v.as_str())
2268                .unwrap_or("")
2269                .to_string(),
2270            None => genesis_prev_hash(),
2271        };
2272        if Some(head.as_str()) != subject.get("blackboxHead").and_then(|v| v.as_str()) {
2273            return Ok((false, None));
2274        }
2275    }
2276
2277    Ok((true, Some(subject)))
2278}
2279
2280// ---------------------------------------------------------------------------
2281// Scannable robot passport (Phase 5.6)
2282// ---------------------------------------------------------------------------
2283
2284pub const ROBOT_PASSPORT_TYPE: &str = "RobotPassport";
2285pub const PASSPORT_URI_SCHEME: &str = "vouch-passport:";
2286pub const STATUS_ACTIVE: &str = "active";
2287pub const STATUS_SUSPENDED: &str = "suspended";
2288pub const STATUS_DECOMMISSIONED: &str = "decommissioned";
2289
2290/// Parameters for [`build_passport`]. The issuer is the signer (the robot or an
2291/// authority); `robot_did` is the robot the passport describes.
2292#[derive(Debug, Clone, Default)]
2293pub struct BuildPassport {
2294    pub issuer_did: String,
2295    pub robot_did: String,
2296    pub make: String,
2297    pub model: String,
2298    pub owner: String,
2299    pub authorized_actions: Vec<String>,
2300    pub certification: Option<String>,
2301    pub status: Option<String>,
2302    pub valid_from: String,
2303    pub valid_until: Option<String>,
2304}
2305
2306/// Build a signed `RobotPassport` credential.
2307pub fn build_passport(signer_seed: &[u8], params: &BuildPassport) -> Result<Value> {
2308    let status = params
2309        .status
2310        .clone()
2311        .unwrap_or_else(|| STATUS_ACTIVE.to_string());
2312    let mut subject = Map::new();
2313    subject.insert("id".into(), json!(params.robot_did));
2314    subject.insert("make".into(), json!(params.make));
2315    subject.insert("model".into(), json!(params.model));
2316    subject.insert("owner".into(), json!(params.owner));
2317    subject.insert("authorizedActions".into(), json!(params.authorized_actions));
2318    subject.insert("status".into(), json!(status));
2319    if let Some(c) = &params.certification {
2320        subject.insert("certification".into(), json!(c));
2321    }
2322
2323    let mut cred = Map::new();
2324    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2325    cred.insert(
2326        "type".into(),
2327        json!(["VerifiableCredential", ROBOT_PASSPORT_TYPE]),
2328    );
2329    cred.insert("issuer".into(), json!(params.issuer_did));
2330    cred.insert("validFrom".into(), json!(params.valid_from));
2331    if let Some(vu) = &params.valid_until {
2332        cred.insert("validUntil".into(), json!(vu));
2333    }
2334    cred.insert("credentialSubject".into(), Value::Object(subject));
2335
2336    let opts = BuildProofOptions::new(
2337        crate::verification_method::ed25519_method(&params.issuer_did),
2338        &params.valid_from,
2339    );
2340    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2341}
2342
2343/// Encode a passport into a compact `vouch-passport:` URI for a QR or NFC tag.
2344pub fn encode_passport(passport: &Value) -> String {
2345    format!(
2346        "{}{}",
2347        PASSPORT_URI_SCHEME,
2348        mb64(&jcs::canonicalize(passport))
2349    )
2350}
2351
2352/// Decode a `vouch-passport:` URI back into the passport credential.
2353pub fn decode_passport(uri: &str) -> Result<Value> {
2354    let body = uri
2355        .strip_prefix(PASSPORT_URI_SCHEME)
2356        .ok_or_else(|| CoreError::Json(format!("not a {PASSPORT_URI_SCHEME} URI")))?;
2357    if body.len() > 2 * rv::MAX_CREDENTIAL_BYTES {
2358        return Err(CoreError::Json("passport URI too large".into()));
2359    }
2360    let raw = unmb64(body)?;
2361    crate::nesting::check_text(&raw)?;
2362    let decoded: Value = serde_json::from_slice(&raw)
2363        .map_err(|e| CoreError::Json(format!("passport decode: {e}")))?;
2364    if !decoded.is_object() {
2365        return Err(CoreError::Json("passport payload is not an object".into()));
2366    }
2367    Ok(decoded)
2368}
2369
2370/// Verify a passport: the proof bound to the issuer (`keys` is a `{did: key}`
2371/// source, or the bare key of a did:key issuer), the validity window at
2372/// `now_iso` (validFrom required, strict times), `authorizedActions` a list of
2373/// strings, and (when given) the issuer in `trusted_issuers`. A suspended or
2374/// decommissioned status still verifies; the caller reads it from the subject.
2375pub fn verify_passport(
2376    passport: &Value,
2377    keys: Keys<'_>,
2378    trusted_issuers: Option<&HashSet<String>>,
2379    now_iso: &str,
2380) -> Result<Option<Value>> {
2381    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); passport);
2382    let now = rv::require_now(now_iso)?;
2383    let opts = VerifyOptions {
2384        trusted_issuers,
2385        ..VerifyOptions::window(Window::FromRequired)
2386    };
2387    let v = match rv::verify_robotics_credential(
2388        passport,
2389        keys,
2390        Some(ROBOT_PASSPORT_TYPE),
2391        now,
2392        opts,
2393    ) {
2394        Ok(v) => v,
2395        Err(_) => return Ok(None),
2396    };
2397    match v.subject.get("authorizedActions") {
2398        None => {}
2399        Some(Value::Array(a)) if a.iter().all(|x| x.is_string()) => {}
2400        _ => return Ok(None),
2401    }
2402    Ok(Some(v.subject))
2403}
2404
2405pub fn verify_passport_uri(
2406    uri: &str,
2407    keys: Keys<'_>,
2408    trusted_issuers: Option<&HashSet<String>>,
2409    now_iso: &str,
2410) -> Result<Option<Value>> {
2411    rv::require_now(now_iso)?;
2412    match decode_passport(uri) {
2413        Ok(p) => verify_passport(&p, keys, trusted_issuers, now_iso),
2414        Err(_) => Ok(None),
2415    }
2416}
2417
2418/// Verify a passport (a credential object or a `vouch-passport:` URI) as
2419/// [`verify_passport`] does and return the human-facing summary the Python
2420/// reference returns: robot, make, model, owner, authorizedActions,
2421/// certification, status, and the verified `issuer`.
2422pub fn verify_passport_summary(
2423    passport: &Value,
2424    keys: Keys<'_>,
2425    trusted_issuers: Option<&HashSet<String>>,
2426    now_iso: &str,
2427) -> Result<Option<Value>> {
2428    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); passport);
2429    let cred = match passport {
2430        Value::String(uri) => match decode_passport(uri) {
2431            Ok(p) => p,
2432            Err(_) => return Ok(None),
2433        },
2434        other => other.clone(),
2435    };
2436    let subject = match verify_passport(&cred, keys, trusted_issuers, now_iso)? {
2437        Some(s) => s,
2438        None => return Ok(None),
2439    };
2440    let issuer = rv::issuer_id(cred.get("issuer")).unwrap_or("").to_string();
2441    let g = |k: &str| subject.get(k).cloned().unwrap_or(Value::Null);
2442    Ok(Some(json!({
2443        "robot": g("id"),
2444        "make": g("make"),
2445        "model": g("model"),
2446        "owner": g("owner"),
2447        "authorizedActions": subject.get("authorizedActions").cloned().unwrap_or(json!([])),
2448        "certification": g("certification"),
2449        "status": g("status"),
2450        "issuer": issuer,
2451    })))
2452}
2453
2454// ---------------------------------------------------------------------------
2455// Liveness heartbeat with safety-envelope conformance (Phase 5.7)
2456// ---------------------------------------------------------------------------
2457
2458pub const ROBOT_HEARTBEAT_TYPE: &str = "RobotHeartbeatCredential";
2459
2460/// Default number of missed intervals tolerated before trust is considered stale.
2461pub const DEFAULT_GRACE_INTERVALS: i64 = 2;
2462
2463/// One observed motion sample. `None` numerics mean "not specified" (a meaningful
2464/// zero is still `Some(0.0)`), matching [`PhysicalAction`].
2465#[derive(Debug, Clone, Default)]
2466pub struct MotionSample {
2467    pub force_n: Option<f64>,
2468    pub speed_mps: Option<f64>,
2469    pub near_humans: bool,
2470    pub zone: Option<String>,
2471    pub time_hm: Option<String>,
2472}
2473
2474/// Collector for per-interval motion telemetry. It accumulates aggregates of what
2475/// the robot physically did over a heartbeat interval and, when given a physical
2476/// scope, counts how many samples fell outside the declared envelope. The
2477/// physical analogue of the agent behavioral digest.
2478///
2479/// With `scope` set to `None` the digest still reports observed maxima but cannot
2480/// judge conformance, so it reports `withinEnvelope` true with a zero breach
2481/// count, mirroring the Python `MotionCollector`.
2482#[derive(Debug, Clone, Default)]
2483pub struct MotionCollector {
2484    scope: Option<Value>,
2485    samples: u64,
2486    max_force: f64,
2487    max_speed: f64,
2488    max_speed_near: f64,
2489    zone_breaches: u64,
2490    breaches: u64,
2491}
2492
2493impl MotionCollector {
2494    /// A collector that judges samples against `scope` (the
2495    /// `credentialSubject.physicalScope` object). Pass `None` to only aggregate.
2496    pub fn new(scope: Option<Value>) -> Self {
2497        Self {
2498            scope,
2499            ..Default::default()
2500        }
2501    }
2502
2503    /// Record a single observed motion sample, updating the running aggregates and
2504    /// (when a scope is set) the breach counts.
2505    pub fn record(&mut self, sample: &MotionSample) -> Result<()> {
2506        crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); self);
2507        if let Some(f) = sample.force_n {
2508            if !f.is_finite() || f < 0.0 {
2509                return Err(CoreError::Json(format!(
2510                    "force_n must be a finite non-negative number, got {f}"
2511                )));
2512            }
2513        }
2514        if let Some(s) = sample.speed_mps {
2515            if !s.is_finite() || s < 0.0 {
2516                return Err(CoreError::Json(format!(
2517                    "speed_mps must be a finite non-negative number, got {s}"
2518                )));
2519            }
2520        }
2521
2522        self.samples += 1;
2523        if let Some(f) = sample.force_n {
2524            self.max_force = self.max_force.max(f);
2525        }
2526        if let Some(s) = sample.speed_mps {
2527            self.max_speed = self.max_speed.max(s);
2528            if sample.near_humans {
2529                self.max_speed_near = self.max_speed_near.max(s);
2530            }
2531        }
2532
2533        if let Some(scope) = &self.scope {
2534            let action = PhysicalAction {
2535                force_n: sample.force_n,
2536                speed_mps: sample.speed_mps,
2537                near_humans: sample.near_humans,
2538                zone: sample.zone.clone(),
2539                time_hm: sample.time_hm.clone(),
2540            };
2541            let result = check_physical_action(scope, &action);
2542            if !result.ok {
2543                self.breaches += 1;
2544                if result
2545                    .reasons
2546                    .iter()
2547                    .any(|r| r.starts_with("zone_not_allowed"))
2548                {
2549                    self.zone_breaches += 1;
2550                }
2551            }
2552        }
2553        Ok(())
2554    }
2555
2556    /// Return the `motionDigest` object for embedding in a heartbeat credential.
2557    pub fn digest(&self) -> Value {
2558        crate::nesting::deep_guard!(Value::Null; self);
2559        json!({
2560            "samples": self.samples,
2561            "maxForceN": self.max_force,
2562            "maxSpeedMps": self.max_speed,
2563            "maxSpeedNearHumansMps": self.max_speed_near,
2564            "zoneBreaches": self.zone_breaches,
2565            "breachCount": self.breaches,
2566            "withinEnvelope": self.breaches == 0,
2567        })
2568    }
2569
2570    /// Clear all state. Call after submitting a heartbeat to start fresh.
2571    pub fn reset(&mut self) {
2572        self.samples = 0;
2573        self.max_force = 0.0;
2574        self.max_speed = 0.0;
2575        self.max_speed_near = 0.0;
2576        self.zone_breaches = 0;
2577        self.breaches = 0;
2578    }
2579}
2580
2581fn digest_non_negative_int(digest: &Map<String, Value>, name: &str) -> Result<()> {
2582    match digest.get(name) {
2583        Some(v) if v.is_u64() => Ok(()),
2584        Some(Value::Number(n)) if n.as_i64().map(|i| i >= 0).unwrap_or(false) => Ok(()),
2585        Some(_) => Err(CoreError::Json(format!(
2586            "motionDigest.{name} must be a non-negative integer"
2587        ))),
2588        None => Err(CoreError::Json(format!("motionDigest.{name} is required"))),
2589    }
2590}
2591
2592/// Structural validation of a `motionDigest` object. Does not judge whether the
2593/// values are acceptable; that is policy, expressed through [`is_live`].
2594pub fn validate_motion_digest(digest: &Value) -> Result<()> {
2595    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); digest);
2596    let obj = digest
2597        .as_object()
2598        .ok_or_else(|| CoreError::Json("motionDigest must be an object".into()))?;
2599
2600    for name in ["samples", "zoneBreaches", "breachCount"] {
2601        digest_non_negative_int(obj, name)?;
2602    }
2603    for name in ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"] {
2604        match obj.get(name) {
2605            Some(Value::Bool(_)) | None => {
2606                return Err(CoreError::Json(format!("motionDigest.{name} is required")))
2607            }
2608            Some(v) => {
2609                let n = rv::finite_number(Some(v)).ok_or_else(|| {
2610                    CoreError::Json(format!("motionDigest.{name} must be a finite number"))
2611                })?;
2612                if n < 0.0 {
2613                    return Err(CoreError::Json(format!(
2614                        "motionDigest.{name} must be non-negative"
2615                    )));
2616                }
2617            }
2618        }
2619    }
2620    let within = match obj.get("withinEnvelope") {
2621        Some(Value::Bool(b)) => *b,
2622        Some(_) => {
2623            return Err(CoreError::Json(
2624                "motionDigest.withinEnvelope must be a boolean".into(),
2625            ))
2626        }
2627        None => {
2628            return Err(CoreError::Json(
2629                "motionDigest.withinEnvelope is required".into(),
2630            ))
2631        }
2632    };
2633    let n = |k: &str| obj.get(k).and_then(|v| v.as_u64()).unwrap_or(0);
2634    if within != (n("breachCount") == 0) {
2635        return Err(CoreError::Json(
2636            "motionDigest.withinEnvelope disagrees with breachCount".into(),
2637        ));
2638    }
2639    if n("zoneBreaches") > n("breachCount") {
2640        return Err(CoreError::Json(
2641            "motionDigest.zoneBreaches exceeds breachCount".into(),
2642        ));
2643    }
2644    Ok(())
2645}
2646
2647/// The longest heartbeat cadence a verifier accepts from the heartbeat itself.
2648pub const MAX_INTERVAL_SECONDS: i64 = 3600;
2649
2650/// Parameters for [`build_robot_heartbeat`]. The robot self-issues the credential
2651/// with its own Ed25519 seed; `motion_digest` is produced by a [`MotionCollector`]
2652/// over the interval and `interval_seconds` is the declared heartbeat cadence.
2653#[derive(Debug, Clone)]
2654pub struct BuildRobotHeartbeat {
2655    pub robot_did: String,
2656    pub session_id: String,
2657    pub interval_index: i64,
2658    pub interval_seconds: i64,
2659    pub motion_digest: Value,
2660    pub valid_from: String,
2661}
2662
2663/// Build a signed `RobotHeartbeatCredential`.
2664pub fn build_robot_heartbeat(robot_seed: &[u8], params: &BuildRobotHeartbeat) -> Result<Value> {
2665    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
2666    if params.interval_index < 0 {
2667        return Err(CoreError::Json(
2668            "interval_index must be non-negative".into(),
2669        ));
2670    }
2671    if params.interval_seconds <= 0 {
2672        return Err(CoreError::Json("interval_seconds must be positive".into()));
2673    }
2674    validate_motion_digest(&params.motion_digest)?;
2675
2676    let mut subject = Map::new();
2677    subject.insert("id".into(), json!(params.robot_did));
2678    subject.insert("sessionId".into(), json!(params.session_id));
2679    subject.insert("intervalIndex".into(), json!(params.interval_index));
2680    subject.insert("intervalSeconds".into(), json!(params.interval_seconds));
2681    subject.insert("motionDigest".into(), params.motion_digest.clone());
2682
2683    let mut cred = Map::new();
2684    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2685    cred.insert(
2686        "type".into(),
2687        json!(["VerifiableCredential", ROBOT_HEARTBEAT_TYPE]),
2688    );
2689    cred.insert("issuer".into(), json!(params.robot_did));
2690    cred.insert("validFrom".into(), json!(params.valid_from));
2691    cred.insert("credentialSubject".into(), Value::Object(subject));
2692
2693    let opts = BuildProofOptions::new(
2694        crate::verification_method::ed25519_method(&params.robot_did),
2695        &params.valid_from,
2696    );
2697    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
2698}
2699
2700/// Verify a `RobotHeartbeatCredential`: the credential proof bound to the robot
2701/// as issuer (which must also be `credentialSubject.id`), a validFrom no later
2702/// than `now_iso`, and the structural validity of the embedded motion digest. Returns the subject on
2703/// success. Whether the robot is currently trusted is a separate, time-dependent
2704/// question answered by [`is_live`].
2705pub fn verify_robot_heartbeat(
2706    credential: &Value,
2707    robot_keys: Keys<'_>,
2708    now_iso: &str,
2709) -> Result<Option<Value>> {
2710    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
2711    let v = match bound(
2712        credential,
2713        robot_keys,
2714        ROBOT_HEARTBEAT_TYPE,
2715        now_iso,
2716        Window::FromRequired,
2717    )? {
2718        Some(v) if issuer_is_subject(&v) => v,
2719        _ => return Ok(None),
2720    };
2721    let digest = v
2722        .subject
2723        .get("motionDigest")
2724        .cloned()
2725        .unwrap_or(Value::Null);
2726    if validate_motion_digest(&digest).is_err() {
2727        return Ok(None);
2728    }
2729    Ok(Some(v.subject))
2730}
2731
2732/// Decide whether a robot is currently trusted, given its most recent heartbeat
2733/// (verify it with [`verify_robot_heartbeat`] first). Live only when: the
2734/// heartbeat was issued within `grace_intervals` cadence periods of `now_iso`
2735/// (the cadence is the verifier's `interval_seconds` when given, else the
2736/// heartbeat's declared interval capped at [`MAX_INTERVAL_SECONDS`]); the
2737/// motion digest covers at least one sample; and the digest is well-formed and
2738/// reports withinEnvelope true. Malformed input returns `false`.
2739pub fn is_live(
2740    credential: &Value,
2741    now_iso: &str,
2742    interval_seconds: Option<i64>,
2743    grace_intervals: i64,
2744) -> Result<bool> {
2745    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
2746    is_live_capped(
2747        credential,
2748        now_iso,
2749        interval_seconds,
2750        grace_intervals,
2751        MAX_INTERVAL_SECONDS,
2752    )
2753}
2754
2755/// [`is_live`] with the caller's cap on a declared cadence instead of
2756/// [`MAX_INTERVAL_SECONDS`].
2757pub fn is_live_capped(
2758    credential: &Value,
2759    now_iso: &str,
2760    interval_seconds: Option<i64>,
2761    grace_intervals: i64,
2762    max_interval_seconds: i64,
2763) -> Result<bool> {
2764    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
2765    if max_interval_seconds < 1 {
2766        return Err(CoreError::Json(
2767            "max_interval_seconds must be at least 1".into(),
2768        ));
2769    }
2770    if grace_intervals < 1 {
2771        return Err(CoreError::Json("grace_intervals must be at least 1".into()));
2772    }
2773    let subject = match credential
2774        .get("credentialSubject")
2775        .and_then(|s| s.as_object())
2776    {
2777        Some(s) => s,
2778        None => return Ok(false),
2779    };
2780    let digest = match subject.get("motionDigest") {
2781        Some(d) if validate_motion_digest(d).is_ok() => d,
2782        _ => return Ok(false),
2783    };
2784    if digest.get("samples").and_then(|v| v.as_u64()).unwrap_or(0) == 0
2785        || digest.get("withinEnvelope") != Some(&Value::Bool(true))
2786    {
2787        return Ok(false);
2788    }
2789    let cadence = match interval_seconds {
2790        Some(c) => c,
2791        None => match rv::strict_int(subject.get("intervalSeconds")) {
2792            Some(d) if d > 0 => d.min(max_interval_seconds),
2793            _ => return Ok(false),
2794        },
2795    };
2796    if cadence <= 0 {
2797        return Ok(false);
2798    }
2799    let issued = match rv::time_ns(credential.get("validFrom")) {
2800        Some(t) => t,
2801        None => return Ok(false),
2802    };
2803    let moment = match crate::time::parse_protocol_time_ns(now_iso) {
2804        Ok(t) => t,
2805        Err(_) => return Ok(false),
2806    };
2807    let cadence_ns = i128::from(cadence) * 1_000_000_000;
2808    // A heartbeat from the future (clock skew beyond one cadence) is not trusted.
2809    if moment + cadence_ns < issued {
2810        return Ok(false);
2811    }
2812    Ok(moment <= issued + cadence_ns * i128::from(grace_intervals))
2813}
2814
2815// ---------------------------------------------------------------------------
2816// Per-credential revocation (Phase 5.8)
2817// ---------------------------------------------------------------------------
2818
2819pub use crate::status_list::{BITSTRING_STATUS_LIST_ENTRY_TYPE, STATUS_PURPOSE_REVOCATION};
2820
2821/// Build a BitstringStatusList `credentialStatus` entry referencing a bit index in
2822/// a published status list credential. Mirrors the agent-side
2823/// `status_list.build_status_list_entry`. `entry_id`, when `None`, defaults to
2824/// `{status_list_credential}#{status_list_index}`.
2825pub fn build_status_list_entry(
2826    status_list_credential: &str,
2827    status_list_index: i64,
2828    status_purpose: &str,
2829    entry_id: Option<&str>,
2830) -> Result<Value> {
2831    if !matches!(status_purpose, "revocation" | "suspension" | "message") {
2832        return Err(CoreError::Json(format!(
2833            "status_purpose must be one of revocation, suspension, message, got {status_purpose:?}"
2834        )));
2835    }
2836    if status_list_index < 0 {
2837        return Err(CoreError::Json(
2838            "status_list_index must be non-negative".into(),
2839        ));
2840    }
2841    if status_list_credential.is_empty() {
2842        return Err(CoreError::Json(
2843            "status_list_credential URL is required".into(),
2844        ));
2845    }
2846    let id = entry_id
2847        .map(String::from)
2848        .unwrap_or_else(|| format!("{status_list_credential}#{status_list_index}"));
2849    Ok(json!({
2850        "id": id,
2851        "type": BITSTRING_STATUS_LIST_ENTRY_TYPE,
2852        "statusPurpose": status_purpose,
2853        "statusListIndex": status_list_index.to_string(),
2854        "statusListCredential": status_list_credential,
2855    }))
2856}
2857
2858/// Parameters for [`attach_credential_status`].
2859#[derive(Debug, Clone)]
2860pub struct AttachCredentialStatus {
2861    pub status_list_credential: String,
2862    pub status_list_index: i64,
2863    pub status_purpose: String,
2864    pub entry_id: Option<String>,
2865    /// `validFrom`-style timestamp used as the proof `created` when re-signing.
2866    pub created: String,
2867}
2868
2869/// Add a BitstringStatusList `credentialStatus` entry to a robot credential and
2870/// re-sign it under `signer_seed`, so the proof covers the status binding. If the
2871/// credential already carries a `credentialStatus`, the new entry is appended (the
2872/// field becomes a list), matching the Verifiable Credentials data model. Any
2873/// pre-existing proof is replaced.
2874pub fn attach_credential_status(
2875    credential: &Value,
2876    signer_seed: &[u8],
2877    params: &AttachCredentialStatus,
2878) -> Result<Value> {
2879    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
2880    let entry = build_status_list_entry(
2881        &params.status_list_credential,
2882        params.status_list_index,
2883        &params.status_purpose,
2884        params.entry_id.as_deref(),
2885    )?;
2886
2887    let mut obj = credential
2888        .as_object()
2889        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
2890        .clone();
2891
2892    match obj.get("credentialStatus").cloned() {
2893        None => {
2894            obj.insert("credentialStatus".into(), entry);
2895        }
2896        Some(Value::Array(mut existing)) => {
2897            existing.push(entry);
2898            obj.insert("credentialStatus".into(), Value::Array(existing));
2899        }
2900        Some(existing) => {
2901            obj.insert("credentialStatus".into(), json!([existing, entry]));
2902        }
2903    }
2904
2905    // Re-sign: the proof must cover the credentialStatus we just added.
2906    obj.remove("proof");
2907    let issuer = obj.get("issuer").and_then(|v| v.as_str()).unwrap_or("");
2908    let opts = BuildProofOptions::new(
2909        crate::verification_method::ed25519_method(issuer),
2910        &params.created,
2911    );
2912    data_integrity::sign(&Value::Object(obj), signer_seed, &opts)
2913}
2914
2915fn status_entries(credential: &Value) -> Result<Vec<Value>> {
2916    match credential.get("credentialStatus") {
2917        None => Ok(Vec::new()),
2918        Some(Value::Array(a)) => Ok(a.iter().filter(|e| e.is_object()).cloned().collect()),
2919        Some(v) if v.is_object() => Ok(vec![v.clone()]),
2920        Some(_) => Err(CoreError::Json(
2921            "credentialStatus must be an object or a list of objects".into(),
2922        )),
2923    }
2924}
2925
2926/// Return `true` if the robot credential's status bit for `status_purpose` is
2927/// set in the supplied status list. Returns `false` only when the credential
2928/// carries no status entry for that purpose, or every entry for that purpose
2929/// that references this list has its bit clear (every matching entry is
2930/// checked). Errors when the credential has an entry for this purpose but none
2931/// references the supplied list (the list cannot answer), or when the list's
2932/// issuer is not the credential's issuer. The caller verifies the list's proof
2933/// first.
2934pub fn check_credential_status(
2935    credential: &Value,
2936    status_list_credential: &Value,
2937    status_purpose: &str,
2938) -> Result<bool> {
2939    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, status_list_credential);
2940    check_status_inner(credential, status_list_credential, status_purpose, None)
2941}
2942
2943/// [`check_credential_status`], and the status list's own signature must
2944/// verify: issued by the issuer it names, under that issuer's key from `keys`
2945/// (see [`crate::robotics_dtn::verify_status_list_signature`]), checked at
2946/// `now_iso` with 30 s of skew. A list whose signature fails is an error.
2947pub fn check_credential_status_signed(
2948    credential: &Value,
2949    status_list_credential: &Value,
2950    status_purpose: &str,
2951    keys: Keys<'_>,
2952    now_iso: &str,
2953) -> Result<bool> {
2954    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, status_list_credential);
2955    check_status_inner(
2956        credential,
2957        status_list_credential,
2958        status_purpose,
2959        Some((keys, now_iso)),
2960    )
2961}
2962
2963fn check_status_inner(
2964    credential: &Value,
2965    status_list_credential: &Value,
2966    status_purpose: &str,
2967    signed_by: Option<(Keys<'_>, &str)>,
2968) -> Result<bool> {
2969    let entries: Vec<Value> = status_entries(credential)?
2970        .into_iter()
2971        .filter(|e| e.get("statusPurpose").and_then(|v| v.as_str()) == Some(status_purpose))
2972        .collect();
2973    if entries.is_empty() {
2974        return Ok(false);
2975    }
2976    let referenced_id = status_list_credential.get("id");
2977    let matching: Vec<&Value> = entries
2978        .iter()
2979        .filter(|e| e.get("statusListCredential") == referenced_id)
2980        .collect();
2981    if matching.is_empty() {
2982        return Err(CoreError::Json(
2983            "the credential has a status entry for this purpose, but none references this list"
2984                .into(),
2985        ));
2986    }
2987    if rv::issuer_id(status_list_credential.get("issuer"))
2988        != rv::issuer_id(credential.get("issuer"))
2989    {
2990        return Err(CoreError::Json(
2991            "the status list is not from the credential's issuer".into(),
2992        ));
2993    }
2994    if let Some((keys, now_iso)) = signed_by {
2995        if !crate::robotics_dtn::verify_status_list_signature(
2996            status_list_credential,
2997            keys,
2998            now_iso,
2999            30,
3000        )? {
3001            return Err(CoreError::Json(
3002                "the status list signature does not verify".into(),
3003            ));
3004        }
3005    }
3006    for entry in matching {
3007        if crate::status_list::verify_status(entry, status_list_credential)? {
3008            return Ok(true);
3009        }
3010    }
3011    Ok(false)
3012}
3013
3014// ---------------------------------------------------------------------------
3015// Accountable safety record (Phase 5.9)
3016// ---------------------------------------------------------------------------
3017
3018pub const SAFETY_RECORD_TYPE: &str = "RobotSafetyRecordCredential";
3019pub const SAFETY_LOG_VERSION: &str = "1.0";
3020
3021/// Standard safety event types: the interoperable set a verifier and an insurer
3022/// can rely on. Implementers MAY use additional types.
3023pub const EVENT_TYPES: [&str; 6] = [
3024    "incident",
3025    "near_miss",
3026    "manual_override",
3027    "kill_switch",
3028    "envelope_breach",
3029    "maintenance",
3030];
3031
3032/// Severity bands, ordered from least to most serious.
3033pub const SEVERITIES: [&str; 5] = ["info", "low", "medium", "high", "critical"];
3034
3035/// Append-only, plaintext, hash-linked safety event ledger. Reuses the black-box
3036/// chain semantics ([`entry_hash`], [`genesis_prev_hash`]) so the two logs verify
3037/// the same way, but entries are plaintext: a safety record is meant to be read
3038/// and trusted by third parties.
3039pub struct SafetyEventLog {
3040    genesis: String,
3041    entries: Vec<Value>,
3042    head: String,
3043    seq_base: u64,
3044}
3045
3046impl SafetyEventLog {
3047    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
3048    pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
3049        let genesis = genesis_prev_hash_override
3050            .map(String::from)
3051            .unwrap_or_else(genesis_prev_hash);
3052        Self {
3053            head: genesis.clone(),
3054            genesis,
3055            entries: Vec::new(),
3056            seq_base: 0,
3057        }
3058    }
3059
3060    /// Continue a log whose head is `prev_hash` and whose next entry is
3061    /// number `next_seq` (a host that keeps the log itself appends one entry
3062    /// at a time this way).
3063    pub fn resume(prev_hash: &str, next_seq: u64) -> Self {
3064        let mut log = Self::new(Some(prev_hash));
3065        log.seq_base = next_seq;
3066        log
3067    }
3068
3069    /// Append one safety event, link it to the chain head, and return the entry.
3070    pub fn append(
3071        &mut self,
3072        event_type: &str,
3073        severity: &str,
3074        details: Option<&Value>,
3075        actor: Option<&str>,
3076        timestamp: &str,
3077    ) -> Result<Value> {
3078        crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); details);
3079        if !EVENT_TYPES.contains(&event_type) {
3080            return Err(CoreError::Json(format!(
3081                "event_type must be one of {EVENT_TYPES:?}, got {event_type:?}"
3082            )));
3083        }
3084        if !SEVERITIES.contains(&severity) {
3085            return Err(CoreError::Json(format!(
3086                "severity must be one of {SEVERITIES:?}, got {severity:?}"
3087            )));
3088        }
3089
3090        let mut body = Map::new();
3091        body.insert("version".into(), json!(SAFETY_LOG_VERSION));
3092        body.insert(
3093            "seq".into(),
3094            json!(self.seq_base + self.entries.len() as u64),
3095        );
3096        body.insert("timestamp".into(), json!(timestamp));
3097        body.insert("eventType".into(), json!(event_type));
3098        body.insert("severity".into(), json!(severity));
3099        body.insert("prevHash".into(), json!(self.head));
3100        if let Some(d) = details {
3101            body.insert("details".into(), d.clone());
3102        }
3103        if let Some(a) = actor {
3104            body.insert("actor".into(), json!(a));
3105        }
3106        let h = entry_hash(&body)?;
3107        body.insert("entryHash".into(), json!(h));
3108        self.head = h;
3109        let entry = Value::Object(body);
3110        self.entries.push(entry.clone());
3111        Ok(entry)
3112    }
3113
3114    pub fn head(&self) -> &str {
3115        &self.head
3116    }
3117
3118    pub fn genesis(&self) -> &str {
3119        &self.genesis
3120    }
3121
3122    pub fn entries(&self) -> &[Value] {
3123        &self.entries
3124    }
3125
3126    /// Produce a summary object for embedding in a safety-record credential.
3127    pub fn summarize(&self) -> Value {
3128        summarize_entries(&self.entries, Some(&self.head))
3129    }
3130}
3131
3132/// Verify the hash chain over the ledger entries. Tamper-evident. Shares the
3133/// black-box chain verifier so the two logs verify identically.
3134pub fn verify_safety_log(
3135    entries: &[Value],
3136    genesis_prev_hash_override: Option<&str>,
3137) -> ChainResult {
3138    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
3139    verify_blackbox_chain(entries, genesis_prev_hash_override)
3140}
3141
3142/// Summarize ledger entries into counts by event type (sorted) and by severity
3143/// (info..critical), the total event count, and (when supplied) the ledger head
3144/// hash that anchors the summary to a specific chain state.
3145pub fn summarize_entries(entries: &[Value], head: Option<&str>) -> Value {
3146    crate::nesting::deep_guard!(Value::Null; entries);
3147    let mut sorted_types: Vec<&str> = EVENT_TYPES.to_vec();
3148    sorted_types.sort_unstable();
3149
3150    let mut event_counts = Map::new();
3151    for t in &sorted_types {
3152        event_counts.insert((*t).to_string(), json!(0));
3153    }
3154    let mut severity_counts = Map::new();
3155    for s in SEVERITIES {
3156        severity_counts.insert(s.to_string(), json!(0));
3157    }
3158
3159    for e in entries {
3160        if let Some(et) = e.get("eventType").and_then(|v| v.as_str()) {
3161            if let Some(c) = event_counts.get_mut(et).and_then(|v| v.as_u64()) {
3162                event_counts.insert(et.to_string(), json!(c + 1));
3163            }
3164        }
3165        if let Some(sv) = e.get("severity").and_then(|v| v.as_str()) {
3166            if let Some(c) = severity_counts.get_mut(sv).and_then(|v| v.as_u64()) {
3167                severity_counts.insert(sv.to_string(), json!(c + 1));
3168            }
3169        }
3170    }
3171
3172    let mut summary = Map::new();
3173    summary.insert("eventCounts".into(), Value::Object(event_counts));
3174    summary.insert("severityCounts".into(), Value::Object(severity_counts));
3175    summary.insert("totalEvents".into(), json!(entries.len() as u64));
3176    if let Some(h) = head {
3177        summary.insert("logHead".into(), json!(h));
3178    }
3179    Value::Object(summary)
3180}
3181
3182/// Structural validation of a safety summary.
3183pub fn validate_safety_summary(summary: &Value) -> Result<()> {
3184    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); summary);
3185    let obj = summary
3186        .as_object()
3187        .ok_or_else(|| CoreError::Json("summary must be an object".into()))?;
3188    for name in ["eventCounts", "severityCounts"] {
3189        let block = obj
3190            .get(name)
3191            .and_then(|v| v.as_object())
3192            .ok_or_else(|| CoreError::Json(format!("summary.{name} must be an object")))?;
3193        for (k, v) in block {
3194            let ok = v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false);
3195            if v.is_boolean() || !ok {
3196                return Err(CoreError::Json(format!(
3197                    "summary.{name}[{k:?}] must be a non-negative integer"
3198                )));
3199            }
3200        }
3201    }
3202    let total_ok = obj
3203        .get("totalEvents")
3204        .map(|v| (v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false)) && !v.is_boolean())
3205        .unwrap_or(false);
3206    if !total_ok {
3207        return Err(CoreError::Json(
3208            "summary.totalEvents must be a non-negative integer".into(),
3209        ));
3210    }
3211    Ok(())
3212}
3213
3214/// Parameters for [`build_safety_record`]. The issuer (an owner, an auditor, or
3215/// the robot itself) attests `summary`, produced by [`SafetyEventLog::summarize`]
3216/// or [`summarize_entries`].
3217#[derive(Debug, Clone)]
3218pub struct BuildSafetyRecord {
3219    pub issuer_did: String,
3220    pub robot_did: String,
3221    pub summary: Value,
3222    pub period_start: Option<String>,
3223    pub period_end: Option<String>,
3224    pub valid_from: String,
3225    pub valid_until: Option<String>,
3226}
3227
3228/// Build a signed `RobotSafetyRecordCredential` summarizing a robot's safety
3229/// ledger.
3230pub fn build_safety_record(signer_seed: &[u8], params: &BuildSafetyRecord) -> Result<Value> {
3231    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
3232    validate_safety_summary(&params.summary)?;
3233
3234    let mut subject = Map::new();
3235    subject.insert("id".into(), json!(params.robot_did));
3236    if let Some(s) = params.summary.as_object() {
3237        for (k, v) in s {
3238            subject.insert(k.clone(), v.clone());
3239        }
3240    }
3241    if params.period_start.is_some() || params.period_end.is_some() {
3242        let mut period = Map::new();
3243        if let Some(start) = &params.period_start {
3244            period.insert("start".into(), json!(start));
3245        }
3246        if let Some(end) = &params.period_end {
3247            period.insert("end".into(), json!(end));
3248        }
3249        subject.insert("period".into(), Value::Object(period));
3250    }
3251
3252    let mut cred = Map::new();
3253    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3254    cred.insert(
3255        "type".into(),
3256        json!(["VerifiableCredential", SAFETY_RECORD_TYPE]),
3257    );
3258    cred.insert("issuer".into(), json!(params.issuer_did));
3259    cred.insert("validFrom".into(), json!(params.valid_from));
3260    if let Some(vu) = &params.valid_until {
3261        cred.insert("validUntil".into(), json!(vu));
3262    }
3263    cred.insert("credentialSubject".into(), Value::Object(subject));
3264
3265    let opts = BuildProofOptions::new(
3266        crate::verification_method::ed25519_method(&params.issuer_did),
3267        &params.valid_from,
3268    );
3269    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
3270}
3271
3272/// Options for [`verify_safety_record`].
3273#[derive(Default, Clone, Copy)]
3274pub struct SafetyRecordCheck<'a> {
3275    /// The ledger entries: they must link, end at the summary's `logHead` with
3276    /// exactly `totalEvents` entries, and reproduce the summary's counts.
3277    /// Without them the record is accepted only when `trusted_issuers` names
3278    /// its issuer.
3279    pub entries: Option<&'a [Value]>,
3280    /// The record must be about this robot.
3281    pub robot_did: Option<&'a str>,
3282    /// The issuer must be in this set.
3283    pub trusted_issuers: Option<&'a HashSet<String>>,
3284}
3285
3286/// Verify a `RobotSafetyRecordCredential`: the issuer's proof bound to the
3287/// issuer, the validity window at `now_iso` (validFrom required), and the
3288/// structure of the embedded summary, plus the [`SafetyRecordCheck`] options.
3289/// Returns the credentialSubject on success.
3290pub fn verify_safety_record(
3291    credential: &Value,
3292    keys: Keys<'_>,
3293    check: SafetyRecordCheck<'_>,
3294    now_iso: &str,
3295) -> Result<Option<Value>> {
3296    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, check);
3297    let now = rv::require_now(now_iso)?;
3298    // A summary is the issuer's own count. Without the ledger to recount it,
3299    // it is accepted only from an issuer the verifier named as trusted.
3300    if check.entries.is_none() && check.trusted_issuers.is_none_or(|t| t.is_empty()) {
3301        return Ok(None);
3302    }
3303    let opts = VerifyOptions {
3304        trusted_issuers: check.trusted_issuers,
3305        ..VerifyOptions::window(Window::FromRequired)
3306    };
3307    let v =
3308        match rv::verify_robotics_credential(credential, keys, Some(SAFETY_RECORD_TYPE), now, opts)
3309        {
3310            Ok(v) => v,
3311            Err(_) => return Ok(None),
3312        };
3313    let subject = v.subject;
3314    if validate_safety_summary(&subject).is_err() {
3315        return Ok(None);
3316    }
3317    if let Some(robot) = check.robot_did {
3318        if subject.get("id").and_then(|x| x.as_str()) != Some(robot) {
3319            return Ok(None);
3320        }
3321    }
3322    if let Some(entries) = check.entries {
3323        if !verify_chain_against_head(
3324            entries,
3325            subject.get("logHead"),
3326            subject.get("totalEvents"),
3327            None,
3328        )
3329        .ok
3330        {
3331            return Ok(None);
3332        }
3333        let recount = summarize_entries(entries, None);
3334        if recount.get("eventCounts") != subject.get("eventCounts")
3335            || recount.get("severityCounts") != subject.get("severityCounts")
3336        {
3337            return Ok(None);
3338        }
3339    }
3340    Ok(Some(subject))
3341}
3342
3343// ---------------------------------------------------------------------------
3344// Perception provenance (Phase 5.10)
3345// ---------------------------------------------------------------------------
3346
3347pub const PERCEPTION_TYPE: &str = "PerceptionProvenanceCredential";
3348pub const PERCEPTION_LOG_VERSION: &str = "1.0";
3349
3350/// Standard sensor modalities: the interoperable set a verifier can rely on.
3351/// Implementers MAY use additional values.
3352pub const MODALITIES: [&str; 6] = ["camera", "lidar", "radar", "depth", "audio", "thermal"];
3353
3354/// Multibase (base64url) SHA-256 of a raw sensor frame. Only the hash travels in
3355/// the log and the attestation; the frame stays wherever the deployment keeps it.
3356pub fn hash_frame(frame: &[u8]) -> String {
3357    mb64(&Sha256::digest(frame))
3358}
3359
3360/// Append-only, plaintext, hash-linked log of sensor-frame provenance records.
3361/// Reuses the black-box chain semantics ([`entry_hash`], [`genesis_prev_hash`]),
3362/// so a perception log verifies the same way as the safety ledger. Each entry
3363/// binds a sequence number, a timestamp, the sensor id, the modality, the frame
3364/// hash, and the hash of the previous entry; the frames are not stored.
3365pub struct PerceptionLog {
3366    genesis: String,
3367    entries: Vec<Value>,
3368    head: String,
3369    seq_base: u64,
3370}
3371
3372impl PerceptionLog {
3373    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
3374    pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
3375        let genesis = genesis_prev_hash_override
3376            .map(String::from)
3377            .unwrap_or_else(genesis_prev_hash);
3378        Self {
3379            head: genesis.clone(),
3380            genesis,
3381            entries: Vec::new(),
3382            seq_base: 0,
3383        }
3384    }
3385
3386    /// Continue a log whose head is `prev_hash` and whose next entry is
3387    /// number `next_seq`.
3388    pub fn resume(prev_hash: &str, next_seq: u64) -> Self {
3389        let mut log = Self::new(Some(prev_hash));
3390        log.seq_base = next_seq;
3391        log
3392    }
3393
3394    /// Append one frame-provenance record, link it to the chain head, and return
3395    /// the entry. Provide either the raw `frame` (it is hashed) or a precomputed
3396    /// `frame_hash`, not both.
3397    pub fn record(
3398        &mut self,
3399        sensor_id: &str,
3400        modality: &str,
3401        frame: Option<&[u8]>,
3402        frame_hash: Option<&str>,
3403        timestamp: &str,
3404    ) -> Result<Value> {
3405        if !MODALITIES.contains(&modality) {
3406            return Err(CoreError::Json(format!(
3407                "modality must be one of {MODALITIES:?}, got {modality:?}"
3408            )));
3409        }
3410        if sensor_id.is_empty() {
3411            return Err(CoreError::Json("sensor_id is required".into()));
3412        }
3413        if frame.is_some() && frame_hash.is_some() {
3414            return Err(CoreError::Json(
3415                "provide either frame or frame_hash, not both".into(),
3416            ));
3417        }
3418        let resolved = match (frame, frame_hash) {
3419            (Some(f), None) => hash_frame(f),
3420            (None, Some(h)) if !h.is_empty() => h.to_string(),
3421            _ => return Err(CoreError::Json("frame or frame_hash is required".into())),
3422        };
3423
3424        let mut body = Map::new();
3425        body.insert("version".into(), json!(PERCEPTION_LOG_VERSION));
3426        body.insert(
3427            "seq".into(),
3428            json!(self.seq_base + self.entries.len() as u64),
3429        );
3430        body.insert("timestamp".into(), json!(timestamp));
3431        body.insert("sensorId".into(), json!(sensor_id));
3432        body.insert("modality".into(), json!(modality));
3433        body.insert("frameHash".into(), json!(resolved));
3434        body.insert("prevHash".into(), json!(self.head));
3435        let h = entry_hash(&body)?;
3436        body.insert("entryHash".into(), json!(h));
3437        self.head = h;
3438        let entry = Value::Object(body);
3439        self.entries.push(entry.clone());
3440        Ok(entry)
3441    }
3442
3443    pub fn head(&self) -> &str {
3444        &self.head
3445    }
3446
3447    pub fn genesis(&self) -> &str {
3448        &self.genesis
3449    }
3450
3451    pub fn entries(&self) -> &[Value] {
3452        &self.entries
3453    }
3454
3455    /// The number of records, the count a perception attestation anchors.
3456    pub fn count(&self) -> usize {
3457        self.entries.len()
3458    }
3459}
3460
3461/// Verify the hash chain over the perception log entries. Tamper-evident. Shares
3462/// the black-box chain verifier so every hash-linked log verifies identically.
3463pub fn verify_perception_log(
3464    entries: &[Value],
3465    genesis_prev_hash_override: Option<&str>,
3466) -> ChainResult {
3467    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
3468    verify_blackbox_chain(entries, genesis_prev_hash_override)
3469}
3470
3471/// Parameters for [`build_perception_attestation`]. The robot self-issues the
3472/// credential with its own Ed25519 seed. `captured_at`, when `None`, defaults to
3473/// `valid_from`. When `log_head` is supplied, the attestation also anchors the
3474/// segment of frames up to that chain head.
3475#[derive(Debug, Clone)]
3476pub struct BuildPerception {
3477    pub robot_did: String,
3478    pub sensor_id: String,
3479    pub modality: String,
3480    pub frame_hash: String,
3481    pub captured_at: Option<String>,
3482    pub log_head: Option<String>,
3483    /// The number of log entries up to `log_head`, so a verifier can tell a
3484    /// segment was not cut short.
3485    pub log_count: Option<u64>,
3486    pub valid_from: String,
3487    pub valid_until: Option<String>,
3488}
3489
3490/// Build a signed `PerceptionProvenanceCredential` attesting that a robot's sensor
3491/// captured a specific frame. Software frame-hash signing: the robot signs the
3492/// provenance of the captured frame with its own key.
3493pub fn build_perception_attestation(robot_seed: &[u8], params: &BuildPerception) -> Result<Value> {
3494    if !MODALITIES.contains(&params.modality.as_str()) {
3495        return Err(CoreError::Json(format!(
3496            "modality must be one of {MODALITIES:?}, got {:?}",
3497            params.modality
3498        )));
3499    }
3500    if params.frame_hash.is_empty() {
3501        return Err(CoreError::Json("frame_hash is required".into()));
3502    }
3503
3504    let captured = params
3505        .captured_at
3506        .clone()
3507        .unwrap_or_else(|| params.valid_from.clone());
3508
3509    let mut subject = Map::new();
3510    subject.insert("id".into(), json!(params.robot_did));
3511    subject.insert("sensorId".into(), json!(params.sensor_id));
3512    subject.insert("modality".into(), json!(params.modality));
3513    subject.insert("frameHash".into(), json!(params.frame_hash));
3514    subject.insert("capturedAt".into(), json!(captured));
3515    if let Some(head) = &params.log_head {
3516        subject.insert("logHead".into(), json!(head));
3517    }
3518    if let Some(n) = params.log_count {
3519        subject.insert("logCount".into(), json!(n));
3520    }
3521
3522    let mut cred = Map::new();
3523    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3524    cred.insert(
3525        "type".into(),
3526        json!(["VerifiableCredential", PERCEPTION_TYPE]),
3527    );
3528    cred.insert("issuer".into(), json!(params.robot_did));
3529    cred.insert("validFrom".into(), json!(params.valid_from));
3530    if let Some(vu) = &params.valid_until {
3531        cred.insert("validUntil".into(), json!(vu));
3532    }
3533    cred.insert("credentialSubject".into(), Value::Object(subject));
3534
3535    let opts = BuildProofOptions::new(
3536        crate::verification_method::ed25519_method(&params.robot_did),
3537        &params.valid_from,
3538    );
3539    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
3540}
3541
3542/// Verify a `PerceptionProvenanceCredential`: the robot's proof and, when the raw
3543/// `frame` is supplied, that its hash reproduces the attested `frameHash`. Returns
3544/// the credentialSubject on success, `None` if invalid.
3545pub fn verify_perception_attestation(
3546    credential: &Value,
3547    keys: Keys<'_>,
3548    frame: Option<&[u8]>,
3549    now_iso: &str,
3550) -> Result<Option<Value>> {
3551    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
3552    let v = match bound(
3553        credential,
3554        keys,
3555        PERCEPTION_TYPE,
3556        now_iso,
3557        Window::FromRequired,
3558    )? {
3559        Some(v) if issuer_is_subject(&v) => v,
3560        _ => return Ok(None),
3561    };
3562    let frame_hash = v.subject.get("frameHash").and_then(|v| v.as_str());
3563    let modality = v.subject.get("modality").and_then(|v| v.as_str());
3564    match (frame_hash, modality) {
3565        (Some(fh), Some(m)) if !fh.is_empty() && MODALITIES.contains(&m) => {}
3566        _ => return Ok(None),
3567    }
3568    if let Some(f) = frame {
3569        if hash_frame(f) != frame_hash.unwrap_or("") {
3570            return Ok(None);
3571        }
3572    }
3573    Ok(Some(v.subject))
3574}
3575
3576/// Verify a perception log against the robot's signed head: the attestation
3577/// must verify and carry `logHead` and `logCount`, and the log must link and
3578/// end at that head with exactly that many entries.
3579pub fn verify_perception_segment(
3580    entries: &[Value],
3581    attestation: &Value,
3582    keys: Keys<'_>,
3583    genesis_prev_hash_override: Option<&str>,
3584    now_iso: &str,
3585) -> Result<ChainResult> {
3586    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); entries, attestation);
3587    let subject = match verify_perception_attestation(attestation, keys, None, now_iso)? {
3588        Some(s) => s,
3589        None => {
3590            return Ok(ChainResult {
3591                ok: false,
3592                reason: Some("attestation does not verify".into()),
3593            })
3594        }
3595    };
3596    if subject.get("logHead").is_none() || subject.get("logCount").is_none() {
3597        return Ok(ChainResult {
3598            ok: false,
3599            reason: Some("attestation does not anchor a log head and count".into()),
3600        });
3601    }
3602    Ok(verify_chain_against_head(
3603        entries,
3604        subject.get("logHead"),
3605        subject.get("logCount"),
3606        genesis_prev_hash_override,
3607    ))
3608}
3609
3610// ---------------------------------------------------------------------------
3611// Delegation lease (Phase 5.11)
3612// ---------------------------------------------------------------------------
3613
3614pub const DELEGATION_LEASE_TYPE: &str = "DelegationLeaseCredential";
3615
3616/// Parameters for [`build_delegation_lease`]. The issuer is the signer (an
3617/// authority or the holder of a parent lease); `robot_did` is the subject the
3618/// lease is granted to. `scope` is a physicalScope object (the same shape as a
3619/// `PhysicalCapabilityScope` credentialSubject.physicalScope). Leases are
3620/// short-lived by design, so the window is bounded by `valid_from`/`valid_until`.
3621/// Set `parent_lease_id` when sub-granting from another lease.
3622#[derive(Debug, Clone)]
3623pub struct BuildDelegationLease {
3624    pub issuer_did: String,
3625    pub robot_did: String,
3626    pub lease_id: String,
3627    pub scope: Value,
3628    pub parent_lease_id: Option<String>,
3629    pub valid_from: String,
3630    pub valid_until: String,
3631}
3632
3633/// Build a signed `DelegationLeaseCredential` granting `robot_did` a bounded
3634/// physical scope for a fixed window. The window is verifiable entirely offline.
3635pub fn build_delegation_lease(signer_seed: &[u8], params: &BuildDelegationLease) -> Result<Value> {
3636    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
3637    if params.lease_id.is_empty() {
3638        return Err(CoreError::Json("lease_id is required".into()));
3639    }
3640    if !params.scope.is_object() {
3641        return Err(CoreError::Json(
3642            "scope must be a physicalScope object".into(),
3643        ));
3644    }
3645
3646    let mut subject = Map::new();
3647    subject.insert("id".into(), json!(params.robot_did));
3648    subject.insert("leaseId".into(), json!(params.lease_id));
3649    subject.insert("physicalScope".into(), params.scope.clone());
3650    if let Some(parent) = &params.parent_lease_id {
3651        subject.insert("parentLeaseId".into(), json!(parent));
3652    }
3653
3654    let mut cred = Map::new();
3655    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3656    cred.insert(
3657        "type".into(),
3658        json!(["VerifiableCredential", DELEGATION_LEASE_TYPE]),
3659    );
3660    cred.insert("issuer".into(), json!(params.issuer_did));
3661    cred.insert("validFrom".into(), json!(params.valid_from));
3662    cred.insert("validUntil".into(), json!(params.valid_until));
3663    cred.insert("credentialSubject".into(), Value::Object(subject));
3664
3665    let opts = BuildProofOptions::new(
3666        crate::verification_method::ed25519_method(&params.issuer_did),
3667        &params.valid_from,
3668    );
3669    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
3670}
3671
3672/// Verify a `DelegationLeaseCredential` offline: the issuer's proof bound to the
3673/// issuer (`keys` is a `{did: key}` source, or the bare key of a did:key
3674/// issuer), validFrom and validUntil both present with `now_iso` inside, the
3675/// lease is for `expected_robot` (required), it carries a `leaseId` and a
3676/// well-formed scope, the issuer is in `trusted_issuers` when given, and (when
3677/// `parent_scope` is supplied) the scope attenuates the parent. Returns the
3678/// credentialSubject on success, `None` if invalid.
3679pub fn verify_delegation_lease(
3680    credential: &Value,
3681    keys: Keys<'_>,
3682    expected_robot: &str,
3683    parent_scope: Option<&Value>,
3684    trusted_issuers: Option<&HashSet<String>>,
3685    now_iso: &str,
3686) -> Result<Option<Value>> {
3687    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, parent_scope);
3688    if expected_robot.is_empty() {
3689        return Err(CoreError::Json("expected_robot is required".into()));
3690    }
3691    let now = rv::require_now(now_iso)?;
3692    let opts = VerifyOptions {
3693        trusted_issuers,
3694        ..VerifyOptions::window(Window::Required)
3695    };
3696    let v = match rv::verify_robotics_credential(
3697        credential,
3698        keys,
3699        Some(DELEGATION_LEASE_TYPE),
3700        now,
3701        opts,
3702    ) {
3703        Ok(v) => v,
3704        Err(_) => return Ok(None),
3705    };
3706    if v.subject.get("id").and_then(|x| x.as_str()) != Some(expected_robot)
3707        || non_empty_str(&v.subject, "leaseId").is_none()
3708    {
3709        return Ok(None);
3710    }
3711    let scope = match v.subject.get("physicalScope") {
3712        Some(sc) if sc.is_object() && scope_problems(sc).is_empty() => sc,
3713        _ => return Ok(None),
3714    };
3715    if parent_scope.is_some_and(|p| !attenuates(p, scope)) {
3716        return Ok(None);
3717    }
3718    Ok(Some(v.subject))
3719}
3720
3721/// Verify a chain of leases from a trusted root down to `expected_robot`
3722/// (`leases` runs root to leaf). The root is issued by one of `root_issuers`
3723/// and has no `parentLeaseId`; each later lease names the previous `leaseId`
3724/// as its `parentLeaseId`, is issued by the party the previous lease was
3725/// granted to, has a window inside the previous window, and attenuates the
3726/// previous scope. Every lease is current at `now_iso`; the leaf is for
3727/// `expected_robot`. Returns the leaf subject on success.
3728pub fn verify_lease_chain(
3729    leases: &[Value],
3730    keys: Keys<'_>,
3731    expected_robot: &str,
3732    root_issuers: &HashSet<String>,
3733    now_iso: &str,
3734) -> Result<Option<Value>> {
3735    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); leases);
3736    rv::require_now(now_iso)?;
3737    if leases.is_empty() || root_issuers.is_empty() {
3738        return Ok(None);
3739    }
3740    let mut prev: Option<(&Value, Value)> = None;
3741    for (i, lease) in leases.iter().enumerate() {
3742        let holder = lease
3743            .get("credentialSubject")
3744            .and_then(|s| s.get("id"))
3745            .and_then(|v| v.as_str())
3746            .unwrap_or("");
3747        let target = if i + 1 == leases.len() {
3748            expected_robot
3749        } else {
3750            holder
3751        };
3752        if target.is_empty() {
3753            return Ok(None);
3754        }
3755        let parent_scope = prev.as_ref().and_then(|(_, ps)| ps.get("physicalScope"));
3756        // The root must be one of `root_issuers`; each child must be issued by
3757        // the holder the verified parent names. Both are named sets, so did:key
3758        // parties verify under their own keys with no key source.
3759        let holder_set: HashSet<String> = prev
3760            .as_ref()
3761            .and_then(|(_, ps)| ps.get("id"))
3762            .and_then(|v| v.as_str())
3763            .filter(|h| !h.is_empty())
3764            .map(|h| [h.to_string()].into_iter().collect())
3765            .unwrap_or_default();
3766        let subject = match verify_delegation_lease(
3767            lease,
3768            keys,
3769            target,
3770            parent_scope,
3771            Some(if prev.is_none() {
3772                root_issuers
3773            } else {
3774                &holder_set
3775            }),
3776            now_iso,
3777        )? {
3778            Some(s) => s,
3779            None => return Ok(None),
3780        };
3781        match &prev {
3782            Some((p_lease, p_sub)) => {
3783                if subject.get("parentLeaseId") != p_sub.get("leaseId") {
3784                    return Ok(None);
3785                }
3786                if rv::issuer_id(lease.get("issuer")) != p_sub.get("id").and_then(|v| v.as_str()) {
3787                    return Ok(None);
3788                }
3789                let t = |c: &Value, k: &str| rv::time_ns(c.get(k));
3790                if t(lease, "validFrom") < t(p_lease, "validFrom")
3791                    || t(lease, "validUntil") > t(p_lease, "validUntil")
3792                {
3793                    return Ok(None);
3794                }
3795            }
3796            None => {
3797                if subject.get("parentLeaseId").is_some() {
3798                    return Ok(None);
3799                }
3800            }
3801        }
3802        prev = Some((lease, subject));
3803    }
3804    Ok(prev.map(|(_, s)| s))
3805}
3806
3807/// Decide whether a verified lease permits a proposed physical action. The full
3808/// lease `credential` is required and is verified again here (`keys` and
3809/// `trusted_issuers` as in [`verify_delegation_lease`], with `subject.id` as the
3810/// expected robot), so its window is read from signed data: a copy with a
3811/// re-dated `validUntil` no longer verifies. Its subject must equal `subject`,
3812/// its window must contain `now_iso`, and the action must fit the scope.
3813pub fn lease_permits(
3814    subject: &Value,
3815    action: &PhysicalAction,
3816    credential: Option<&Value>,
3817    keys: Keys<'_>,
3818    trusted_issuers: Option<&HashSet<String>>,
3819    now_iso: &str,
3820) -> Result<bool> {
3821    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); subject, credential);
3822    let now = rv::require_now(now_iso)?;
3823    let cred = match credential {
3824        Some(c) if c.is_object() && subject.is_object() => c,
3825        _ => return Ok(false),
3826    };
3827    let robot = match subject.get("id").and_then(|v| v.as_str()) {
3828        Some(r) if !r.is_empty() => r,
3829        _ => return Ok(false),
3830    };
3831    match verify_delegation_lease(cred, keys, robot, None, trusted_issuers, now_iso)? {
3832        Some(v) if &v == subject => {}
3833        _ => return Ok(false),
3834    }
3835    if rv::window_reason(cred, Window::Required, now, 0).is_some() {
3836        return Ok(false);
3837    }
3838    match subject.get("physicalScope") {
3839        Some(scope) if scope.is_object() => Ok(check_physical_action(scope, action).ok),
3840        _ => Ok(false),
3841    }
3842}
3843
3844// ---------------------------------------------------------------------------
3845// Physical quorum (Phase 5.12)
3846// ---------------------------------------------------------------------------
3847
3848pub const ACTION_APPROVAL_TYPE: &str = "PhysicalActionApprovalCredential";
3849pub const APPROVE: &str = "approve";
3850pub const REJECT: &str = "reject";
3851/// How long an approval lasts when its builder gives no end.
3852pub const DEFAULT_APPROVAL_SECONDS: i64 = 300;
3853/// The longest approval lifetime a verifier accepts.
3854pub const MAX_APPROVAL_SECONDS: i64 = 900;
3855
3856/// Parameters for [`build_action_approval`]. The approver is the signer; the
3857/// approval is over a specific physical action `action_id` that `robot_did`
3858/// would perform. `decision` is "approve" or "reject".
3859#[derive(Debug, Clone)]
3860pub struct BuildActionApproval {
3861    pub approver_did: String,
3862    pub action_id: String,
3863    pub robot_did: String,
3864    pub decision: String,
3865    pub valid_from: String,
3866    pub valid_until: Option<String>,
3867}
3868
3869/// Build a signed `PhysicalActionApprovalCredential` by one approver for a
3870/// specific physical action.
3871pub fn build_action_approval(approver_seed: &[u8], params: &BuildActionApproval) -> Result<Value> {
3872    if params.decision != APPROVE && params.decision != REJECT {
3873        return Err(CoreError::Json(format!(
3874            "decision must be {APPROVE:?} or {REJECT:?}, got {:?}",
3875            params.decision
3876        )));
3877    }
3878    if params.action_id.is_empty() {
3879        return Err(CoreError::Json("action_id is required".into()));
3880    }
3881
3882    let mut subject = Map::new();
3883    subject.insert("id".into(), json!(params.approver_did));
3884    subject.insert("actionId".into(), json!(params.action_id));
3885    subject.insert("robotDid".into(), json!(params.robot_did));
3886    subject.insert("decision".into(), json!(params.decision));
3887
3888    let mut cred = Map::new();
3889    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3890    cred.insert(
3891        "type".into(),
3892        json!(["VerifiableCredential", ACTION_APPROVAL_TYPE]),
3893    );
3894    cred.insert("issuer".into(), json!(params.approver_did));
3895    cred.insert("validFrom".into(), json!(params.valid_from));
3896    // An approval is short-lived: without an explicit end it lasts
3897    // DEFAULT_APPROVAL_SECONDS, and a verifier refuses one without validUntil.
3898    let valid_until = match &params.valid_until {
3899        Some(vu) => vu.clone(),
3900        None => crate::time::epoch_seconds_to_iso(
3901            crate::time::iso_to_epoch_seconds(&params.valid_from)? + DEFAULT_APPROVAL_SECONDS,
3902        ),
3903    };
3904    cred.insert("validUntil".into(), json!(valid_until));
3905    cred.insert("credentialSubject".into(), Value::Object(subject));
3906
3907    let opts = BuildProofOptions::new(
3908        crate::verification_method::ed25519_method(&params.approver_did),
3909        &params.valid_from,
3910    );
3911    data_integrity::sign(&Value::Object(cred), approver_seed, &opts)
3912}
3913
3914/// One approver's public key, looked up by issuer DID, for
3915/// [`verify_action_authorization`].
3916#[derive(Debug, Clone)]
3917pub struct ApproverKey {
3918    pub did: String,
3919    pub public_key: Vec<u8>,
3920}
3921
3922/// Verify that a high-consequence physical action is authorized by a quorum.
3923///
3924/// Each approval must carry a proof bound to its issuer and verified with the
3925/// issuer's key from `approver_keys`, name the issuer as its subject, match
3926/// `action_id` and `robot_did`, and carry both validFrom and validUntil with
3927/// `now_iso` inside and a lifetime of at most [`MAX_APPROVAL_SECONDS`]. When
3928/// `approver_set` is supplied, the approver must be in it. Each approver's
3929/// latest decision counts (at the same instant a rejection wins); any latest
3930/// rejection vetoes the action. Otherwise it is authorized when at least
3931/// `threshold` approvers with DISTINCT signing keys approve: two DIDs mapped to
3932/// the same key count once. Returns `(authorized, sorted approving DIDs)`.
3933pub fn verify_action_authorization(
3934    approvals: &[Value],
3935    action_id: &str,
3936    robot_did: &str,
3937    approver_keys: &[ApproverKey],
3938    threshold: i64,
3939    approver_set: Option<&HashSet<String>>,
3940    now_iso: &str,
3941) -> Result<(bool, Vec<String>)> {
3942    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); approvals);
3943    verify_action_authorization_with(
3944        approvals,
3945        action_id,
3946        robot_did,
3947        approver_keys,
3948        threshold,
3949        approver_set,
3950        MAX_APPROVAL_SECONDS,
3951        now_iso,
3952    )
3953}
3954
3955/// [`verify_action_authorization`] with the caller's longest approval
3956/// lifetime instead of [`MAX_APPROVAL_SECONDS`].
3957#[allow(clippy::too_many_arguments)]
3958pub fn verify_action_authorization_with(
3959    approvals: &[Value],
3960    action_id: &str,
3961    robot_did: &str,
3962    approver_keys: &[ApproverKey],
3963    threshold: i64,
3964    approver_set: Option<&HashSet<String>>,
3965    max_approval_seconds: i64,
3966    now_iso: &str,
3967) -> Result<(bool, Vec<String>)> {
3968    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); approvals);
3969    if max_approval_seconds < 1 {
3970        return Err(CoreError::Json(
3971            "max_approval_seconds must be at least 1".into(),
3972        ));
3973    }
3974    if threshold < 1 {
3975        return Err(CoreError::Json("threshold must be at least 1".into()));
3976    }
3977    let now = rv::require_now(now_iso)?;
3978    let map: alloc::collections::BTreeMap<String, Vec<u8>> =
3979        Keys::map_of(approver_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
3980    let keys = Keys::Map(&map);
3981
3982    // The approver set is a named member set: with no key on file, its
3983    // did:key members verify under their own keys. A freshly minted did:key
3984    // is never an approver by itself.
3985    let opts = VerifyOptions {
3986        trusted_issuers: approver_set,
3987        ..VerifyOptions::window(Window::Required)
3988    };
3989    let mut latest: alloc::collections::BTreeMap<String, (i128, bool)> =
3990        alloc::collections::BTreeMap::new();
3991    for approval in approvals {
3992        let mut early = false;
3993        let v = match rv::verify_robotics_credential(
3994            approval,
3995            keys,
3996            Some(ACTION_APPROVAL_TYPE),
3997            now,
3998            opts,
3999        ) {
4000            Ok(v) if issuer_is_subject(&v) => v,
4001            Err(why) if why == "credential window: not_yet_valid" => {
4002                // A rejection dated slightly ahead of the verifier's clock
4003                // still vetoes: re-check everything else at its own start. An
4004                // early approval never counts.
4005                let at = match rv::time_ns(approval.get("validFrom")) {
4006                    Some(t) => t,
4007                    None => continue,
4008                };
4009                match rv::verify_robotics_credential(
4010                    approval,
4011                    keys,
4012                    Some(ACTION_APPROVAL_TYPE),
4013                    at,
4014                    opts,
4015                ) {
4016                    Ok(v) if issuer_is_subject(&v) => {
4017                        early = true;
4018                        v
4019                    }
4020                    _ => continue,
4021                }
4022            }
4023            _ => continue,
4024        };
4025        if v.subject.get("actionId").and_then(|x| x.as_str()) != Some(action_id)
4026            || v.subject.get("robotDid").and_then(|x| x.as_str()) != Some(robot_did)
4027        {
4028            continue;
4029        }
4030        let reject = match v.subject.get("decision").and_then(|x| x.as_str()) {
4031            Some(APPROVE) => false,
4032            Some(REJECT) => true,
4033            _ => continue,
4034        };
4035        if early && !reject {
4036            continue;
4037        }
4038        if let Some(set) = approver_set {
4039            if !set.contains(&v.issuer) {
4040                continue;
4041            }
4042        }
4043        let (start, end) = match (
4044            rv::time_ns(approval.get("validFrom")),
4045            rv::time_ns(approval.get("validUntil")),
4046        ) {
4047            (Some(a), Some(b)) => (a, b),
4048            _ => continue,
4049        };
4050        if end - start > i128::from(max_approval_seconds) * 1_000_000_000 {
4051            continue;
4052        }
4053        let newer = match latest.get(&v.issuer) {
4054            None => true,
4055            Some((t, _)) => start > *t || (start == *t && reject),
4056        };
4057        if newer {
4058            latest.insert(v.issuer, (start, reject));
4059        }
4060    }
4061
4062    if latest.values().any(|(_, reject)| *reject) {
4063        return Ok((false, Vec::new()));
4064    }
4065    let mut approvers: Vec<String> = Vec::new();
4066    let mut seen: HashSet<Vec<u8>> = HashSet::new();
4067    for issuer in latest.keys() {
4068        let raw = match map.get(issuer) {
4069            Some(k) => k.clone(),
4070            None => match crate::keys::did_key_to_ed25519(issuer) {
4071                Ok(k) if issuer.starts_with("did:key:") => k,
4072                _ => continue,
4073            },
4074        };
4075        if seen.insert(raw) {
4076            approvers.push(issuer.clone());
4077        }
4078    }
4079    approvers.sort();
4080    Ok((approvers.len() as i64 >= threshold, approvers))
4081}
4082
4083// ---------------------------------------------------------------------------
4084// Robot lifecycle: ownership transfer, key rotation, decommission (Phase 5.13)
4085// ---------------------------------------------------------------------------
4086
4087pub const OWNERSHIP_TRANSFER_TYPE: &str = "RobotOwnershipTransferCredential";
4088pub const KEY_ROTATION_TYPE: &str = "RobotKeyRotationCredential";
4089pub const DECOMMISSION_TYPE: &str = "RobotDecommissionCredential";
4090
4091/// Parameters for [`build_ownership_transfer`]. The signer is the current owner;
4092/// `from_owner` defaults to `issuer_did` (the current owner's DID). Setting
4093/// `prev_transfer_id` links this transfer to the previous one, forming a chain:
4094/// it must be the previous transfer's `id`. `credential_id` is this transfer's
4095/// own `id` (the caller supplies it; use a fresh `urn:uuid:`).
4096#[derive(Debug, Clone)]
4097pub struct BuildOwnershipTransfer {
4098    pub issuer_did: String,
4099    pub robot_did: String,
4100    pub to_owner: String,
4101    pub from_owner: Option<String>,
4102    pub prev_transfer_id: Option<String>,
4103    pub credential_id: String,
4104    pub valid_from: String,
4105}
4106
4107/// Build a signed transfer of `robot_did` from the current owner to `to_owner`.
4108/// The signer is the current owner; `from_owner` defaults to `issuer_did`.
4109pub fn build_ownership_transfer(
4110    current_owner_seed: &[u8],
4111    params: &BuildOwnershipTransfer,
4112) -> Result<Value> {
4113    if params.robot_did.is_empty() || params.to_owner.is_empty() {
4114        return Err(CoreError::Json(
4115            "robot_did and to_owner are required".into(),
4116        ));
4117    }
4118    if params.credential_id.is_empty() {
4119        return Err(CoreError::Json("credential_id is required".into()));
4120    }
4121    let seller = params
4122        .from_owner
4123        .clone()
4124        .unwrap_or_else(|| params.issuer_did.clone());
4125
4126    let mut subject = Map::new();
4127    subject.insert("id".into(), json!(params.robot_did));
4128    subject.insert("fromOwner".into(), json!(seller));
4129    subject.insert("toOwner".into(), json!(params.to_owner));
4130    if let Some(prev) = &params.prev_transfer_id {
4131        subject.insert("prevTransferId".into(), json!(prev));
4132    }
4133
4134    let mut cred = Map::new();
4135    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4136    cred.insert("id".into(), json!(params.credential_id));
4137    cred.insert(
4138        "type".into(),
4139        json!(["VerifiableCredential", OWNERSHIP_TRANSFER_TYPE]),
4140    );
4141    cred.insert("issuer".into(), json!(params.issuer_did));
4142    cred.insert("validFrom".into(), json!(params.valid_from));
4143    cred.insert("credentialSubject".into(), Value::Object(subject));
4144
4145    let opts = BuildProofOptions::new(
4146        crate::verification_method::ed25519_method(&params.issuer_did),
4147        &params.valid_from,
4148    );
4149    data_integrity::sign(&Value::Object(cred), current_owner_seed, &opts)
4150}
4151
4152fn non_empty_str<'v>(v: &'v Value, key: &str) -> Option<&'v str> {
4153    v.get(key)
4154        .and_then(|x| x.as_str())
4155        .filter(|s| !s.is_empty())
4156}
4157
4158/// Verify a transfer: the current owner's proof bound to the issuer, the
4159/// issuer is the `fromOwner` (only the current owner can transfer the robot),
4160/// `toOwner` and the robot `id` are non-empty strings, validFrom no later than
4161/// `now_iso`, and (when given) the transfer is for `robot_did`. `owner_keys` is
4162/// a `{owner_did: key}` source (or the bare key of a did:key owner).
4163pub fn verify_ownership_transfer(
4164    credential: &Value,
4165    owner_keys: Keys<'_>,
4166    robot_did: Option<&str>,
4167    now_iso: &str,
4168) -> Result<Option<Value>> {
4169    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
4170    let v = match bound(
4171        credential,
4172        owner_keys,
4173        OWNERSHIP_TRANSFER_TYPE,
4174        now_iso,
4175        Window::FromRequired,
4176    )? {
4177        Some(v) => v,
4178        None => return Ok(None),
4179    };
4180    let ok = non_empty_str(&v.subject, "toOwner").is_some()
4181        && non_empty_str(&v.subject, "fromOwner") == Some(v.issuer.as_str())
4182        && non_empty_str(&v.subject, "id").is_some()
4183        && robot_did.is_none_or(|r| v.subject.get("id").and_then(|x| x.as_str()) == Some(r));
4184    Ok(if ok { Some(v.subject) } else { None })
4185}
4186
4187/// One owner's public key, looked up by owner DID, for [`verify_custody_chain`].
4188#[derive(Debug, Clone)]
4189pub struct OwnerKey {
4190    pub did: String,
4191    pub public_key: Vec<u8>,
4192}
4193
4194/// The links of a chain of custody (see [`verify_custody_chain`]). Returns
4195/// `(ok, last_owner, last_transfer_id)`.
4196fn custody_links(
4197    transfers: &[Value],
4198    public_keys: &[OwnerKey],
4199    robot_did: &str,
4200    origin_owner: Option<&str>,
4201    now_iso: &str,
4202) -> Result<(bool, Option<String>, Option<String>)> {
4203    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); transfers);
4204    rv::require_now(now_iso)?;
4205    if robot_did.is_empty() || origin_owner.is_none_or(str::is_empty) {
4206        return Ok((false, None, None));
4207    }
4208    let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
4209    let mut expected_from: Option<String> = origin_owner.map(String::from);
4210    let mut current_owner: Option<String> = origin_owner.map(String::from);
4211    let mut prev_id: Option<String> = None;
4212    let mut prev_time: Option<i128> = None;
4213    for (i, transfer) in transfers.iter().enumerate() {
4214        let keys = rv::pin_if_keyless(Keys::Map(&map), expected_from.as_deref());
4215        let subject = match verify_ownership_transfer(transfer, keys, Some(robot_did), now_iso)? {
4216            Some(s) => s,
4217            None => return Ok((false, None, None)),
4218        };
4219        if let Some(expected) = &expected_from {
4220            if subject.get("fromOwner").and_then(|v| v.as_str()) != Some(expected.as_str()) {
4221                return Ok((false, None, None));
4222            }
4223        }
4224        let this_time = match rv::time_ns(transfer.get("validFrom")) {
4225            Some(t) if prev_time.is_none_or(|p| t >= p) => t,
4226            _ => return Ok((false, None, None)),
4227        };
4228        if i > 0 {
4229            match &prev_id {
4230                Some(p) if subject.get("prevTransferId").and_then(|v| v.as_str()) == Some(p) => {}
4231                _ => return Ok((false, None, None)),
4232            }
4233        }
4234        prev_id = non_empty_str(transfer, "id").map(String::from);
4235        prev_time = Some(this_time);
4236        current_owner = subject
4237            .get("toOwner")
4238            .and_then(|v| v.as_str())
4239            .map(String::from);
4240        expected_from = current_owner.clone();
4241    }
4242    Ok((true, current_owner, prev_id))
4243}
4244
4245/// The type of a robot's signed statement naming its current owner.
4246pub const CUSTODY_HEAD_TYPE: &str = "RobotCustodyHead";
4247
4248/// How fresh a custody head must be, by default: one day.
4249pub const CUSTODY_HEAD_MAX_AGE_SECONDS: i64 = 86_400;
4250
4251/// Parameters for [`build_custody_head`].
4252#[derive(Debug, Clone)]
4253pub struct BuildCustodyHead {
4254    pub robot_did: String,
4255    /// The owner the robot now follows: the `toOwner` of the newest transfer
4256    /// it accepted, or the origin owner when there is none.
4257    pub owner: String,
4258    /// The `id` of that newest transfer; `None` before any transfer.
4259    pub head_transfer_id: Option<String>,
4260    pub attested_at: String,
4261    /// A verifier's challenge, echoed so the statement can't be replayed.
4262    pub challenge: Option<String>,
4263}
4264
4265/// Build a `RobotCustodyHead`: the robot signs which transfer it now follows
4266/// and who its owner is. A former owner no longer holds the robot, so it can't
4267/// get a fresh head naming itself after a sale.
4268pub fn build_custody_head(robot_seed: &[u8], params: &BuildCustodyHead) -> Result<Value> {
4269    if params.robot_did.is_empty() || params.owner.is_empty() {
4270        return Err(CoreError::Json("robot_did and owner are required".into()));
4271    }
4272    if params.head_transfer_id.as_deref() == Some("") {
4273        return Err(CoreError::Json("head_transfer_id must not be empty".into()));
4274    }
4275    if rv::time_ns(Some(&json!(params.attested_at))).is_none() {
4276        return Err(CoreError::Json(
4277            "attested_at must be an RFC 3339 time".into(),
4278        ));
4279    }
4280    let mut subject = Map::new();
4281    subject.insert("id".into(), json!(params.robot_did));
4282    subject.insert("owner".into(), json!(params.owner));
4283    if let Some(t) = &params.head_transfer_id {
4284        subject.insert("headTransferId".into(), json!(t));
4285    }
4286    subject.insert("attestedAt".into(), json!(params.attested_at));
4287    if let Some(c) = &params.challenge {
4288        if c.is_empty() {
4289            return Err(CoreError::Json("challenge must not be empty".into()));
4290        }
4291        subject.insert("challenge".into(), json!(c));
4292    }
4293    let mut cred = Map::new();
4294    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4295    cred.insert(
4296        "type".into(),
4297        json!(["VerifiableCredential", CUSTODY_HEAD_TYPE]),
4298    );
4299    cred.insert("issuer".into(), json!(params.robot_did));
4300    cred.insert("validFrom".into(), json!(params.attested_at));
4301    cred.insert("credentialSubject".into(), Value::Object(subject));
4302    let opts = BuildProofOptions::new(
4303        crate::verification_method::ed25519_method(&params.robot_did),
4304        &params.attested_at,
4305    );
4306    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
4307}
4308
4309/// What a verifier asks of a chain of custody beyond the links.
4310#[derive(Debug, Clone, Default)]
4311pub struct CustodyCheck<'a> {
4312    /// The robot's signed [`CUSTODY_HEAD_TYPE`] statement. Required unless
4313    /// `history_only` is set.
4314    pub head: Option<&'a Value>,
4315    /// Check the links alone. The result then names the last owner in the
4316    /// chain given and no current owner.
4317    pub history_only: bool,
4318    /// The head's `attestedAt` must be no older than this at `now`. `None`
4319    /// means [`CUSTODY_HEAD_MAX_AGE_SECONDS`].
4320    pub max_age_seconds: Option<i64>,
4321    /// When given, the head must carry exactly this challenge.
4322    pub challenge: Option<&'a str>,
4323}
4324
4325/// The outcome of [`verify_custody_chain`].
4326#[derive(Debug, Clone, Default, PartialEq, Eq)]
4327pub struct CustodyResult {
4328    pub ok: bool,
4329    /// The `toOwner` of the last transfer given (or the origin owner).
4330    pub last_owner: Option<String>,
4331    /// The owner the robot itself confirmed, set only when a head verified.
4332    pub current_owner: Option<String>,
4333}
4334
4335/// Verify an ordered list of transfer credentials forms a valid chain of custody
4336/// for `robot_did`, and that the robot itself confirms its end.
4337///
4338/// The links: every transfer verifies under the owner who signed it (keys from
4339/// `public_keys`), names the previous transfer's `id` as its
4340/// `prevTransferId`, is dated no earlier than the previous one, each `toOwner`
4341/// is the next transfer's `fromOwner`, and the first `fromOwner` is
4342/// `origin_owner` (required: with no known first owner, anyone could sign a
4343/// first transfer of any robot from themselves). Each link's signer is pinned,
4344/// so a did:key owner verifies under its own key.
4345///
4346/// The end: a chain cut short still links, so the links alone can't say who
4347/// owns the robot now. The robot's [`CUSTODY_HEAD_TYPE`] statement must verify
4348/// under the robot's key (from `public_keys`, or a did:key robot's own), name
4349/// the last transfer's `id` and its `toOwner`, be fresh at `now_iso`, and carry
4350/// `check.challenge` when one is given. Only then is `current_owner` set. With
4351/// `check.history_only` the head is not needed and `current_owner` stays empty.
4352pub fn verify_custody_chain(
4353    transfers: &[Value],
4354    public_keys: &[OwnerKey],
4355    robot_did: &str,
4356    origin_owner: Option<&str>,
4357    now_iso: &str,
4358    check: &CustodyCheck<'_>,
4359) -> Result<CustodyResult> {
4360    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); transfers, check);
4361    let refused = CustodyResult::default();
4362    let (ok, last_owner, last_id) =
4363        custody_links(transfers, public_keys, robot_did, origin_owner, now_iso)?;
4364    if !ok {
4365        return Ok(refused);
4366    }
4367    let Some(head) = check.head else {
4368        return Ok(if check.history_only {
4369            CustodyResult {
4370                ok: true,
4371                last_owner,
4372                current_owner: None,
4373            }
4374        } else {
4375            refused
4376        });
4377    };
4378    let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
4379    // The head must be the robot's own: its key from the map, or, when the map
4380    // has none for it, the key inside a did:key robot's DID.
4381    let keys = if public_keys.iter().any(|k| k.did == robot_did) {
4382        Keys::Map(&map)
4383    } else {
4384        Keys::Pinned(robot_did)
4385    };
4386    let v = match bound(head, keys, CUSTODY_HEAD_TYPE, now_iso, Window::FromRequired)? {
4387        Some(v) if issuer_is_subject(&v) && v.issuer == robot_did => v,
4388        _ => return Ok(refused),
4389    };
4390    let subject = &v.subject;
4391    let names_end = non_empty_str(subject, "owner") == last_owner.as_deref()
4392        && subject.get("headTransferId").and_then(|x| x.as_str()) == last_id.as_deref();
4393    let max_age = check
4394        .max_age_seconds
4395        .unwrap_or(CUSTODY_HEAD_MAX_AGE_SECONDS);
4396    let challenged = match check.challenge {
4397        None => true,
4398        Some(c) => !c.is_empty() && subject.get("challenge").and_then(|x| x.as_str()) == Some(c),
4399    };
4400    if !names_end || !fresh_at(subject, now_iso, max_age) || !challenged {
4401        return Ok(refused);
4402    }
4403    Ok(CustodyResult {
4404        ok: true,
4405        current_owner: last_owner.clone(),
4406        last_owner,
4407    })
4408}
4409
4410/// Parameters for [`build_key_rotation`]. The credential is signed by the old key
4411/// (the `signer_seed`) and issued under `robot_did`; the old key's public multibase
4412/// is recorded as `previousKey` and `new_key_multibase` as the authorized successor.
4413#[derive(Debug, Clone)]
4414pub struct BuildKeyRotation {
4415    pub robot_did: String,
4416    pub new_key_multibase: String,
4417    pub reason: Option<String>,
4418    pub valid_from: String,
4419}
4420
4421/// Build a key-rotation credential in which the robot's current (old) key
4422/// authorizes a new key. Signed by the old key, so anyone trusting the old key
4423/// can trust the new one. `old_key_seed` is the seed of the current key.
4424pub fn build_key_rotation(old_key_seed: &[u8], params: &BuildKeyRotation) -> Result<Value> {
4425    if params.new_key_multibase.is_empty() {
4426        return Err(CoreError::Json("new_key_multibase is required".into()));
4427    }
4428    let old_kp = keys::Ed25519KeyPair::from_seed_slice(old_key_seed)?;
4429
4430    let mut subject = Map::new();
4431    subject.insert("id".into(), json!(params.robot_did));
4432    subject.insert("previousKey".into(), json!(old_kp.public_multikey()));
4433    subject.insert("newKey".into(), json!(params.new_key_multibase));
4434    if let Some(reason) = &params.reason {
4435        subject.insert("reason".into(), json!(reason));
4436    }
4437
4438    let mut cred = Map::new();
4439    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4440    cred.insert(
4441        "type".into(),
4442        json!(["VerifiableCredential", KEY_ROTATION_TYPE]),
4443    );
4444    cred.insert("issuer".into(), json!(params.robot_did));
4445    cred.insert("validFrom".into(), json!(params.valid_from));
4446    cred.insert("credentialSubject".into(), Value::Object(subject));
4447
4448    let opts = BuildProofOptions::new(
4449        crate::verification_method::ed25519_method(&params.robot_did),
4450        &params.valid_from,
4451    );
4452    data_integrity::sign(&Value::Object(cred), old_key_seed, &opts)
4453}
4454
4455/// The raw Ed25519 key of a `z...` multikey, or `None`.
4456fn multikey_raw(v: Option<&Value>) -> Option<Vec<u8>> {
4457    let s = v.and_then(|x| x.as_str()).filter(|s| s.starts_with('z'))?;
4458    match multikey::decode(s) {
4459        Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => Some(d.raw_key),
4460        _ => None,
4461    }
4462}
4463
4464/// Verify a key rotation: the robot's OLD key signed it, binding the new key.
4465///
4466/// The rotation is a self-attestation: the issuer must be the robot
4467/// (`credentialSubject.id`), `previousKey` must decode to exactly the key the
4468/// caller trusts as the robot's current key (`old_keys`: a bare key, or a
4469/// `{robot_did: key}` source), the proof is checked under that key, and
4470/// `newKey` must decode and differ. When given, the rotation must be for
4471/// `robot_did`. Returns the credentialSubject (with `newKey` the successor).
4472pub fn verify_key_rotation(
4473    credential: &Value,
4474    old_keys: Keys<'_>,
4475    robot_did: Option<&str>,
4476    now_iso: &str,
4477) -> Result<Option<Value>> {
4478    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
4479    let now = rv::require_now(now_iso)?;
4480    let issuer = match rv::issuer_id(credential.get("issuer")) {
4481        Some(i) => i.to_string(),
4482        None => return Ok(None),
4483    };
4484    let trusted: Option<Vec<u8>> = match old_keys {
4485        Keys::Embedded | Keys::Pinned(_) => None,
4486        Keys::Bare(k) => Some(k.to_vec()),
4487        Keys::One(did, k) => (did == issuer).then(|| k.to_vec()),
4488        Keys::Map(m) => m.get(&issuer).cloned(),
4489        Keys::Resolver(f) => f(&issuer),
4490    };
4491    let trusted = match trusted {
4492        Some(t) if t.len() == 32 => t,
4493        _ => return Ok(None),
4494    };
4495    let previous = credential
4496        .get("credentialSubject")
4497        .and_then(|s| s.get("previousKey"));
4498    if multikey_raw(previous) != Some(trusted.clone()) {
4499        return Ok(None);
4500    }
4501    let v = match rv::verify_robotics_credential(
4502        credential,
4503        Keys::One(&issuer, &trusted),
4504        Some(KEY_ROTATION_TYPE),
4505        now,
4506        VerifyOptions::window(Window::FromRequired),
4507    ) {
4508        Ok(v) if issuer_is_subject(&v) => v,
4509        _ => return Ok(None),
4510    };
4511    if robot_did.is_some_and(|r| r != v.issuer) {
4512        return Ok(None);
4513    }
4514    match multikey_raw(v.subject.get("newKey")) {
4515        Some(n) if n != trusted => Ok(Some(v.subject)),
4516        _ => Ok(None),
4517    }
4518}
4519
4520/// Verify an ordered list of key rotations forms one linear key history from
4521/// `origin_key_multibase`. Each rotation must be signed by the key it rotates
4522/// from, decoded from the multibase itself; every rotation is for the same
4523/// robot (`robot_did` when given, else the first rotation's robot) and dated no
4524/// earlier than the one before; a key that appears twice (a fork or a cycle)
4525/// is refused. Returns `(ok, current_key)`.
4526pub fn verify_key_history(
4527    rotations: &[Value],
4528    origin_key_multibase: &str,
4529    robot_did: Option<&str>,
4530    now_iso: &str,
4531) -> Result<(bool, Option<String>)> {
4532    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); rotations);
4533    rv::require_now(now_iso)?;
4534    let origin = match multikey_raw(Some(&json!(origin_key_multibase))) {
4535        Some(o) => o,
4536        None => return Ok((false, None)),
4537    };
4538    let mut current_key = origin_key_multibase.to_string();
4539    let mut current_raw = origin.clone();
4540    let mut seen: HashSet<Vec<u8>> = HashSet::from([origin]);
4541    let mut pinned: Option<String> = robot_did.map(String::from);
4542    let mut prev_time: Option<i128> = None;
4543    for rotation in rotations {
4544        let subject = match verify_key_rotation(
4545            rotation,
4546            Keys::Bare(&current_raw),
4547            pinned.as_deref(),
4548            now_iso,
4549        )? {
4550            Some(s) => s,
4551            None => return Ok((false, None)),
4552        };
4553        if pinned.is_none() {
4554            pinned = subject.get("id").and_then(|v| v.as_str()).map(String::from);
4555        }
4556        match rv::time_ns(rotation.get("validFrom")) {
4557            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
4558            _ => return Ok((false, None)),
4559        }
4560        let new_raw = match multikey_raw(subject.get("newKey")) {
4561            Some(n) if !seen.contains(&n) => n,
4562            _ => return Ok((false, None)),
4563        };
4564        seen.insert(new_raw.clone());
4565        current_raw = new_raw;
4566        current_key = subject
4567            .get("newKey")
4568            .and_then(|v| v.as_str())
4569            .unwrap_or("")
4570            .to_string();
4571    }
4572    Ok((true, Some(current_key)))
4573}
4574
4575/// Parameters for [`build_decommission`]. The signer is the owner or an authority;
4576/// `final_disposition` records the outcome (for example recycled, destroyed, or
4577/// transferred to parts). When `valid_until` is set it bounds the credential.
4578#[derive(Debug, Clone)]
4579pub struct BuildDecommission {
4580    pub issuer_did: String,
4581    pub robot_did: String,
4582    pub reason: String,
4583    pub final_disposition: Option<String>,
4584    pub valid_from: String,
4585    pub valid_until: Option<String>,
4586}
4587
4588/// Build a signed decommission credential retiring `robot_did`. After
4589/// decommissioning, a verifier should refuse to trust the robot. `decommissionedBy`
4590/// is the issuer DID.
4591pub fn build_decommission(signer_seed: &[u8], params: &BuildDecommission) -> Result<Value> {
4592    if params.reason.is_empty() {
4593        return Err(CoreError::Json("reason is required".into()));
4594    }
4595    let mut subject = Map::new();
4596    subject.insert("id".into(), json!(params.robot_did));
4597    subject.insert("reason".into(), json!(params.reason));
4598    subject.insert("decommissionedBy".into(), json!(params.issuer_did));
4599    if let Some(disposition) = &params.final_disposition {
4600        subject.insert("finalDisposition".into(), json!(disposition));
4601    }
4602
4603    let mut cred = Map::new();
4604    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4605    cred.insert(
4606        "type".into(),
4607        json!(["VerifiableCredential", DECOMMISSION_TYPE]),
4608    );
4609    cred.insert("issuer".into(), json!(params.issuer_did));
4610    cred.insert("validFrom".into(), json!(params.valid_from));
4611    if let Some(vu) = &params.valid_until {
4612        cred.insert("validUntil".into(), json!(vu));
4613    }
4614    cred.insert("credentialSubject".into(), Value::Object(subject));
4615
4616    let opts = BuildProofOptions::new(
4617        crate::verification_method::ed25519_method(&params.issuer_did),
4618        &params.valid_from,
4619    );
4620    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
4621}
4622
4623/// Verify a decommission credential: the proof bound to the issuer, the
4624/// window at `now_iso` (validFrom required), `decommissionedBy` (when present)
4625/// equal to the issuer, the issuer in `trusted_authorities` when supplied, and
4626/// (when given) the credential is about `robot_did`.
4627pub fn verify_decommission(
4628    credential: &Value,
4629    keys: Keys<'_>,
4630    trusted_authorities: Option<&HashSet<String>>,
4631    robot_did: Option<&str>,
4632    now_iso: &str,
4633) -> Result<Option<Value>> {
4634    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
4635    let now = rv::require_now(now_iso)?;
4636    let opts = VerifyOptions {
4637        trusted_issuers: trusted_authorities,
4638        ..VerifyOptions::window(Window::FromRequired)
4639    };
4640    let v = match rv::verify_robotics_credential(
4641        credential,
4642        keys,
4643        Some(DECOMMISSION_TYPE),
4644        now,
4645        opts,
4646    ) {
4647        Ok(v) => v,
4648        Err(_) => return Ok(None),
4649    };
4650    if let Some(by) = v.subject.get("decommissionedBy") {
4651        if by.as_str() != Some(v.issuer.as_str()) {
4652            return Ok(None);
4653        }
4654    }
4655    if robot_did.is_some_and(|r| v.subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
4656        return Ok(None);
4657    }
4658    Ok(Some(v.subject))
4659}
4660
4661// ---------------------------------------------------------------------------
4662// Regulatory conformance profiles (Phase 5.14)
4663// ---------------------------------------------------------------------------
4664//
4665// A conformance profile is a machine-checkable mapping from Vouch robotics
4666// credentials to the clauses of a public safety or AI regulation. Given the
4667// credentials a robot presents, the checker reports which clauses are satisfied
4668// and cites each one, and an issuer can sign a point-in-time conformance
4669// attestation an auditor or notified body can consume. The profiles are plain
4670// data so every language reproduces them identically.
4671//
4672// This is the open layer: declarative profiles, a deterministic checker, and a
4673// signed point-in-time attestation over the full report. It is a reference
4674// crosswalk to make conformance verifiable in the open, not legal advice.
4675
4676pub const CONFORMANCE_ATTESTATION_TYPE: &str = "RobotConformanceAttestation";
4677
4678/// How well-sourced a requirement's clause citation is. A profile can be a
4679/// useful crosswalk while its citations are only as good as the sources that
4680/// were available, and a reader is entitled to know which. Every report and
4681/// every signed attestation carries these, so a conformance result never
4682/// implies more authority over the regulation than it has.
4683///
4684/// The clause text was read from the official published source.
4685pub const CITATION_VERIFIED_PRIMARY: &str = "verified-primary";
4686/// The mapping is believed sound, but the clause number comes from secondary
4687/// sources rather than the standard or official journal itself. The default,
4688/// because it is the honest default.
4689pub const CITATION_UNVERIFIED_SECONDARY: &str = "unverified-secondary";
4690/// Not a clause reference at all, only a description of the topic. An assessor
4691/// cannot look it up.
4692pub const CITATION_DESCRIPTIVE: &str = "descriptive";
4693
4694/// Every citation provenance value, in report order.
4695pub const CITATION_STATUSES: &[&str] = &[
4696    CITATION_VERIFIED_PRIMARY,
4697    CITATION_UNVERIFIED_SECONDARY,
4698    CITATION_DESCRIPTIVE,
4699];
4700
4701// Citation notes shared by several requirements. Macros rather than consts so
4702// they can be `concat!`-ed into the longer per-requirement notes, byte-for-byte
4703// identical with the Python, TypeScript and Go profiles.
4704macro_rules! iso_paywall_note {
4705    () => {
4706        "Clause number taken from secondary sources; the standard is paywalled \
4707         and the text has not been read."
4708    };
4709}
4710
4711macro_rules! iso_10218_note {
4712    () => {
4713        concat!(
4714            iso_paywall_note!(),
4715            " ISO 10218-1/-2:2011 were superseded by the 2025 editions (in \
4716             force 1 April 2025); this mapping still cites the 2011 clause \
4717             numbering and has not been migrated."
4718        )
4719    };
4720}
4721
4722macro_rules! oj_note {
4723    () => {
4724        "Article number taken from a third-party reproduction of the Official \
4725         Journal text, not from EUR-Lex itself."
4726    };
4727}
4728
4729macro_rules! ul_note {
4730    () => {
4731        "UL 3300 (now ANSI/CAN/UL 3300:2024) is paywalled and no clause \
4732         numbering was available; this names the topic only and cannot be \
4733         looked up."
4734    };
4735}
4736
4737/// One requirement in a profile: a clause of a regulation mapped to the
4738/// credential type and field paths that satisfy it.
4739struct ProfileRequirement {
4740    id: &'static str,
4741    clause: &'static str,
4742    title: &'static str,
4743    credential: &'static str,
4744    fields: &'static [&'static str],
4745    /// Subject paths that must hold boolean `true`, for requirements where mere
4746    /// presence is not evidence: a heartbeat reporting an envelope breach is not
4747    /// evidence of having stayed inside the envelope. This is the boolean subset
4748    /// of the `expect` map the Python, TypeScript and Go profiles carry; the
4749    /// built-in profiles use only boolean expectations.
4750    expect_true: &'static [&'static str],
4751    /// Provenance of the `clause` reference above, one of [`CITATION_STATUSES`].
4752    citation: &'static str,
4753    /// Anything a reader should know about the citation, such as a known
4754    /// conflict between sources.
4755    citation_note: Option<&'static str>,
4756}
4757
4758/// A built-in conformance profile: a regime, a version, and its requirements.
4759struct ConformanceProfile {
4760    regime: &'static str,
4761    version: &'static str,
4762    requirements: &'static [ProfileRequirement],
4763}
4764
4765const ISO_10218_REQUIREMENTS: &[ProfileRequirement] = &[
4766    ProfileRequirement {
4767        id: "iso10218-identification",
4768        clause: "ISO 10218-1:2011, 5.2",
4769        title: "Robot identification bound to its hardware",
4770        credential: "RobotIdentityCredential",
4771        fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
4772        expect_true: &[],
4773        citation: CITATION_UNVERIFIED_SECONDARY,
4774        citation_note: Some(iso_10218_note!()),
4775    },
4776    ProfileRequirement {
4777        id: "iso10218-software-integrity",
4778        clause: "ISO 10218-1:2011, 5.3",
4779        title: "Control software and configuration integrity",
4780        credential: "ModelProvenanceAttestation",
4781        fields: &["vla.weightsHash"],
4782        expect_true: &[],
4783        citation: CITATION_UNVERIFIED_SECONDARY,
4784        citation_note: Some(iso_10218_note!()),
4785    },
4786    ProfileRequirement {
4787        id: "iso10218-limits",
4788        clause: "ISO 10218-1:2011, 5.6",
4789        title: "Limiting of speed, force, and workspace",
4790        credential: "PhysicalCapabilityScope",
4791        fields: &[
4792            "physicalScope.maxForceN",
4793            "physicalScope.maxSpeedMps",
4794            "physicalScope.allowedZones",
4795        ],
4796        expect_true: &[],
4797        citation: CITATION_UNVERIFIED_SECONDARY,
4798        citation_note: Some(iso_10218_note!()),
4799    },
4800    ProfileRequirement {
4801        id: "iso10218-records",
4802        clause: "ISO 10218-2:2011, 5.2",
4803        title: "Records of safety-relevant events",
4804        credential: "RobotSafetyRecordCredential",
4805        fields: &["totalEvents", "logHead"],
4806        expect_true: &[],
4807        citation: CITATION_UNVERIFIED_SECONDARY,
4808        citation_note: Some(iso_10218_note!()),
4809    },
4810];
4811
4812const ISO_TS_15066_REQUIREMENTS: &[ProfileRequirement] = &[
4813    ProfileRequirement {
4814        id: "iso15066-power-force-limiting",
4815        clause: "ISO/TS 15066:2016, 5.5.4",
4816        title: "Power and force limiting near humans",
4817        credential: "PhysicalCapabilityScope",
4818        fields: &[
4819            "physicalScope.maxSpeedNearHumansMps",
4820            "physicalScope.maxForceN",
4821        ],
4822        expect_true: &[],
4823        citation: CITATION_UNVERIFIED_SECONDARY,
4824        citation_note: Some(concat!(
4825            iso_paywall_note!(),
4826            " Secondary sources disagree on whether power and force limiting \
4827             is 5.5.4 or 5.5.2; confirm against the published table of \
4828             contents before relying on the number."
4829        )),
4830    },
4831    ProfileRequirement {
4832        id: "iso15066-collaborative-workspace",
4833        clause: "ISO/TS 15066:2016, 5.5.2",
4834        title: "Defined collaborative workspace",
4835        credential: "PhysicalCapabilityScope",
4836        fields: &["physicalScope.allowedZones"],
4837        expect_true: &[],
4838        citation: CITATION_UNVERIFIED_SECONDARY,
4839        citation_note: Some(concat!(
4840            iso_paywall_note!(),
4841            " Shares the unresolved 5.5.2/5.5.4 numbering conflict with \
4842             iso15066-power-force-limiting."
4843        )),
4844    },
4845    ProfileRequirement {
4846        id: "iso15066-monitoring",
4847        clause: "ISO/TS 15066:2016, 5.2",
4848        title: "Continuous monitoring of the collaborative operation",
4849        credential: "RobotHeartbeatCredential",
4850        fields: &["motionDigest"],
4851        expect_true: &["motionDigest.withinEnvelope"],
4852        citation: CITATION_UNVERIFIED_SECONDARY,
4853        citation_note: Some(iso_paywall_note!()),
4854    },
4855];
4856
4857const EU_MACHINERY_REQUIREMENTS: &[ProfileRequirement] = &[
4858    ProfileRequirement {
4859        id: "eu-mr-identification",
4860        clause: "Reg (EU) 2023/1230, Annex III 1.7.4",
4861        title: "Machinery identification and traceability",
4862        credential: "RobotIdentityCredential",
4863        fields: &["make", "model", "serial"],
4864        expect_true: &[],
4865        citation: CITATION_UNVERIFIED_SECONDARY,
4866        citation_note: Some(oj_note!()),
4867    },
4868    ProfileRequirement {
4869        id: "eu-mr-software-integrity",
4870        clause: "Reg (EU) 2023/1230, Annex III 1.1.9",
4871        title: "Protection against corruption of safety software",
4872        credential: "ModelProvenanceAttestation",
4873        fields: &["vla.weightsHash", "vla.safetyPolicy"],
4874        expect_true: &[],
4875        citation: CITATION_UNVERIFIED_SECONDARY,
4876        citation_note: Some(concat!(
4877            oj_note!(),
4878            " The Annex III subclause for protection against corruption has \
4879             not been confirmed and may need to be re-pointed."
4880        )),
4881    },
4882    ProfileRequirement {
4883        id: "eu-mr-safe-limits",
4884        clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
4885        title: "Safety and reliability of control systems and limits",
4886        credential: "PhysicalCapabilityScope",
4887        fields: &["physicalScope.maxForceN"],
4888        expect_true: &[],
4889        citation: CITATION_UNVERIFIED_SECONDARY,
4890        citation_note: Some(oj_note!()),
4891    },
4892    ProfileRequirement {
4893        id: "eu-mr-records",
4894        clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
4895        title: "Recording of safety-relevant data",
4896        credential: "RobotSafetyRecordCredential",
4897        fields: &["totalEvents", "logHead"],
4898        expect_true: &[],
4899        citation: CITATION_UNVERIFIED_SECONDARY,
4900        citation_note: Some(oj_note!()),
4901    },
4902];
4903
4904const EU_AI_ACT_REQUIREMENTS: &[ProfileRequirement] = &[
4905    ProfileRequirement {
4906        id: "eu-aia-record-keeping",
4907        clause: "Reg (EU) 2024/1689, Art. 12",
4908        title: "Automatic recording of events (logging)",
4909        credential: "RobotSafetyRecordCredential",
4910        fields: &["logHead"],
4911        expect_true: &[],
4912        citation: CITATION_UNVERIFIED_SECONDARY,
4913        citation_note: Some(oj_note!()),
4914    },
4915    ProfileRequirement {
4916        id: "eu-aia-transparency",
4917        clause: "Reg (EU) 2024/1689, Art. 13",
4918        title: "Model and configuration transparency",
4919        credential: "ModelProvenanceAttestation",
4920        fields: &["vla.modelName", "vla.configHash"],
4921        expect_true: &[],
4922        citation: CITATION_UNVERIFIED_SECONDARY,
4923        citation_note: Some(oj_note!()),
4924    },
4925    ProfileRequirement {
4926        id: "eu-aia-human-oversight",
4927        clause: "Reg (EU) 2024/1689, Art. 14",
4928        title: "Human oversight through enforced operating limits",
4929        credential: "PhysicalCapabilityScope",
4930        fields: &["physicalScope.maxSpeedNearHumansMps"],
4931        expect_true: &[],
4932        citation: CITATION_UNVERIFIED_SECONDARY,
4933        citation_note: Some(concat!(
4934            oj_note!(),
4935            " Art. 14 also requires a means for the overseer to intervene or \
4936             stop the system, which an operating-limit scope alone does not \
4937             evidence."
4938        )),
4939    },
4940    ProfileRequirement {
4941        id: "eu-aia-accuracy-robustness",
4942        clause: "Reg (EU) 2024/1689, Art. 15",
4943        title: "Accuracy and robustness traceable to a known build",
4944        credential: "ModelProvenanceAttestation",
4945        fields: &["vla.weightsHash"],
4946        expect_true: &[],
4947        citation: CITATION_UNVERIFIED_SECONDARY,
4948        citation_note: Some(oj_note!()),
4949    },
4950];
4951
4952const UL_3300_REQUIREMENTS: &[ProfileRequirement] = &[
4953    ProfileRequirement {
4954        id: "ul3300-identity",
4955        clause: "UL 3300, identification",
4956        title: "Robot identity bound to its hardware",
4957        credential: "RobotIdentityCredential",
4958        fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
4959        expect_true: &[],
4960        citation: CITATION_DESCRIPTIVE,
4961        citation_note: Some(ul_note!()),
4962    },
4963    ProfileRequirement {
4964        id: "ul3300-operating-limits",
4965        clause: "UL 3300, operating limits",
4966        title: "Enforced speed and zone limits",
4967        credential: "PhysicalCapabilityScope",
4968        fields: &["physicalScope.maxSpeedMps", "physicalScope.allowedZones"],
4969        expect_true: &[],
4970        citation: CITATION_DESCRIPTIVE,
4971        citation_note: Some(ul_note!()),
4972    },
4973    ProfileRequirement {
4974        id: "ul3300-perception-integrity",
4975        clause: "UL 3300, sensing integrity",
4976        title: "Integrity of perception used for safe operation",
4977        credential: "PerceptionProvenanceCredential",
4978        fields: &["frameHash"],
4979        expect_true: &[],
4980        citation: CITATION_DESCRIPTIVE,
4981        citation_note: Some(ul_note!()),
4982    },
4983    ProfileRequirement {
4984        id: "ul3300-records",
4985        clause: "UL 3300, incident records",
4986        title: "Records of safety-relevant incidents",
4987        credential: "RobotSafetyRecordCredential",
4988        fields: &["totalEvents", "logHead"],
4989        expect_true: &[],
4990        citation: CITATION_DESCRIPTIVE,
4991        citation_note: Some(ul_note!()),
4992    },
4993];
4994
4995/// Return a built-in profile by id, or `None` if it is unknown. The five profiles
4996/// cover ISO 10218-1/-2 (industrial), ISO/TS 15066 (collaborative), the EU
4997/// Machinery Regulation 2023/1230, the EU AI Act high-risk requirements, and
4998/// UL 3300 (service and mobile robots).
4999fn conformance_profile(profile_id: &str) -> Option<ConformanceProfile> {
5000    match profile_id {
5001        "iso-10218" => Some(ConformanceProfile {
5002            regime: "ISO 10218-1/-2 industrial robots",
5003            version: "2011 (superseded by the 2025 editions; mapping not yet migrated)",
5004            requirements: ISO_10218_REQUIREMENTS,
5005        }),
5006        "iso-ts-15066" => Some(ConformanceProfile {
5007            regime: "ISO/TS 15066 collaborative robots",
5008            version: "2016",
5009            requirements: ISO_TS_15066_REQUIREMENTS,
5010        }),
5011        "eu-machinery-2023-1230" => Some(ConformanceProfile {
5012            regime: "EU Machinery Regulation 2023/1230",
5013            version: "2023",
5014            requirements: EU_MACHINERY_REQUIREMENTS,
5015        }),
5016        "eu-ai-act-high-risk" => Some(ConformanceProfile {
5017            regime: "EU AI Act high-risk systems",
5018            version: "2024",
5019            requirements: EU_AI_ACT_REQUIREMENTS,
5020        }),
5021        "ul-3300" => Some(ConformanceProfile {
5022            regime: "UL 3300 service, communication, and mobile robots",
5023            version: "2022 (see ANSI/CAN/UL 3300:2024)",
5024            requirements: UL_3300_REQUIREMENTS,
5025        }),
5026        _ => None,
5027    }
5028}
5029
5030/// A built-in conformance profile as JSON (`{regime, version, requirements:
5031/// [{id, clause, title, credential, fields, expect, citation,
5032/// citationNote?}]}`), or `null` for an unknown id.
5033pub fn conformance_profile_json(profile_id: &str) -> Value {
5034    let Some(p) = conformance_profile(profile_id) else {
5035        return Value::Null;
5036    };
5037    let requirements: Vec<Value> = p
5038        .requirements
5039        .iter()
5040        .map(|r| {
5041            let expect: Map<String, Value> = r
5042                .expect_true
5043                .iter()
5044                .map(|f| (f.to_string(), Value::Bool(true)))
5045                .collect();
5046            let mut m = Map::new();
5047            m.insert("id".into(), json!(r.id));
5048            m.insert("clause".into(), json!(r.clause));
5049            m.insert("title".into(), json!(r.title));
5050            m.insert("credential".into(), json!(r.credential));
5051            m.insert("fields".into(), json!(r.fields));
5052            m.insert("expect".into(), Value::Object(expect));
5053            m.insert("citation".into(), json!(r.citation));
5054            if let Some(n) = r.citation_note {
5055                m.insert("citationNote".into(), json!(n));
5056            }
5057            Value::Object(m)
5058        })
5059        .collect();
5060    json!({"regime": p.regime, "version": p.version, "requirements": requirements})
5061}
5062
5063/// The type array of a credential, accepting a JSON string or an array of strings.
5064fn credential_types(credential: &Value) -> Vec<&str> {
5065    match credential.get("type") {
5066        Some(Value::String(s)) => vec![s.as_str()],
5067        Some(Value::Array(items)) => items.iter().filter_map(|v| v.as_str()).collect(),
5068        _ => Vec::new(),
5069    }
5070}
5071
5072/// Follow a dot-separated path from the credentialSubject, returning the value at
5073/// the leaf or `None` if any segment is missing or not an object.
5074fn path_value<'a>(subject: &'a Value, path: &str) -> Option<&'a Value> {
5075    let mut node = subject;
5076    for part in path.split('.') {
5077        match node {
5078            Value::Object(map) => match map.get(part) {
5079                Some(v) => node = v,
5080                None => return None,
5081            },
5082            _ => return None,
5083        }
5084    }
5085    Some(node)
5086}
5087
5088/// True when a value is present and non-empty: not null, and not an empty array
5089/// or empty object. Any other value (including `false`, `0`, or `""`) counts.
5090fn value_present(value: &Value) -> bool {
5091    match value {
5092        Value::Null => false,
5093        Value::Array(a) => !a.is_empty(),
5094        Value::Object(o) => !o.is_empty(),
5095        _ => true,
5096    }
5097}
5098
5099/// True when `credential` satisfies `requirement`: its type array includes the
5100/// requirement's credential type, its credentialSubject has a non-null,
5101/// non-empty value at every field path, and every `expect_true` path holds
5102/// boolean `true`. Presence alone is not evidence: a heartbeat that reports an
5103/// envelope breach does not evidence having stayed inside the envelope.
5104fn credential_satisfies(credential: &Value, requirement: &ProfileRequirement) -> bool {
5105    if !credential_types(credential).contains(&requirement.credential) {
5106        return false;
5107    }
5108    let empty = Value::Object(Map::new());
5109    let subject = credential.get("credentialSubject").unwrap_or(&empty);
5110    for path in requirement.fields {
5111        match path_value(subject, path) {
5112            Some(v) if value_present(v) => {}
5113            _ => return false,
5114        }
5115    }
5116    for path in requirement.expect_true {
5117        if path_value(subject, path) != Some(&Value::Bool(true)) {
5118            return false;
5119        }
5120    }
5121    true
5122}
5123
5124/// Check the presented `credentials` against the named profile and return a
5125/// deterministic report. Each requirement is satisfied when some presented
5126/// credential matches its type and has every required field. The caller is
5127/// expected to have verified the credentials' signatures first; this checks
5128/// structure and coverage, not proofs.
5129///
5130/// Every requirement carries the provenance of its clause citation, and the
5131/// report totals them, so a result never reads as more authoritative about the
5132/// regulation than its sources are.
5133///
5134/// The report has exactly `{profileId, regime, version, conforms,
5135/// satisfiedCount, totalCount, citations:{...},
5136/// requirements:[{id, clause, title, satisfied, citation, citationNote?}]}`.
5137pub fn check_conformance(credentials: &[Value], profile_id: &str) -> Result<Value> {
5138    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credentials);
5139    check_conformance_for(credentials, profile_id, None)
5140}
5141
5142/// [`check_conformance`] bound to one robot: with `robot_did`, only credentials
5143/// whose `credentialSubject.id` is that robot count (so another robot's
5144/// credential mixed into the set cannot fill a gap), and the report carries
5145/// `robotDid`.
5146pub fn check_conformance_for(
5147    credentials: &[Value],
5148    profile_id: &str,
5149    robot_did: Option<&str>,
5150) -> Result<Value> {
5151    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credentials);
5152    let prof = conformance_profile(profile_id)
5153        .ok_or_else(|| CoreError::Json(format!("unknown conformance profile: {profile_id}")))?;
5154    if robot_did.is_some_and(str::is_empty) {
5155        return Err(CoreError::Json("robot_did must be a non-empty DID".into()));
5156    }
5157    let presented: Vec<&Value> = credentials
5158        .iter()
5159        .filter(|c| c.is_object())
5160        .filter(|c| {
5161            robot_did.is_none_or(|r| {
5162                c.get("credentialSubject")
5163                    .and_then(|s| s.get("id"))
5164                    .and_then(|x| x.as_str())
5165                    == Some(r)
5166            })
5167        })
5168        .collect();
5169
5170    let mut results: Vec<Value> = Vec::with_capacity(prof.requirements.len());
5171    let mut satisfied = 0i64;
5172    let mut citations = Map::new();
5173    for status in CITATION_STATUSES {
5174        citations.insert((*status).into(), json!(0i64));
5175    }
5176    for requirement in prof.requirements {
5177        let ok = presented
5178            .iter()
5179            .any(|c| credential_satisfies(c, requirement));
5180        if ok {
5181            satisfied += 1;
5182        }
5183        let seen = citations
5184            .get(requirement.citation)
5185            .and_then(|v| v.as_i64())
5186            .unwrap_or(0);
5187        citations.insert(requirement.citation.into(), json!(seen + 1));
5188        let mut result = Map::new();
5189        result.insert("id".into(), json!(requirement.id));
5190        result.insert("clause".into(), json!(requirement.clause));
5191        result.insert("title".into(), json!(requirement.title));
5192        result.insert("satisfied".into(), json!(ok));
5193        result.insert("citation".into(), json!(requirement.citation));
5194        if let Some(note) = requirement.citation_note {
5195            result.insert("citationNote".into(), json!(note));
5196        }
5197        results.push(Value::Object(result));
5198    }
5199    let total = prof.requirements.len() as i64;
5200
5201    let mut report = Map::new();
5202    report.insert("profileId".into(), json!(profile_id));
5203    report.insert("regime".into(), json!(prof.regime));
5204    report.insert("version".into(), json!(prof.version));
5205    report.insert("conforms".into(), json!(satisfied == total));
5206    report.insert("satisfiedCount".into(), json!(satisfied));
5207    report.insert("totalCount".into(), json!(total));
5208    report.insert("citations".into(), Value::Object(citations));
5209    report.insert("requirements".into(), Value::Array(results));
5210    if let Some(r) = robot_did {
5211        report.insert("robotDid".into(), json!(r));
5212    }
5213    Ok(Value::Object(report))
5214}
5215
5216/// Multibase SHA-256 of the JCS-canonical report, for binding into an
5217/// attestation. Every language canonicalizes identically, so the digest is the
5218/// same byte string everywhere.
5219pub fn report_digest(report: &Value) -> String {
5220    mb64(&Sha256::digest(jcs::canonicalize(report)))
5221}
5222
5223/// Parameters for [`build_conformance_attestation`]. The signer is the robot, its
5224/// owner, or an assessing authority; `robot_did` names the robot the attestation
5225/// is about. `report` is produced by [`check_conformance`] and is embedded and
5226/// bound by digest. When `valid_seconds` is set it bounds the attestation.
5227#[derive(Debug, Clone)]
5228pub struct BuildConformanceAttestation {
5229    pub issuer_did: String,
5230    pub robot_did: String,
5231    pub report: Value,
5232    pub valid_from: String,
5233    pub valid_until: Option<String>,
5234}
5235
5236/// Build a signed point-in-time `RobotConformanceAttestation` for `robot_did`
5237/// over a `report` produced by [`check_conformance`]. The report is embedded and
5238/// bound by digest.
5239pub fn build_conformance_attestation(
5240    signer_seed: &[u8],
5241    params: &BuildConformanceAttestation,
5242) -> Result<Value> {
5243    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
5244    if params.robot_did.is_empty() {
5245        return Err(CoreError::Json("robot_did is required".into()));
5246    }
5247    let report = params
5248        .report
5249        .as_object()
5250        .ok_or_else(|| CoreError::Json("report must come from check_conformance".into()))?;
5251    if !report.contains_key("profileId") || !report.contains_key("conforms") {
5252        return Err(CoreError::Json(
5253            "report must come from check_conformance".into(),
5254        ));
5255    }
5256
5257    let mut subject = Map::new();
5258    subject.insert("id".into(), json!(params.robot_did));
5259    subject.insert(
5260        "profileId".into(),
5261        report.get("profileId").cloned().unwrap_or(Value::Null),
5262    );
5263    subject.insert(
5264        "regime".into(),
5265        report.get("regime").cloned().unwrap_or(Value::Null),
5266    );
5267    subject.insert(
5268        "conforms".into(),
5269        report.get("conforms").cloned().unwrap_or(Value::Null),
5270    );
5271    subject.insert(
5272        "satisfiedCount".into(),
5273        report.get("satisfiedCount").cloned().unwrap_or(Value::Null),
5274    );
5275    subject.insert(
5276        "totalCount".into(),
5277        report.get("totalCount").cloned().unwrap_or(Value::Null),
5278    );
5279    subject.insert(
5280        "citations".into(),
5281        report
5282            .get("citations")
5283            .cloned()
5284            .unwrap_or_else(|| Value::Object(Map::new())),
5285    );
5286    subject.insert("reportDigest".into(), json!(report_digest(&params.report)));
5287    subject.insert("report".into(), params.report.clone());
5288
5289    let mut cred = Map::new();
5290    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5291    cred.insert(
5292        "type".into(),
5293        json!(["VerifiableCredential", CONFORMANCE_ATTESTATION_TYPE]),
5294    );
5295    cred.insert("issuer".into(), json!(params.issuer_did));
5296    cred.insert("validFrom".into(), json!(params.valid_from));
5297    if let Some(vu) = &params.valid_until {
5298        cred.insert("validUntil".into(), json!(vu));
5299    }
5300    cred.insert("credentialSubject".into(), Value::Object(subject));
5301
5302    let opts = BuildProofOptions::new(
5303        crate::verification_method::ed25519_method(&params.issuer_did),
5304        &params.valid_from,
5305    );
5306    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
5307}
5308
5309/// Verify a conformance attestation: the issuer's proof bound to the issuer,
5310/// the window at `now_iso` (validFrom required), that the embedded report
5311/// matches its bound digest, that every summary field (profileId, regime,
5312/// conforms, satisfiedCount, totalCount) matches the report, and that
5313/// `conforms` is a boolean. When given, the attestation must be about
5314/// `robot_did` and its issuer must be in `trusted_issuers`. Returns the
5315/// credentialSubject on success, `None` if invalid.
5316pub fn verify_conformance_attestation(
5317    credential: &Value,
5318    keys: Keys<'_>,
5319    robot_did: Option<&str>,
5320    trusted_issuers: Option<&HashSet<String>>,
5321    now_iso: &str,
5322) -> Result<Option<Value>> {
5323    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5324    let now = rv::require_now(now_iso)?;
5325    let opts = VerifyOptions {
5326        trusted_issuers,
5327        ..VerifyOptions::window(Window::FromRequired)
5328    };
5329    let v = match rv::verify_robotics_credential(
5330        credential,
5331        keys,
5332        Some(CONFORMANCE_ATTESTATION_TYPE),
5333        now,
5334        opts,
5335    ) {
5336        Ok(v) => v,
5337        Err(_) => return Ok(None),
5338    };
5339    let subject = v.subject;
5340    let embedded = match subject.get("report") {
5341        Some(r) if r.is_object() => r,
5342        _ => return Ok(None),
5343    };
5344    if subject.get("reportDigest").and_then(|v| v.as_str())
5345        != Some(report_digest(embedded).as_str())
5346    {
5347        return Ok(None);
5348    }
5349    for name in [
5350        "profileId",
5351        "regime",
5352        "conforms",
5353        "satisfiedCount",
5354        "totalCount",
5355    ] {
5356        if subject.get(name) != embedded.get(name) {
5357            return Ok(None);
5358        }
5359    }
5360    if !subject.get("conforms").is_some_and(|c| c.is_boolean()) {
5361        return Ok(None);
5362    }
5363    // A report bound to one robot cannot be attested as being about another.
5364    if embedded.get("robotDid").is_some() && embedded.get("robotDid") != subject.get("id") {
5365        return Ok(None);
5366    }
5367    if robot_did.is_some_and(|r| subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
5368        return Ok(None);
5369    }
5370    Ok(Some(subject))
5371}
5372
5373// ---------------------------------------------------------------------------
5374// Post-quantum robot credentials (Phase 5.13)
5375// ---------------------------------------------------------------------------
5376//
5377// A robot fielded today lives for ten to twenty years, longer than classical
5378// Ed25519 is expected to stay safe, so a robot identity signed now could be
5379// forged once a quantum computer arrives. This section makes the hybrid
5380// post-quantum cryptosuite (`hybrid-eddsa-mldsa44-jcs-2026`, a classical
5381// Ed25519 signature alongside an ML-DSA-44 signature) available for robot
5382// credentials so they stay unforgeable across the robot's whole service life.
5383//
5384//   - sign_pq: attach a hybrid proof to a robot credential.
5385//   - verify_robot_credential: verify a robot credential whether it carries a
5386//     classical or a hybrid proof, auto-detected from the proof, so a fleet can
5387//     move to PQ gradually without breaking the classical credentials already in
5388//     the field.
5389//   - migrate_to_pq: re-sign a fielded robot's classical credential under PQ.
5390//
5391// This is the open layer: hybrid signing, backward-compatible verification, and
5392// a software re-signing migration path. It reuses the proof set of
5393// [`crate::hybrid`] and the ML-DSA-44 and multikey helpers rather than
5394// re-deriving any cryptography.
5395
5396/// The classical (Ed25519-only) robot credential cryptosuite.
5397pub const CLASSICAL_CRYPTOSUITE: &str = data_integrity::CRYPTOSUITE_ID;
5398/// The ML-DSA-44 proof a post-quantum robot credential carries next to its
5399/// classical proof, in a proof set.
5400pub const POST_QUANTUM_CRYPTOSUITE: &str = hybrid::MLDSA44_CRYPTOSUITE_ID;
5401
5402/// Coerce an ML-DSA-44 public key supplied either as raw 1312-byte bytes or as a
5403/// Multikey string into raw bytes. Errors on the wrong length or a non-ML-DSA
5404/// multikey.
5405pub fn coerce_mldsa44_public(mldsa44_public: &[u8]) -> Result<Vec<u8>> {
5406    if mldsa44_public.len() != MLDSA44_PUBLIC_LEN {
5407        return Err(CoreError::InvalidKeyLength {
5408            expected: MLDSA44_PUBLIC_LEN,
5409            got: mldsa44_public.len(),
5410        });
5411    }
5412    Ok(mldsa44_public.to_vec())
5413}
5414
5415/// Coerce an ML-DSA-44 Multikey string into raw public-key bytes. Errors if the
5416/// multikey does not carry an ML-DSA-44 key.
5417pub fn mldsa44_public_from_multikey(multikey_str: &str) -> Result<Vec<u8>> {
5418    let decoded = multikey::decode(multikey_str)?;
5419    if decoded.algorithm != "ML-DSA-44" {
5420        return Err(CoreError::InvalidMultikey(format!(
5421            "expected an ML-DSA-44 multikey, got {}",
5422            decoded.algorithm
5423        )));
5424    }
5425    coerce_mldsa44_public(&decoded.raw_key)
5426}
5427
5428fn pq_verification_method(credential: &Value) -> String {
5429    let issuer = credential
5430        .as_object()
5431        .and_then(|o| o.get("issuer"))
5432        .and_then(|v| v.as_str())
5433        .unwrap_or("");
5434    crate::verification_method::ed25519_method(issuer)
5435}
5436
5437/// The ML-DSA-44 verification method slot, matching the `#key-2` convention the
5438/// language SDKs derive for the post-quantum member of a proof set.
5439fn pq_mldsa_verification_method(credential: &Value) -> String {
5440    let issuer = credential
5441        .as_object()
5442        .and_then(|o| o.get("issuer"))
5443        .and_then(|v| v.as_str())
5444        .unwrap_or("");
5445    format!("{issuer}#key-2")
5446}
5447
5448/// Attach a hybrid (classical Ed25519 plus post-quantum ML-DSA-44) Data Integrity
5449/// proof to a pre-built robot `credential`. Any existing proof is replaced. The
5450/// robot signs with its Ed25519 seed and its ML-DSA-44 key pair; `created` is the
5451/// caller-supplied ISO-8601 instant, keeping the core deterministic.
5452pub fn sign_pq(
5453    credential: &Value,
5454    ed25519_seed: &[u8],
5455    mldsa: &MlDsa44KeyPair,
5456    created: &str,
5457) -> Result<Value> {
5458    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5459    let ed_vm = pq_verification_method(credential);
5460    let ml_vm = pq_mldsa_verification_method(credential);
5461    hybrid::sign_dual(credential, ed25519_seed, mldsa, &ed_vm, &ml_vm, created)
5462}
5463
5464/// Return true if `credential` carries a post-quantum proof: a `proof` array
5465/// holding an ML-DSA-44 proof. One proof object is never post-quantum (the
5466/// earlier composite proof is refused by every verifier).
5467pub fn is_pq(credential: &Value) -> bool {
5468    crate::nesting::deep_guard!(false; credential);
5469    match credential.as_object().and_then(|o| o.get("proof")) {
5470        Some(Value::Array(proofs)) => proofs
5471            .iter()
5472            .any(|p| hybrid::Suite::of_proof(p) == Some(hybrid::Suite::Mldsa44)),
5473        _ => false,
5474    }
5475}
5476
5477/// Verify a post-quantum robot credential: a proof set whose Ed25519 and
5478/// ML-DSA-44 signatures both validate. One proof object is refused, the
5479/// earlier composite proof included.
5480fn verify_pq_proof_set(
5481    credential: &Value,
5482    ed25519_public_key: &[u8],
5483    mldsa44_public_key: &[u8],
5484) -> Result<bool> {
5485    match credential.as_object().and_then(|o| o.get("proof")) {
5486        Some(Value::Array(_)) => {
5487            hybrid::verify_dual(credential, ed25519_public_key, mldsa44_public_key)
5488        }
5489        _ => Ok(false),
5490    }
5491}
5492
5493/// Verify a hybrid robot credential. Both the Ed25519 and the ML-DSA-44 signature
5494/// MUST validate. `mldsa44_public_key` is raw 1312-byte bytes or an ML-DSA-44
5495/// Multikey string (pass `mldsa44_multikey` for the string form).
5496pub fn verify_pq(
5497    credential: &Value,
5498    ed25519_public_key: &[u8],
5499    mldsa44_public_key: &[u8],
5500) -> Result<bool> {
5501    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5502    let resolved_ml = coerce_mldsa44_public(mldsa44_public_key)?;
5503    verify_pq_proof_set(credential, ed25519_public_key, &resolved_ml)
5504}
5505
5506/// [`verify_robot_credential`] with the ML-DSA-44 key taken from a key source
5507/// like the Ed25519 key: a bare key, or a `{did: key}` map / resolver from which
5508/// the entry for the credential's issuer is used (no entry fails a
5509/// post-quantum credential). Map values are raw 1312-byte keys or ML-DSA-44
5510/// Multikey strings as UTF-8 bytes.
5511pub fn verify_robot_credential_keyed(
5512    credential: &Value,
5513    ed_keys: Keys<'_>,
5514    mldsa44_keys: Option<Keys<'_>>,
5515    expected_type: Option<&str>,
5516    now_iso: &str,
5517) -> Result<bool> {
5518    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5519    let ml = match mldsa44_keys {
5520        None => return verify_robot_credential(credential, ed_keys, None, expected_type, now_iso),
5521        Some(k) => k,
5522    };
5523    let issuer = rv::issuer_id(credential.get("issuer"))
5524        .unwrap_or("")
5525        .to_string();
5526    let picked: Option<Vec<u8>> = match ml {
5527        Keys::Embedded | Keys::Pinned(_) => None,
5528        Keys::Bare(k) => Some(k.to_vec()),
5529        Keys::One(d, k) => (d == issuer).then(|| k.to_vec()),
5530        Keys::Map(m) => m.get(&issuer).cloned(),
5531        Keys::Resolver(f) => f(&issuer),
5532    };
5533    match picked {
5534        Some(k) => verify_robot_credential(credential, ed_keys, Some(&k), expected_type, now_iso),
5535        // A post-quantum credential needs its issuer's ML-DSA key; a classical
5536        // one given an ML-DSA source is refused by the same rule as a bare key.
5537        None => Ok(false),
5538    }
5539}
5540
5541/// The backward-compatible robot credential verify a fleet uses while
5542/// migrating to post-quantum: auto-detects a hybrid proof set.
5543///
5544/// Every proof must be bound to the issuer (`proofPurpose` assertionMethod and
5545/// a verification method of the issuer DID), and the Ed25519 key must belong to
5546/// the issuer (the key inside a did:key, or `ed_keys` as a `{did: key}`
5547/// source for any other DID). Present validity bounds must be strict protocol
5548/// times with `now_iso` inside. When `expected_type` is given the credential
5549/// must carry it. A post-quantum credential requires `mldsa44_public_key`;
5550/// supplying one for a classical credential refuses it (so a stripped ML-DSA
5551/// proof cannot pass as classical). Malformed input returns `false`.
5552pub fn verify_robot_credential(
5553    credential: &Value,
5554    ed_keys: Keys<'_>,
5555    mldsa44_public_key: Option<&[u8]>,
5556    expected_type: Option<&str>,
5557    now_iso: &str,
5558) -> Result<bool> {
5559    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5560    let now = rv::require_now(now_iso)?;
5561    if !credential.is_object() {
5562        return Ok(false);
5563    }
5564    if is_pq(credential) {
5565        let ml = match mldsa44_public_key {
5566            Some(k) => k,
5567            None => return Ok(false),
5568        };
5569        let issuer = match rv::issuer_id(credential.get("issuer")) {
5570            Some(i) => i,
5571            None => return Ok(false),
5572        };
5573        if rv::input_too_large(credential, rv::MAX_CREDENTIAL_BYTES).is_some() {
5574            return Ok(false);
5575        }
5576        let types: Vec<&str> = match credential.get("type") {
5577            Some(Value::String(t)) => vec![t.as_str()],
5578            Some(Value::Array(a)) if a.iter().all(|t| t.is_string()) => {
5579                a.iter().filter_map(|t| t.as_str()).collect()
5580            }
5581            _ => return Ok(false),
5582        };
5583        if expected_type.is_some_and(|e| !types.contains(&e)) {
5584            return Ok(false);
5585        }
5586        let members: Vec<&Value> = match credential.get("proof") {
5587            Some(Value::Array(a)) => a.iter().collect(),
5588            Some(p) => vec![p],
5589            None => return Ok(false),
5590        };
5591        if members.is_empty()
5592            || members
5593                .iter()
5594                .any(|m| rv::proof_unbound_reason(m, issuer).is_some())
5595        {
5596            return Ok(false);
5597        }
5598        if rv::window_reason(credential, Window::IfPresent, now, 0).is_some() {
5599            return Ok(false);
5600        }
5601        let ed = match rv::resolve_issuer_key(issuer, ed_keys) {
5602            Ok(k) => k,
5603            Err(_) => return Ok(false),
5604        };
5605        let resolved_ml = match resolve_mldsa44_public(ml) {
5606            Ok(m) => m,
5607            Err(_) => return Ok(false),
5608        };
5609        return Ok(verify_pq_proof_set(credential, &ed, &resolved_ml).unwrap_or(false));
5610    }
5611    if mldsa44_public_key.is_some() {
5612        return Ok(false);
5613    }
5614    Ok(rv::verify_robotics_credential(
5615        credential,
5616        ed_keys,
5617        expected_type,
5618        now,
5619        VerifyOptions::window(Window::IfPresent),
5620    )
5621    .is_ok())
5622}
5623
5624/// Resolve an ML-DSA-44 public key given either raw bytes or a Multikey string.
5625/// A 1312-byte input is the raw key; otherwise it is parsed as a UTF-8 Multikey.
5626pub fn resolve_mldsa44_public(mldsa44_public_key: &[u8]) -> Result<Vec<u8>> {
5627    if mldsa44_public_key.len() == MLDSA44_PUBLIC_LEN {
5628        return Ok(mldsa44_public_key.to_vec());
5629    }
5630    let s = core::str::from_utf8(mldsa44_public_key).map_err(|_| {
5631        CoreError::InvalidMultikey("ML-DSA-44 key must be raw bytes or a Multikey string".into())
5632    })?;
5633    mldsa44_public_from_multikey(s)
5634}
5635
5636/// Re-sign a fielded robot's classical `credential` under the hybrid PQ
5637/// cryptosuite, preserving its body. The robot holds its current Ed25519 seed and
5638/// an ML-DSA-44 key pair; `created` is the caller-supplied re-signing instant.
5639pub fn migrate_to_pq(
5640    credential: &Value,
5641    ed25519_seed: &[u8],
5642    mldsa: &MlDsa44KeyPair,
5643    created: &str,
5644) -> Result<Value> {
5645    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5646    sign_pq(credential, ed25519_seed, mldsa, created)
5647}
5648
5649// ---------------------------------------------------------------------------
5650// Cross-embodiment identity continuity (Phase 5.15)
5651// ---------------------------------------------------------------------------
5652//
5653// An AI agent (a policy with its own Vouch identity) can run on one robot body
5654// today and a different body tomorrow. An embodiment credential binds the agent
5655// identity to a specific body (a hardware-rooted robot identity) and that body's
5656// hardware root for a period, signed by the agent's own persistent key. Linking
5657// each embodiment to the previous forms a continuity chain a verifier walks to
5658// confirm the same accountable agent persisted across bodies, re-binding to each
5659// body's hardware root as it moved. A fork check confirms the agent was never
5660// actively embodied in two bodies at once.
5661//
5662// This is the inverse of the ownership custody chain: there one body passes
5663// between owners; here one mind passes between bodies, and the constant that
5664// signs every link is the agent identity itself.
5665//
5666// This is the open layer: plain signed embodiment credentials, continuity-chain
5667// verification, and software fork detection. It reuses the core proof path
5668// ([`data_integrity`]) rather than re-deriving any cryptography.
5669
5670pub const EMBODIMENT_TYPE: &str = "AgentEmbodimentCredential";
5671
5672/// Parameters for [`build_embodiment`]. The signer is the agent's own persistent
5673/// key; `agent_did` is both issuer and subject id, so the whole continuity chain
5674/// is signed by one accountable identity. `from_body`, when set, links this
5675/// embodiment to the body the agent left, forming the chain. `valid_until`, when
5676/// set, bounds the active window (used by [`check_no_fork`]).
5677#[derive(Debug, Clone)]
5678pub struct BuildEmbodiment {
5679    pub agent_did: String,
5680    pub body_did: String,
5681    pub body_hardware_root: String,
5682    pub from_body: Option<String>,
5683    pub embodied_at: String,
5684    pub valid_until: Option<String>,
5685}
5686
5687/// Build a signed embodiment credential: the agent `agent_did` authorizes running
5688/// on `body_did`, re-binding to that body's hardware root `body_hardware_root`.
5689/// Signed by the agent's own persistent key. `from_body` links this embodiment to
5690/// the body the agent left.
5691pub fn build_embodiment(agent_seed: &[u8], params: &BuildEmbodiment) -> Result<Value> {
5692    if params.agent_did.is_empty()
5693        || params.body_did.is_empty()
5694        || params.body_hardware_root.is_empty()
5695    {
5696        return Err(CoreError::Json(
5697            "agent_did, body_did, and body_hardware_root are required".into(),
5698        ));
5699    }
5700
5701    let mut subject = Map::new();
5702    subject.insert("id".into(), json!(params.agent_did));
5703    subject.insert("body".into(), json!(params.body_did));
5704    subject.insert("bodyHardwareRoot".into(), json!(params.body_hardware_root));
5705    if let Some(from_body) = &params.from_body {
5706        subject.insert("fromBody".into(), json!(from_body));
5707    }
5708
5709    let mut cred = Map::new();
5710    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5711    cred.insert(
5712        "type".into(),
5713        json!(["VerifiableCredential", EMBODIMENT_TYPE]),
5714    );
5715    cred.insert("issuer".into(), json!(params.agent_did));
5716    cred.insert("validFrom".into(), json!(params.embodied_at));
5717    if let Some(vu) = &params.valid_until {
5718        cred.insert("validUntil".into(), json!(vu));
5719    }
5720    cred.insert("credentialSubject".into(), Value::Object(subject));
5721
5722    let opts = BuildProofOptions::new(
5723        crate::verification_method::ed25519_method(&params.agent_did),
5724        &params.embodied_at,
5725    );
5726    data_integrity::sign(&Value::Object(cred), agent_seed, &opts)
5727}
5728
5729/// Verify an embodiment credential: the agent's proof bound to the agent as
5730/// issuer (a mind authorizes its own embodiment, so the issuer must be
5731/// `credentialSubject.id`), the window at `now_iso` (validFrom required), and
5732/// that the subject carries a `body` and a `bodyHardwareRoot`. When
5733/// `body_hardware_roots` (body DID -> trusted hardware-root key) is given, the
5734/// credential's `bodyHardwareRoot` must match the entry for its body. Returns
5735/// the credentialSubject on success, `None` if invalid.
5736pub fn verify_embodiment(
5737    credential: &Value,
5738    agent_keys: Keys<'_>,
5739    body_hardware_roots: Option<&alloc::collections::BTreeMap<String, String>>,
5740    now_iso: &str,
5741) -> Result<Option<Value>> {
5742    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5743    let v = match bound(
5744        credential,
5745        agent_keys,
5746        EMBODIMENT_TYPE,
5747        now_iso,
5748        Window::FromRequired,
5749    )? {
5750        Some(v) if issuer_is_subject(&v) => v,
5751        _ => return Ok(None),
5752    };
5753    let body = non_empty_str(&v.subject, "body");
5754    let root = non_empty_str(&v.subject, "bodyHardwareRoot");
5755    let (body, root) = match (body, root) {
5756        (Some(b), Some(r)) => (b, r),
5757        _ => return Ok(None),
5758    };
5759    if let Some(roots) = body_hardware_roots {
5760        if roots.get(body).map(String::as_str) != Some(root) {
5761            return Ok(None);
5762        }
5763    }
5764    Ok(Some(v.subject))
5765}
5766
5767/// Verify an ordered list of embodiment credentials forms a valid continuity
5768/// chain: every link verifies under the same agent (the persistent mind), each
5769/// link's `fromBody` matches the previous link's `body`, and (when given) the
5770/// first `fromBody` is `origin_body`. Links start in order; each earlier link
5771/// must still have been valid when the next one started, and the last link
5772/// must be valid at `now_iso`. The verified links are then checked for forks.
5773/// Returns `(ok, current_body)`.
5774pub fn verify_continuity_chain(
5775    embodiments: &[Value],
5776    agent_keys: Keys<'_>,
5777    origin_body: Option<&str>,
5778    body_hardware_roots: Option<&alloc::collections::BTreeMap<String, String>>,
5779    now_iso: &str,
5780) -> Result<(bool, Option<String>)> {
5781    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); embodiments);
5782    rv::require_now(now_iso)?;
5783    let mut expected_from: Option<String> = origin_body.map(String::from);
5784    let mut current_body: Option<String> = origin_body.map(String::from);
5785    let mut agent: Option<String> = None;
5786    let mut prev_start: Option<i128> = None;
5787    for (i, embodiment) in embodiments.iter().enumerate() {
5788        let at: String = match embodiments.get(i + 1) {
5789            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
5790                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
5791                _ => return Ok((false, None)),
5792            },
5793            None => now_iso.to_string(),
5794        };
5795        let subject = match verify_embodiment(embodiment, agent_keys, body_hardware_roots, &at)? {
5796            Some(s) => s,
5797            None => return Ok((false, None)),
5798        };
5799        let id = subject.get("id").and_then(|v| v.as_str()).map(String::from);
5800        match &agent {
5801            None => agent = id,
5802            Some(a) if id.as_deref() == Some(a.as_str()) => {}
5803            _ => return Ok((false, None)),
5804        }
5805        match rv::time_ns(embodiment.get("validFrom")) {
5806            Some(t) if prev_start.is_none_or(|p| t >= p) => prev_start = Some(t),
5807            _ => return Ok((false, None)),
5808        }
5809        if let Some(expected) = &expected_from {
5810            if subject.get("fromBody").and_then(|v| v.as_str()) != Some(expected.as_str()) {
5811                return Ok((false, None));
5812            }
5813        }
5814        current_body = subject
5815            .get("body")
5816            .and_then(|v| v.as_str())
5817            .map(String::from);
5818        expected_from = current_body.clone();
5819    }
5820    if !check_no_fork(embodiments)?.0 {
5821        return Ok((false, None));
5822    }
5823    Ok((true, current_body))
5824}
5825
5826/// Two conflicting bodies surfaced by [`check_no_fork`].
5827#[derive(Debug, Clone, PartialEq, Eq)]
5828pub struct ForkConflict {
5829    pub body_a: String,
5830    pub body_b: String,
5831}
5832
5833/// Half-open intervals [start, end); a missing end is open-ended (+infinity). A
5834/// clean handover sets one window's end to the next window's start, which does not
5835/// overlap.
5836fn windows_overlap(start_a: i128, end_a: Option<i128>, start_b: i128, end_b: Option<i128>) -> bool {
5837    let a_before_b = end_a.map(|e| e <= start_b).unwrap_or(false);
5838    let b_before_a = end_b.map(|e| e <= start_a).unwrap_or(false);
5839    !(a_before_b || b_before_a)
5840}
5841
5842/// Confirm no two embodiments place the agent in different bodies with overlapping
5843/// active windows. Each embodiment is active from `validFrom` to `validUntil` (a
5844/// missing `validUntil` is treated as open-ended). Two embodiments on different
5845/// bodies whose windows overlap are a fork. Returns `(ok, conflict)` where
5846/// conflict, when present, names the two conflicting bodies.
5847pub fn check_no_fork(embodiments: &[Value]) -> Result<(bool, Option<ForkConflict>)> {
5848    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); embodiments);
5849    let mut windows: Vec<(String, i128, Option<i128>)> = Vec::with_capacity(embodiments.len());
5850    for embodiment in embodiments {
5851        let subject = embodiment
5852            .get("credentialSubject")
5853            .and_then(|s| s.as_object());
5854        let body = subject
5855            .and_then(|s| s.get("body"))
5856            .and_then(|v| v.as_str())
5857            .filter(|s| !s.is_empty());
5858        let start = rv::time_ns(embodiment.get("validFrom"));
5859        let (body, start) = match (body, start) {
5860            (Some(b), Some(s)) => (b.to_string(), s),
5861            _ => return Ok((false, None)),
5862        };
5863        // A present end must be a strict time; only an absent end is open-ended.
5864        let end = match embodiment.get("validUntil") {
5865            None => None,
5866            Some(v) => match rv::time_ns(Some(v)) {
5867                Some(t) => Some(t),
5868                None => return Ok((false, None)),
5869            },
5870        };
5871        windows.push((body, start, end));
5872    }
5873
5874    let Some(first) = first_forked_index(&windows) else {
5875        return Ok((true, None));
5876    };
5877    let (body_i, start_i, end_i) = &windows[first];
5878    for (body_j, start_j, end_j) in &windows[first + 1..] {
5879        if body_i != body_j && windows_overlap(*start_i, *end_i, *start_j, *end_j) {
5880            return Ok((
5881                false,
5882                Some(ForkConflict {
5883                    body_a: body_i.clone(),
5884                    body_b: body_j.clone(),
5885                }),
5886            ));
5887        }
5888    }
5889    unreachable!("the forked window has a partner")
5890}
5891
5892/// The most windows on one body a segmented fork check keeps at once (the
5893/// windows whose ends still matter). A real history holds a handful; a
5894/// history that needs more is refused and must be checked whole.
5895pub const MAX_FORK_WINDOWS: usize = 4096;
5896
5897/// Why a segmented fork check failed for a reason other than a fork.
5898#[derive(Debug, Clone, PartialEq, Eq)]
5899pub enum ForkFailure {
5900    /// An embodiment has no body, no valid `validFrom`, or a `validUntil`
5901    /// that is not a protocol time. The whole check answers `(false, None)`.
5902    Malformed(u64),
5903    /// An embodiment starts before the one before it. The segmented check
5904    /// reads a history in `validFrom` order.
5905    OutOfOrder(u64),
5906    /// More than [`MAX_FORK_WINDOWS`] windows on one body overlap at once.
5907    TooManyWindows(u64),
5908}
5909
5910/// Where a fork check stands after the first embodiments of a history, so a
5911/// long history is checked one segment at a time with bounded memory. The
5912/// history must be in `validFrom` order (the order a history is recorded
5913/// in); for such a history the verdict after the last segment is the one
5914/// [`check_no_fork`] gives for the whole list, conflict included.
5915///
5916/// The bookkeeping: while no fork has been seen, every window still open at
5917/// the latest start is on one body (two such windows on different bodies
5918/// would overlap). `windows` keeps, for that body, the points where the
5919/// latest end so far grows: `(start, latest end up to that start)`, with
5920/// `None` for an open end. A later window on another body forks exactly
5921/// when some kept window that starts before its end also ends after its
5922/// start.
5923#[derive(Debug, Clone, PartialEq, Eq)]
5924pub struct ForkProgress {
5925    /// Embodiments checked so far.
5926    pub count: u64,
5927    /// The latest `validFrom` seen, in nanoseconds.
5928    pub last_start: Option<i128>,
5929    /// The body every open window is on.
5930    pub body: Option<String>,
5931    /// `(start, latest end)` steps for `body`, oldest first.
5932    pub windows: Vec<(i128, Option<i128>)>,
5933    /// The first fork, as [`check_no_fork`] reports it.
5934    pub conflict: Option<ForkConflict>,
5935    /// A failure that is not a fork.
5936    pub failure: Option<ForkFailure>,
5937}
5938
5939impl Default for ForkProgress {
5940    fn default() -> Self {
5941        Self::start()
5942    }
5943}
5944
5945/// `a` ends after instant `t` (an open end is after everything).
5946fn ends_after(end: Option<i128>, t: i128) -> bool {
5947    end.is_none_or(|e| e > t)
5948}
5949
5950impl ForkProgress {
5951    pub fn start() -> Self {
5952        Self {
5953            count: 0,
5954            last_start: None,
5955            body: None,
5956            windows: Vec::new(),
5957            conflict: None,
5958            failure: None,
5959        }
5960    }
5961
5962    /// The verdict over every embodiment checked so far: `(ok, conflict)`
5963    /// as [`check_no_fork`] gives it, plus a reason when not ok.
5964    pub fn result(&self) -> (bool, Option<ForkConflict>, Option<String>) {
5965        match &self.failure {
5966            Some(ForkFailure::Malformed(i)) => (
5967                false,
5968                None,
5969                Some(format!(
5970                    "embodiment {i} has no body, or a bad validFrom or validUntil"
5971                )),
5972            ),
5973            Some(ForkFailure::OutOfOrder(i)) => (
5974                false,
5975                None,
5976                Some(format!(
5977                    "embodiment {i} starts before the one before it; a segmented check reads the history in validFrom order"
5978                )),
5979            ),
5980            Some(ForkFailure::TooManyWindows(i)) => (
5981                false,
5982                None,
5983                Some(format!(
5984                    "at embodiment {i} more than {MAX_FORK_WINDOWS} windows on one body are open at once; check this history whole"
5985                )),
5986            ),
5987            None => match &self.conflict {
5988                Some(c) => (
5989                    false,
5990                    Some(c.clone()),
5991                    Some("the agent is in two bodies at once".into()),
5992                ),
5993                None => (true, None, None),
5994            },
5995        }
5996    }
5997}
5998
5999/// Check the next `embodiments` of a history (one segment) for forks and
6000/// move `progress` past them.
6001pub fn check_no_fork_segment(progress: &mut ForkProgress, embodiments: &[Value]) {
6002    #[cfg(not(feature = "std"))]
6003    if crate::nesting::Nested::nests_past(&embodiments, crate::nesting::NO_STD_MAX_NESTING) {
6004        progress.failure = Some(ForkFailure::Malformed(progress.count));
6005        return;
6006    }
6007    #[cfg(not(feature = "std"))]
6008    if crate::nesting::Nested::nests_past(&embodiments, crate::nesting::NO_STD_MAX_NESTING) {
6009        progress.failure = Some(ForkFailure::Malformed(progress.count));
6010        return;
6011    }
6012    for embodiment in embodiments {
6013        let i = progress.count;
6014        progress.count = progress.count.saturating_add(1);
6015        if matches!(
6016            progress.failure,
6017            Some(ForkFailure::Malformed(_)) | Some(ForkFailure::OutOfOrder(_))
6018        ) {
6019            continue;
6020        }
6021        let body = embodiment
6022            .get("credentialSubject")
6023            .and_then(|s| s.as_object())
6024            .and_then(|s| s.get("body"))
6025            .and_then(|v| v.as_str())
6026            .filter(|s| !s.is_empty());
6027        let start = rv::time_ns(embodiment.get("validFrom"));
6028        let end = match embodiment.get("validUntil") {
6029            None => Ok(None),
6030            Some(v) => rv::time_ns(Some(v)).map(Some).ok_or(()),
6031        };
6032        let (body, start, end) = match (body, start, end) {
6033            (Some(b), Some(s), Ok(e)) => (b, s, e),
6034            _ => {
6035                // The whole check answers (false, None) for a malformed
6036                // entry anywhere in the list, a fork or not.
6037                progress.failure = Some(ForkFailure::Malformed(i));
6038                continue;
6039            }
6040        };
6041        if progress.conflict.is_some() || progress.failure.is_some() {
6042            // The verdict is set; only a malformed entry can still change it.
6043            continue;
6044        }
6045        if progress.last_start.is_some_and(|p| start < p) {
6046            progress.failure = Some(ForkFailure::OutOfOrder(i));
6047            continue;
6048        }
6049        progress.last_start = Some(start);
6050        // Steps whose latest end is not after this start can never overlap
6051        // this or any later window (later windows start no earlier).
6052        let live = progress
6053            .windows
6054            .iter()
6055            .position(|(_, e)| ends_after(*e, start))
6056            .unwrap_or(progress.windows.len());
6057        progress.windows.drain(..live);
6058        if progress.windows.is_empty() {
6059            progress.body = None;
6060        }
6061        let same_body = progress.body.as_deref() == Some(body);
6062        if !same_body && progress.body.is_some() {
6063            // The latest end over the open windows on the other body that
6064            // start before this window's end. A window that ends after it
6065            // starts is past every kept start.
6066            let latest = progress
6067                .windows
6068                .iter()
6069                .take_while(|(s, _)| end.is_none_or(|e| *s < e))
6070                .last()
6071                .map(|(_, e)| *e);
6072            if let Some(latest) = latest {
6073                if ends_after(latest, start) {
6074                    progress.conflict = Some(ForkConflict {
6075                        body_a: progress.body.clone().unwrap_or_default(),
6076                        body_b: body.to_string(),
6077                    });
6078                    continue;
6079                }
6080            }
6081        }
6082        // A window that ends at or before its start never overlaps a later
6083        // window, so it is not kept.
6084        if !ends_after(end, start) {
6085            continue;
6086        }
6087        if !same_body {
6088            progress.body = Some(body.to_string());
6089            progress.windows.clear();
6090        }
6091        let grows = match progress.windows.last() {
6092            None => true,
6093            Some((_, latest)) => match (latest, end) {
6094                (None, _) => false,
6095                (Some(_), None) => true,
6096                (Some(l), Some(e)) => e > *l,
6097            },
6098        };
6099        if grows {
6100            if progress.windows.len() >= MAX_FORK_WINDOWS {
6101                progress.failure = Some(ForkFailure::TooManyWindows(i));
6102                continue;
6103            }
6104            progress.windows.push((start, end));
6105        }
6106    }
6107}
6108
6109/// The smallest i whose window overlaps a later window on another body, or
6110/// None: the window a pairwise scan in list order reports first, found in
6111/// O(n log n).
6112///
6113/// Times become ranks. Walking the list from the end, a Fenwick tree indexed by
6114/// start rank holds the later windows; each node keeps the latest end for its
6115/// range plus the latest end on any other body. Window i overlaps a later
6116/// window j on another body exactly when some j with start_j < end_i, on
6117/// another body, has end_j > start_i.
6118fn first_forked_index(windows: &[(String, i128, Option<i128>)]) -> Option<usize> {
6119    let mut times: Vec<i128> = windows
6120        .iter()
6121        .flat_map(|(_, s, e)| core::iter::once(*s).chain(*e))
6122        .collect();
6123    times.sort_unstable();
6124    times.dedup();
6125    let size = times.len();
6126    let rank = |t: i128| times.binary_search(&t).expect("every time is ranked") as i64;
6127    let mut body_ids: crate::collections::HashMap<&str, i64> = crate::collections::HashMap::new();
6128    let ranked: Vec<(i64, i64, i64)> = windows
6129        .iter()
6130        .map(|(b, s, e)| {
6131            let next = body_ids.len() as i64;
6132            let id = *body_ids.entry(b.as_str()).or_insert(next);
6133            (id, rank(*s), e.map_or(size as i64, rank))
6134        })
6135        .collect();
6136
6137    let mut tree = vec![TopTwo::EMPTY; size + 1];
6138    let mut first = None;
6139    for i in (0..ranked.len()).rev() {
6140        let (body, start, end) = ranked[i];
6141        let mut acc = TopTwo::EMPTY;
6142        let mut k = (end as usize).min(size);
6143        while k > 0 {
6144            acc.add(tree[k].end, tree[k].body);
6145            acc.add(tree[k].other_end, tree[k].other_body);
6146            k &= k - 1;
6147        }
6148        let other_end = if acc.body != body {
6149            acc.end
6150        } else {
6151            acc.other_end
6152        };
6153        if other_end > start {
6154            first = Some(i);
6155        }
6156        let mut k = start as usize + 1;
6157        while k <= size {
6158            tree[k].add(end, body);
6159            k += k & k.wrapping_neg();
6160        }
6161    }
6162    first
6163}
6164
6165/// The latest end in a range, and the latest end on a body other than its own.
6166#[derive(Clone, Copy)]
6167struct TopTwo {
6168    end: i64,
6169    body: i64,
6170    other_end: i64,
6171    other_body: i64,
6172}
6173
6174impl TopTwo {
6175    const EMPTY: TopTwo = TopTwo {
6176        end: -1,
6177        body: -1,
6178        other_end: -1,
6179        other_body: -1,
6180    };
6181
6182    fn add(&mut self, end: i64, body: i64) {
6183        if body < 0 {
6184            return;
6185        }
6186        if body == self.body {
6187            self.end = self.end.max(end);
6188        } else if body == self.other_body {
6189            if end > self.other_end {
6190                self.other_end = end;
6191                if self.other_end > self.end {
6192                    core::mem::swap(&mut self.end, &mut self.other_end);
6193                    core::mem::swap(&mut self.body, &mut self.other_body);
6194                }
6195            }
6196        } else if end > self.end {
6197            self.other_end = self.end;
6198            self.other_body = self.body;
6199            self.end = end;
6200            self.body = body;
6201        } else if end > self.other_end {
6202            self.other_end = end;
6203            self.other_body = body;
6204        }
6205    }
6206}
6207
6208// ---------------------------------------------------------------------------
6209// Physical custody handoff (Phase 5.16)
6210// ---------------------------------------------------------------------------
6211//
6212// A physical task or object passes across a chain of actors, human and robot: a
6213// person picks an item, hands it to a robot, that robot hands it to another
6214// robot, which places it. Each handoff is a signed custody transition, so a
6215// physical-world event traces to the exact hop and the actor responsible.
6216//
6217// A custody handoff credential records that a receiving actor accepted custody
6218// of a task or object from a releasing actor, signed by the receiver. Linking
6219// each handoff to the previous forms a chain a verifier walks to establish who
6220// held the task at any time. A condition attested at each handoff lets a state
6221// change be localized to the specific hop whose holder was responsible.
6222//
6223// This is the open layer: signed handoff credentials, chain verification, a
6224// holder-at-time helper, and software condition localization. It reuses the core
6225// proof path ([`data_integrity`]) rather than re-deriving any cryptography.
6226
6227pub const CUSTODY_HANDOFF_TYPE: &str = "CustodyHandoffCredential";
6228
6229/// A signed custody release: the actor handing a task over states that it
6230/// releases custody to the receiver. The receiver embeds it in its handoff.
6231pub const CUSTODY_RELEASE_TYPE: &str = "CustodyReleaseCredential";
6232
6233/// Build a signed custody release by `releaser_did` (the signer) for
6234/// `task_id` to `to_actor`, dated `released_at`.
6235pub fn build_release(
6236    releaser_seed: &[u8],
6237    releaser_did: &str,
6238    task_id: &str,
6239    to_actor: &str,
6240    released_at: &str,
6241) -> Result<Value> {
6242    if task_id.is_empty() || to_actor.is_empty() {
6243        return Err(CoreError::Json("task_id and to_actor are required".into()));
6244    }
6245    let cred = json!({
6246        "@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
6247        "type": ["VerifiableCredential", CUSTODY_RELEASE_TYPE],
6248        "issuer": releaser_did,
6249        "validFrom": released_at,
6250        "credentialSubject": {"id": task_id, "fromActor": releaser_did, "toActor": to_actor},
6251    });
6252    let opts = BuildProofOptions::new(
6253        crate::verification_method::ed25519_method(releaser_did),
6254        released_at,
6255    );
6256    data_integrity::sign(&cred, releaser_seed, &opts)
6257}
6258
6259/// Parameters for [`build_handoff`]. The signer is the receiver (`to_actor`), the
6260/// party taking responsibility. `condition`, when set, attests the state of the
6261/// task or object as received, which lets a later state change be localized to
6262/// a hop. `release` is the releasing actor's signed [`build_release`]
6263/// credential (a chain verifier requires it). `prev_handoff_id` is the previous
6264/// handoff's `id`; `credential_id` is this handoff's own `id`. `valid_until`,
6265/// when set, bounds the handoff's active window.
6266#[derive(Debug, Clone)]
6267pub struct BuildHandoff {
6268    pub task_id: String,
6269    pub from_actor: String,
6270    pub to_actor: String,
6271    pub condition: Option<String>,
6272    pub handoff_at: String,
6273    pub valid_until: Option<String>,
6274    pub release: Option<Value>,
6275    pub prev_handoff_id: Option<String>,
6276    pub credential_id: String,
6277}
6278
6279/// Build a signed custody handoff: the receiving actor `to_actor` accepts custody
6280/// of `task_id` from `from_actor`, signed by the receiver. The issuer is the
6281/// receiver, so a party attests its own acceptance of custody.
6282pub fn build_handoff(receiver_seed: &[u8], params: &BuildHandoff) -> Result<Value> {
6283    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
6284    if params.task_id.is_empty() || params.from_actor.is_empty() || params.to_actor.is_empty() {
6285        return Err(CoreError::Json(
6286            "task_id, from_actor, and to_actor are required".into(),
6287        ));
6288    }
6289    if params.credential_id.is_empty() {
6290        return Err(CoreError::Json("credential_id is required".into()));
6291    }
6292
6293    let mut subject = Map::new();
6294    subject.insert("id".into(), json!(params.task_id));
6295    subject.insert("fromActor".into(), json!(params.from_actor));
6296    subject.insert("toActor".into(), json!(params.to_actor));
6297    if let Some(condition) = &params.condition {
6298        subject.insert("condition".into(), json!(condition));
6299    }
6300    if let Some(release) = &params.release {
6301        subject.insert("release".into(), release.clone());
6302    }
6303    if let Some(prev) = &params.prev_handoff_id {
6304        subject.insert("prevHandoffId".into(), json!(prev));
6305    }
6306
6307    let mut cred = Map::new();
6308    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6309    cred.insert("id".into(), json!(params.credential_id));
6310    cred.insert(
6311        "type".into(),
6312        json!(["VerifiableCredential", CUSTODY_HANDOFF_TYPE]),
6313    );
6314    cred.insert("issuer".into(), json!(params.to_actor));
6315    cred.insert("validFrom".into(), json!(params.handoff_at));
6316    if let Some(vu) = &params.valid_until {
6317        cred.insert("validUntil".into(), json!(vu));
6318    }
6319    cred.insert("credentialSubject".into(), Value::Object(subject));
6320
6321    let opts = BuildProofOptions::new(
6322        crate::verification_method::ed25519_method(&params.to_actor),
6323        &params.handoff_at,
6324    );
6325    data_integrity::sign(&Value::Object(cred), receiver_seed, &opts)
6326}
6327
6328/// True when the handoff `subject` embeds a release signed by its `fromActor`
6329/// that names the same task and receiver.
6330fn release_ok(subject: &Value, releaser_keys: Keys<'_>, now_ns: i128) -> bool {
6331    let release = match subject.get("release") {
6332        Some(r) => r,
6333        None => return false,
6334    };
6335    let v = match rv::verify_robotics_credential(
6336        release,
6337        releaser_keys,
6338        Some(CUSTODY_RELEASE_TYPE),
6339        now_ns,
6340        VerifyOptions::window(Window::FromRequired),
6341    ) {
6342        Ok(v) => v,
6343        Err(_) => return false,
6344    };
6345    let s = |x: &Value, k: &str| x.get(k).and_then(|y| y.as_str()).map(String::from);
6346    Some(v.issuer.clone()) == s(subject, "fromActor")
6347        && s(&v.subject, "fromActor").as_deref() == Some(v.issuer.as_str())
6348        && s(&v.subject, "id") == s(subject, "id")
6349        && s(&v.subject, "toActor") == s(subject, "toActor")
6350}
6351
6352/// Options for [`verify_handoff`].
6353#[derive(Clone, Copy, Default)]
6354pub struct HandoffCheck<'a> {
6355    /// The handoff must be for this task.
6356    pub task_id: Option<&'a str>,
6357    /// Key source for the releasing actor; giving one requires the release.
6358    pub releaser_keys: Option<Keys<'a>>,
6359    /// Require the releasing actor's signed release (keys from the receiver
6360    /// source when no `releaser_keys` is given).
6361    pub require_release: bool,
6362    /// The releasing actor the caller expects. The release must be signed by
6363    /// it and name it as `fromActor`; with no releaser key a did:key releaser
6364    /// verifies under its own key only when this names it, and the receiver
6365    /// is then pinned to the toActor that verified release names.
6366    pub from_actor: Option<&'a str>,
6367}
6368
6369/// Verify a custody handoff: the receiver's proof bound to the issuer, the
6370/// issuer is the receiving actor (`toActor`), `id` / `fromActor` / `toActor`
6371/// are non-empty strings, and the window at `now_iso` (validFrom required).
6372/// With [`HandoffCheck`] options, the task is pinned and the embedded release
6373/// must be signed by the `fromActor` and name the same task and receiver.
6374pub fn verify_handoff(
6375    credential: &Value,
6376    receiver_keys: Keys<'_>,
6377    check: HandoffCheck<'_>,
6378    now_iso: &str,
6379) -> Result<Option<Value>> {
6380    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
6381    let now = rv::require_now(now_iso)?;
6382    let releaser_keys = rv::pin_if_keyless(
6383        check.releaser_keys.unwrap_or(receiver_keys),
6384        check.from_actor,
6385    );
6386    // With no receiver key, the receiver is pinned to the toActor named by the
6387    // release the pinned releaser signed.
6388    let mut receiver_pin: Option<String> = None;
6389    if check.from_actor.is_some() && rv::no_key_source(&receiver_keys) {
6390        if let Some(rel) = credential
6391            .get("credentialSubject")
6392            .and_then(|s| s.get("release"))
6393        {
6394            if let Ok(r) = rv::verify_robotics_credential(
6395                rel,
6396                releaser_keys,
6397                Some(CUSTODY_RELEASE_TYPE),
6398                now,
6399                VerifyOptions::window(Window::FromRequired),
6400            ) {
6401                if r.subject.get("fromActor").and_then(|x| x.as_str()) == Some(r.issuer.as_str()) {
6402                    receiver_pin = non_empty_str(&r.subject, "toActor").map(String::from);
6403                }
6404            }
6405        }
6406    }
6407    let v = match rv::verify_robotics_credential(
6408        credential,
6409        rv::pin_if_keyless(receiver_keys, receiver_pin.as_deref()),
6410        Some(CUSTODY_HANDOFF_TYPE),
6411        now,
6412        VerifyOptions::window(Window::FromRequired),
6413    ) {
6414        Ok(v) => v,
6415        Err(_) => return Ok(None),
6416    };
6417    for f in ["id", "fromActor", "toActor"] {
6418        if non_empty_str(&v.subject, f).is_none() {
6419            return Ok(None);
6420        }
6421    }
6422    if v.subject.get("toActor").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
6423        return Ok(None);
6424    }
6425    if check
6426        .task_id
6427        .is_some_and(|t| v.subject.get("id").and_then(|x| x.as_str()) != Some(t))
6428    {
6429        return Ok(None);
6430    }
6431    if check
6432        .from_actor
6433        .is_some_and(|f| v.subject.get("fromActor").and_then(|x| x.as_str()) != Some(f))
6434    {
6435        return Ok(None);
6436    }
6437    if (check.require_release || check.releaser_keys.is_some() || check.from_actor.is_some())
6438        && !release_ok(&v.subject, releaser_keys, now)
6439    {
6440        return Ok(None);
6441    }
6442    Ok(Some(v.subject))
6443}
6444
6445/// One actor's public key, looked up by actor DID, for [`verify_handoff_chain`].
6446#[derive(Debug, Clone)]
6447pub struct ActorKey {
6448    pub did: String,
6449    pub public_key: Vec<u8>,
6450}
6451
6452/// Verify an ordered list of handoff credentials forms a valid custody chain for
6453/// `task_id`: every handoff verifies under its receiver's key and (with
6454/// `require_release`) carries a release signed by its releasing actor (keys for
6455/// both from `public_keys`); each `toActor` matches the next link's
6456/// `fromActor`; each link after the first names the previous link's `id` as
6457/// `prevHandoffId`; links are in time order; and the first `fromActor` is
6458/// `origin_actor`. Each earlier link must still have been valid when the next
6459/// began, and the last at `now_iso`. Returns `(ok, current_holder)`.
6460///
6461/// `origin_actor` is required: with no known first holder, anyone could sign a
6462/// first link handing the task from themselves. Each link's releaser is pinned
6463/// (the origin, then each `toActor`), so did:key actors verify under their own
6464/// keys even with no entry in `public_keys`.
6465pub fn verify_handoff_chain(
6466    handoffs: &[Value],
6467    public_keys: &[ActorKey],
6468    task_id: &str,
6469    origin_actor: Option<&str>,
6470    require_release: bool,
6471    now_iso: &str,
6472) -> Result<(bool, Option<String>)> {
6473    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); handoffs);
6474    rv::require_now(now_iso)?;
6475    if task_id.is_empty() || origin_actor.is_none_or(str::is_empty) {
6476        return Ok((false, None));
6477    }
6478    let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
6479    let keys = Keys::Map(&map);
6480    let mut expected_from: Option<String> = origin_actor.map(String::from);
6481    let mut current_holder: Option<String> = origin_actor.map(String::from);
6482    let mut prev_id: Option<String> = None;
6483    let mut prev_time: Option<i128> = None;
6484    for (i, handoff) in handoffs.iter().enumerate() {
6485        let at: String = match handoffs.get(i + 1) {
6486            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
6487                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
6488                _ => return Ok((false, None)),
6489            },
6490            None => now_iso.to_string(),
6491        };
6492        let check = HandoffCheck {
6493            task_id: Some(task_id),
6494            releaser_keys: if require_release { Some(keys) } else { None },
6495            require_release,
6496            from_actor: if require_release {
6497                expected_from.as_deref()
6498            } else {
6499                None
6500            },
6501        };
6502        let subject = match verify_handoff(handoff, keys, check, &at)? {
6503            Some(s) => s,
6504            None => return Ok((false, None)),
6505        };
6506        if let Some(expected) = &expected_from {
6507            if subject.get("fromActor").and_then(|v| v.as_str()) != Some(expected.as_str()) {
6508                return Ok((false, None));
6509            }
6510        }
6511        match rv::time_ns(handoff.get("validFrom")) {
6512            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
6513            _ => return Ok((false, None)),
6514        }
6515        if i > 0 {
6516            match &prev_id {
6517                Some(p) if subject.get("prevHandoffId").and_then(|v| v.as_str()) == Some(p) => {}
6518                _ => return Ok((false, None)),
6519            }
6520        }
6521        prev_id = non_empty_str(handoff, "id").map(String::from);
6522        current_holder = subject
6523            .get("toActor")
6524            .and_then(|v| v.as_str())
6525            .map(String::from);
6526        expected_from = current_holder.clone();
6527    }
6528    Ok((true, current_holder))
6529}
6530
6531/// Return the actor holding the task at protocol time `at`: the receiver
6532/// (`toActor`) of the most recent handoff whose `validFrom` is at or before
6533/// `at`. Returns `None` if no handoff had occurred yet or `at` is not a strict
6534/// protocol time. `handoffs` is assumed in chain order.
6535pub fn holder_at(handoffs: &[Value], at: &str) -> Option<String> {
6536    crate::nesting::deep_guard!(None; handoffs);
6537    let when = crate::time::parse_protocol_time_ns(at).ok()?;
6538    let mut holder: Option<String> = None;
6539    for handoff in handoffs {
6540        if let Some(start) = rv::time_ns(handoff.get("validFrom")) {
6541            if start <= when {
6542                holder = handoff
6543                    .get("credentialSubject")
6544                    .and_then(|s| s.get("toActor"))
6545                    .and_then(|v| v.as_str())
6546                    .map(String::from);
6547            }
6548        }
6549    }
6550    holder
6551}
6552
6553/// A condition change localized to the hop responsible for it, surfaced by
6554/// [`locate_condition_change`].
6555#[derive(Debug, Clone, PartialEq, Eq)]
6556pub struct ConditionChange {
6557    pub responsible_holder: Option<String>,
6558    pub from_condition: String,
6559    pub to_condition: String,
6560}
6561
6562/// Find the first hop where the attested condition differs from the previous
6563/// handoff. The holder responsible for the change is the actor who held the task
6564/// during it (the previous handoff's receiver). Returns the change, or `None` if
6565/// the condition never changed. Handoffs without a condition are skipped for the
6566/// comparison.
6567pub fn locate_condition_change(handoffs: &[Value]) -> Option<ConditionChange> {
6568    crate::nesting::deep_guard!(None; handoffs);
6569    let mut prev_condition: Option<String> = None;
6570    let mut prev_holder: Option<String> = None;
6571    for handoff in handoffs {
6572        let subject = handoff.get("credentialSubject");
6573        let condition = subject
6574            .and_then(|s| s.get("condition"))
6575            .and_then(|v| v.as_str());
6576        let condition = match condition {
6577            Some(c) => c,
6578            None => continue,
6579        };
6580        if let Some(prev) = &prev_condition {
6581            if condition != prev {
6582                return Some(ConditionChange {
6583                    responsible_holder: prev_holder,
6584                    from_condition: prev.clone(),
6585                    to_condition: condition.to_string(),
6586                });
6587            }
6588        }
6589        prev_condition = Some(condition.to_string());
6590        prev_holder = subject
6591            .and_then(|s| s.get("toActor"))
6592            .and_then(|v| v.as_str())
6593            .map(String::from);
6594    }
6595    None
6596}
6597
6598// ---------------------------------------------------------------------------
6599// Robot-to-infrastructure bounded access (Phase 5.17)
6600// ---------------------------------------------------------------------------
6601//
6602// A robot in a warehouse, hospital, or building needs to open doors, call
6603// elevators, dock at chargers, and operate machines. This gives it a bounded,
6604// revocable, auditable way to do so. The infrastructure operator issues an access
6605// grant naming a resource, the permitted operations, an optional zone, and a time
6606// window, signed by the operator. The robot presents a signed access request for a
6607// specific operation on a specific resource, and the resource authorizes it
6608// offline: the grant must be valid and operator-signed, the request valid and
6609// robot-signed, the operation permitted, and the moment inside the window. The
6610// grant plus the request is a tamper-evident, attributable record of the access.
6611//
6612// This is the open layer: signed grants and requests, an offline authorize
6613// decision, shrink-only attenuation, and the audit record. Hardware-enforced
6614// actuation in the resource and managed fleet access-policy orchestration are out
6615// of scope for the open layer.
6616
6617pub const ACCESS_GRANT_TYPE: &str = "InfrastructureAccessGrant";
6618pub const ACCESS_REQUEST_TYPE: &str = "InfrastructureAccessRequest";
6619
6620/// Parameters for [`build_access_grant`]. The signer is the operator; the grant
6621/// names the robot, the resource, the permitted operations, an optional zone, and
6622/// a validity window. `valid_until`, when set, bounds the window (the wrapper
6623/// derives it from a `valid_seconds` lifetime added to `granted_at`, keeping the
6624/// core's clock caller-supplied).
6625#[derive(Debug, Clone)]
6626pub struct BuildAccessGrant {
6627    pub operator_did: String,
6628    pub robot_did: String,
6629    pub resource: String,
6630    pub operations: Vec<String>,
6631    pub zone: Option<String>,
6632    pub granted_at: String,
6633    pub valid_until: Option<String>,
6634}
6635
6636/// Build a signed access grant: the operator grants `robot_did` permission to
6637/// perform `operations` on `resource` (optionally within `zone`) for the window.
6638/// Signed by the operator.
6639pub fn build_access_grant(operator_seed: &[u8], params: &BuildAccessGrant) -> Result<Value> {
6640    if params.robot_did.is_empty() || params.resource.is_empty() {
6641        return Err(CoreError::Json(
6642            "robot_did and resource are required".into(),
6643        ));
6644    }
6645    if params.operations.is_empty() {
6646        return Err(CoreError::Json(
6647            "operations must be a non-empty list".into(),
6648        ));
6649    }
6650
6651    let mut subject = Map::new();
6652    subject.insert("id".into(), json!(params.robot_did));
6653    subject.insert("resource".into(), json!(params.resource));
6654    subject.insert("operations".into(), json!(params.operations));
6655    if let Some(zone) = &params.zone {
6656        subject.insert("zone".into(), json!(zone));
6657    }
6658
6659    let mut cred = Map::new();
6660    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6661    cred.insert(
6662        "type".into(),
6663        json!(["VerifiableCredential", ACCESS_GRANT_TYPE]),
6664    );
6665    cred.insert("issuer".into(), json!(params.operator_did));
6666    cred.insert("validFrom".into(), json!(params.granted_at));
6667    if let Some(vu) = &params.valid_until {
6668        cred.insert("validUntil".into(), json!(vu));
6669    }
6670    cred.insert("credentialSubject".into(), Value::Object(subject));
6671
6672    let opts = BuildProofOptions::new(
6673        crate::verification_method::ed25519_method(&params.operator_did),
6674        &params.granted_at,
6675    );
6676    data_integrity::sign(&Value::Object(cred), operator_seed, &opts)
6677}
6678
6679/// Verify an access grant: the operator's proof bound to the issuer
6680/// (`operator_keys` is a `{did: key}` source, or the bare key of a did:key
6681/// operator), validFrom and validUntil present strict protocol times with
6682/// `now_iso` inside, a non-empty string `resource`, a non-empty list of string
6683/// `operations`, and (when given) the operator in `trusted_operators`. Returns
6684/// the credentialSubject on success, `None` if invalid.
6685pub fn verify_access_grant(
6686    credential: &Value,
6687    operator_keys: Keys<'_>,
6688    trusted_operators: Option<&HashSet<String>>,
6689    now_iso: &str,
6690) -> Result<Option<Value>> {
6691    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
6692    let now = rv::require_now(now_iso)?;
6693    let opts = VerifyOptions {
6694        trusted_issuers: trusted_operators,
6695        ..VerifyOptions::window(Window::Required)
6696    };
6697    let v = match rv::verify_robotics_credential(
6698        credential,
6699        operator_keys,
6700        Some(ACCESS_GRANT_TYPE),
6701        now,
6702        opts,
6703    ) {
6704        Ok(v) => v,
6705        Err(_) => return Ok(None),
6706    };
6707    if non_empty_str(&v.subject, "resource").is_none() {
6708        return Ok(None);
6709    }
6710    match v.subject.get("operations") {
6711        Some(Value::Array(ops)) if !ops.is_empty() && ops.iter().all(|o| o.is_string()) => {}
6712        _ => return Ok(None),
6713    }
6714    Ok(Some(v.subject))
6715}
6716
6717/// Parameters for [`build_access_request`]. The signer is the robot; the request
6718/// names the resource and the single operation the robot wants to perform.
6719#[derive(Debug, Clone)]
6720pub struct BuildAccessRequest {
6721    pub robot_did: String,
6722    pub resource: String,
6723    pub operation: String,
6724    pub requested_at: String,
6725    /// A one-time value the resource remembers to refuse a replay.
6726    pub nonce: String,
6727}
6728
6729/// Build a signed access request: the robot requests to perform `operation` on
6730/// `resource`. Signed by the robot.
6731pub fn build_access_request(robot_seed: &[u8], params: &BuildAccessRequest) -> Result<Value> {
6732    if params.robot_did.is_empty() || params.resource.is_empty() || params.operation.is_empty() {
6733        return Err(CoreError::Json(
6734            "robot_did, resource, and operation are required".into(),
6735        ));
6736    }
6737    if params.nonce.is_empty() {
6738        return Err(CoreError::Json("nonce is required".into()));
6739    }
6740
6741    let mut subject = Map::new();
6742    subject.insert("id".into(), json!(params.robot_did));
6743    subject.insert("resource".into(), json!(params.resource));
6744    subject.insert("operation".into(), json!(params.operation));
6745    subject.insert("nonce".into(), json!(params.nonce));
6746
6747    let mut cred = Map::new();
6748    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6749    cred.insert(
6750        "type".into(),
6751        json!(["VerifiableCredential", ACCESS_REQUEST_TYPE]),
6752    );
6753    cred.insert("issuer".into(), json!(params.robot_did));
6754    cred.insert("validFrom".into(), json!(params.requested_at));
6755    cred.insert("credentialSubject".into(), Value::Object(subject));
6756
6757    let opts = BuildProofOptions::new(
6758        crate::verification_method::ed25519_method(&params.robot_did),
6759        &params.requested_at,
6760    );
6761    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
6762}
6763
6764/// The outcome of an offline access authorization: `ok` plus any reasons it
6765/// failed. Surfaced by [`authorize_access`].
6766#[derive(Debug, Clone)]
6767pub struct AuthorizeResult {
6768    pub ok: bool,
6769    pub reasons: Vec<String>,
6770}
6771
6772/// Decide, offline, whether to allow the requested access. The grant must verify
6773/// under the operator's key and be in window, the request must verify bound to
6774/// the robot as issuer (and name it as subject) with validFrom no later than
6775/// `now_iso` (keys are `{did: key}` sources, or bare keys of did:key parties), the grant and request must
6776/// name the same robot and resource, and the requested operation must be permitted
6777/// by the grant. Returns an [`AuthorizeResult`] with the reasons for any refusal.
6778/// How old an access request may be by default (seconds).
6779pub const DEFAULT_MAX_REQUEST_AGE_SECONDS: i64 = 60;
6780
6781/// Replay limits for [`authorize_access`]: the request may be no older than
6782/// `max_age_seconds` and not from the future (both with `clock_skew_seconds`),
6783/// and its nonce must not be in `seen_nonces` (it is added when access is
6784/// allowed).
6785pub struct RequestReplay<'a> {
6786    pub seen_nonces: &'a mut HashSet<String>,
6787    pub max_age_seconds: i64,
6788    pub clock_skew_seconds: i64,
6789    /// With no operator key, the grant verifies only when its did:key
6790    /// operator is in this non-empty set.
6791    pub trusted_operators: Option<&'a HashSet<String>>,
6792}
6793
6794impl<'a> RequestReplay<'a> {
6795    /// The default limits (60 s age, 30 s skew) over `seen_nonces`.
6796    pub fn new(seen_nonces: &'a mut HashSet<String>) -> Self {
6797        Self {
6798            seen_nonces,
6799            max_age_seconds: DEFAULT_MAX_REQUEST_AGE_SECONDS,
6800            clock_skew_seconds: 30,
6801            trusted_operators: None,
6802        }
6803    }
6804}
6805
6806pub fn authorize_access(
6807    grant: &Value,
6808    request: &Value,
6809    operator_keys: Keys<'_>,
6810    robot_keys: Keys<'_>,
6811    replay: RequestReplay<'_>,
6812    now_iso: &str,
6813) -> Result<AuthorizeResult> {
6814    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); grant, request);
6815    let current = rv::require_now(now_iso)?;
6816    let mut reasons: Vec<String> = Vec::new();
6817
6818    let grant_subject =
6819        match verify_access_grant(grant, operator_keys, replay.trusted_operators, now_iso)? {
6820            Some(s) => s,
6821            None => {
6822                reasons.push("grant invalid or out of window".into());
6823                return Ok(AuthorizeResult { ok: false, reasons });
6824            }
6825        };
6826
6827    // With no robot key, only the robot the verified grant names may sign.
6828    let granted_robot = grant_subject
6829        .get("id")
6830        .and_then(|v| v.as_str())
6831        .map(String::from);
6832    let req_subject = match bound(
6833        request,
6834        rv::pin_if_keyless(robot_keys, granted_robot.as_deref()),
6835        ACCESS_REQUEST_TYPE,
6836        now_iso,
6837        Window::FromRequired,
6838    )? {
6839        Some(v) if issuer_is_subject(&v) => v.subject,
6840        _ => {
6841            reasons.push("request invalid".into());
6842            return Ok(AuthorizeResult { ok: false, reasons });
6843        }
6844    };
6845    let second: i128 = 1_000_000_000;
6846    let skew = i128::from(replay.clock_skew_seconds) * second;
6847    match rv::time_ns(request.get("validFrom")) {
6848        Some(issued) if issued > current + skew => {
6849            reasons.push("request is dated in the future".into())
6850        }
6851        Some(issued) if current - issued > i128::from(replay.max_age_seconds) * second + skew => {
6852            reasons.push("request is too old".into())
6853        }
6854        Some(_) => {}
6855        None => reasons.push("request is dated in the future".into()),
6856    }
6857    let nonce = non_empty_str(&req_subject, "nonce").map(String::from);
6858    match &nonce {
6859        None => reasons.push("request carries no nonce".into()),
6860        Some(n) if replay.seen_nonces.contains(n) => {
6861            reasons.push("request was already used (replay)".into())
6862        }
6863        Some(_) => {}
6864    }
6865    if !reasons.is_empty() {
6866        return Ok(AuthorizeResult { ok: false, reasons });
6867    }
6868    let req_id = req_subject.get("id").and_then(|v| v.as_str());
6869
6870    if grant_subject.get("id").and_then(|v| v.as_str()) != req_id {
6871        reasons.push("grant and request name different robots".into());
6872    }
6873    if grant_subject.get("resource").and_then(|v| v.as_str())
6874        != req_subject.get("resource").and_then(|v| v.as_str())
6875    {
6876        reasons.push("grant and request name different resources".into());
6877    }
6878    let operation = req_subject.get("operation").and_then(|v| v.as_str());
6879    let permitted = grant_subject
6880        .get("operations")
6881        .and_then(|v| v.as_array())
6882        .map(|ops| operation.is_some() && ops.iter().any(|o| o.as_str() == operation))
6883        .unwrap_or(false);
6884    if !permitted {
6885        reasons.push("operation not permitted by the grant".into());
6886    }
6887    if reasons.is_empty() {
6888        if let Some(n) = nonce {
6889            replay.seen_nonces.insert(n);
6890        }
6891    }
6892
6893    Ok(AuthorizeResult {
6894        ok: reasons.is_empty(),
6895        reasons,
6896    })
6897}
6898
6899/// Return true if `child` is a valid attenuation of `parent`: the same resource, a
6900/// subset of the operations, and the same zone (or the parent had no zone). A
6901/// sub-grant may only narrow, never widen, the access it inherits.
6902pub fn attenuates_grant(parent: &Value, child: &Value) -> bool {
6903    crate::nesting::deep_guard!(false; parent, child);
6904    let p = parent.get("credentialSubject");
6905    let c = child.get("credentialSubject");
6906    let p_resource = p.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
6907    let c_resource = c.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
6908    if p_resource != c_resource {
6909        return false;
6910    }
6911    let p_ops: HashSet<&str> = p
6912        .and_then(|s| s.get("operations"))
6913        .and_then(|v| v.as_array())
6914        .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
6915        .unwrap_or_default();
6916    let c_ops: HashSet<&str> = c
6917        .and_then(|s| s.get("operations"))
6918        .and_then(|v| v.as_array())
6919        .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
6920        .unwrap_or_default();
6921    if !c_ops.is_subset(&p_ops) {
6922        return false;
6923    }
6924    let p_zone = p.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
6925    let c_zone = c.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
6926    if p_zone.is_some() && c_zone != p_zone {
6927        return false;
6928    }
6929    true
6930}
6931
6932// ---------------------------------------------------------------------------
6933// Fused-sensor provenance (Phase 5.18)
6934// ---------------------------------------------------------------------------
6935//
6936// Perception provenance signs individual sensor frames. A robot rarely acts on
6937// one frame, though: it fuses many frames, from cameras, lidar, radar, and other
6938// sensors, into a single world model, an object set, an occupancy grid, or a
6939// pose estimate, and acts on that. This binds a fused output to the exact set of
6940// input frames that produced it and the fusion method that produced it, signed by
6941// the robot, so a manipulated fusion result or a silently dropped or substituted
6942// input is detectable at the provenance layer.
6943//
6944// A fused-perception attestation carries the hash of the fused output, an ordered
6945// list of the input frame hashes, a digest over those inputs, and a fusion method
6946// identifier, signed by the robot. A verifier reproduces the input digest from the
6947// listed inputs and, when it holds the raw fused output, reproduces its hash, so
6948// the attestation commits to exactly those inputs and that output. Checking each
6949// listed input against the robot's signed perception log confirms every fused
6950// input traces to a frame the robot actually recorded.
6951//
6952// This is the open layer: the robot signs the binding of a fused output to its
6953// inputs in software, reusing the perception frame hashes. Hardware sensor
6954// attestation and managed sensor-fusion orchestration are out of scope for the
6955// open layer.
6956
6957pub const FUSED_PERCEPTION_TYPE: &str = "FusedPerceptionAttestation";
6958
6959/// Multibase (base64url) SHA-256 of a raw fused output. Only the hash travels in
6960/// the attestation; the fused output stays wherever the deployment keeps it.
6961pub fn hash_fused_output(output: &[u8]) -> String {
6962    mb64(&Sha256::digest(output))
6963}
6964
6965/// Input-digest version 1: SHA-256 of the hashes joined by "\n" (the
6966/// original; assumed when an attestation names no version).
6967pub const INPUTS_DIGEST_V1: &str = "1";
6968/// Input-digest version 2: SHA-256 of the JCS JSON array of the hashes (the
6969/// default for new attestations).
6970pub const INPUTS_DIGEST_V2: &str = "2";
6971
6972/// Deterministic multibase digest over an ordered list of input frame hashes
6973/// (version 2, the default). It commits to the exact inputs and their order.
6974pub fn fusion_inputs_digest(input_frame_hashes: &[String]) -> Result<String> {
6975    fusion_inputs_digest_version(input_frame_hashes, INPUTS_DIGEST_V2)
6976}
6977
6978/// [`fusion_inputs_digest`] under a named version. Version 1 refuses a hash
6979/// that contains "\n" (otherwise two different lists could share a digest).
6980pub fn fusion_inputs_digest_version(
6981    input_frame_hashes: &[String],
6982    version: &str,
6983) -> Result<String> {
6984    if input_frame_hashes.is_empty() {
6985        return Err(CoreError::Json(
6986            "input_frame_hashes must be a non-empty list".into(),
6987        ));
6988    }
6989    for h in input_frame_hashes {
6990        if h.is_empty() {
6991            return Err(CoreError::Json(
6992                "each input frame hash must be a non-empty string".into(),
6993            ));
6994        }
6995    }
6996    match version {
6997        INPUTS_DIGEST_V2 => Ok(mb64(&Sha256::digest(jcs::canonicalize(&json!(
6998            input_frame_hashes
6999        ))))),
7000        INPUTS_DIGEST_V1 => {
7001            if input_frame_hashes.iter().any(|h| h.contains('\n')) {
7002                return Err(CoreError::Json(
7003                    "a version 1 input digest cannot carry a hash containing a newline".into(),
7004                ));
7005            }
7006            Ok(mb64(&Sha256::digest(
7007                input_frame_hashes.join("\n").as_bytes(),
7008            )))
7009        }
7010        other => Err(CoreError::Json(format!(
7011            "unknown inputs digest version {other:?}"
7012        ))),
7013    }
7014}
7015
7016/// Parameters for [`build_fused_attestation`]. The robot self-issues the
7017/// credential with its own Ed25519 seed. Provide either the raw `fused_output` (it
7018/// is hashed) or a precomputed `fused_output_hash`, not both. `captured_at`, when
7019/// `None`, defaults to `valid_from`.
7020#[derive(Debug, Clone)]
7021pub struct BuildFusedAttestation {
7022    pub robot_did: String,
7023    pub fusion_method: String,
7024    pub input_frame_hashes: Vec<String>,
7025    pub fused_output: Option<Vec<u8>>,
7026    pub fused_output_hash: Option<String>,
7027    pub captured_at: Option<String>,
7028    pub valid_from: String,
7029    pub valid_until: Option<String>,
7030}
7031
7032/// Build a signed `FusedPerceptionAttestation`: the robot attests that a fused
7033/// output was produced by `fusion_method` from the frames named in
7034/// `input_frame_hashes`. The attestation carries a digest over the ordered inputs,
7035/// so the set of inputs is tamper-evident. Signed by the robot.
7036pub fn build_fused_attestation(robot_seed: &[u8], params: &BuildFusedAttestation) -> Result<Value> {
7037    if params.robot_did.is_empty() {
7038        return Err(CoreError::Json("robot_did is required".into()));
7039    }
7040    if params.fusion_method.is_empty() {
7041        return Err(CoreError::Json("fusion_method is required".into()));
7042    }
7043    if params.input_frame_hashes.is_empty() {
7044        return Err(CoreError::Json(
7045            "input_frame_hashes must be a non-empty list".into(),
7046        ));
7047    }
7048    if params.fused_output.is_some() && params.fused_output_hash.is_some() {
7049        return Err(CoreError::Json(
7050            "provide either fused_output or fused_output_hash, not both".into(),
7051        ));
7052    }
7053    let fused_output_hash = match (&params.fused_output, &params.fused_output_hash) {
7054        (Some(o), None) => hash_fused_output(o),
7055        (None, Some(h)) if !h.is_empty() => h.clone(),
7056        _ => {
7057            return Err(CoreError::Json(
7058                "fused_output or fused_output_hash is required".into(),
7059            ))
7060        }
7061    };
7062
7063    let captured = params
7064        .captured_at
7065        .clone()
7066        .unwrap_or_else(|| params.valid_from.clone());
7067
7068    let mut subject = Map::new();
7069    subject.insert("id".into(), json!(params.robot_did));
7070    subject.insert("fusionMethod".into(), json!(params.fusion_method));
7071    subject.insert("fusedOutputHash".into(), json!(fused_output_hash));
7072    subject.insert("inputFrameHashes".into(), json!(params.input_frame_hashes));
7073    subject.insert(
7074        "inputsDigest".into(),
7075        json!(fusion_inputs_digest(&params.input_frame_hashes)?),
7076    );
7077    subject.insert("inputsDigestVersion".into(), json!(INPUTS_DIGEST_V2));
7078    subject.insert("capturedAt".into(), json!(captured));
7079
7080    let mut cred = Map::new();
7081    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
7082    cred.insert(
7083        "type".into(),
7084        json!(["VerifiableCredential", FUSED_PERCEPTION_TYPE]),
7085    );
7086    cred.insert("issuer".into(), json!(params.robot_did));
7087    cred.insert("validFrom".into(), json!(params.valid_from));
7088    if let Some(vu) = &params.valid_until {
7089        cred.insert("validUntil".into(), json!(vu));
7090    }
7091    cred.insert("credentialSubject".into(), Value::Object(subject));
7092
7093    let opts = BuildProofOptions::new(
7094        crate::verification_method::ed25519_method(&params.robot_did),
7095        &params.valid_from,
7096    );
7097    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
7098}
7099
7100/// Verify a `FusedPerceptionAttestation`: the robot's proof bound to the robot
7101/// as issuer (which must also be `credentialSubject.id`), the window at
7102/// `now_iso` (validFrom required), that the digest over
7103/// the listed inputs reproduces the attested `inputsDigest` (so the inputs are
7104/// internally consistent and tamper-evident), and, when the raw `fused_output` is
7105/// supplied, that its hash reproduces the attested `fusedOutputHash`. Returns the
7106/// credentialSubject on success, `None` if invalid.
7107pub fn verify_fused_attestation(
7108    credential: &Value,
7109    keys: Keys<'_>,
7110    fused_output: Option<&[u8]>,
7111    now_iso: &str,
7112) -> Result<Option<Value>> {
7113    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
7114    let v = match bound(
7115        credential,
7116        keys,
7117        FUSED_PERCEPTION_TYPE,
7118        now_iso,
7119        Window::FromRequired,
7120    )? {
7121        Some(v) if issuer_is_subject(&v) => v,
7122        _ => return Ok(None),
7123    };
7124    let subject = v.subject;
7125    let fused_output_hash = non_empty_str(&subject, "fusedOutputHash");
7126    let inputs: Vec<String> = match subject.get("inputFrameHashes") {
7127        Some(Value::Array(a)) if !a.is_empty() && a.iter().all(|e| e.is_string()) => a
7128            .iter()
7129            .filter_map(|e| e.as_str().map(String::from))
7130            .collect(),
7131        _ => return Ok(None),
7132    };
7133    if fused_output_hash.is_none() {
7134        return Ok(None);
7135    }
7136    let version = match subject.get("inputsDigestVersion") {
7137        None => INPUTS_DIGEST_V1,
7138        Some(Value::String(v)) if v == INPUTS_DIGEST_V1 || v == INPUTS_DIGEST_V2 => v.as_str(),
7139        _ => return Ok(None),
7140    };
7141    match fusion_inputs_digest_version(&inputs, version) {
7142        Ok(d) => {
7143            if Some(d.as_str()) != subject.get("inputsDigest").and_then(|v| v.as_str()) {
7144                return Ok(None);
7145            }
7146        }
7147        Err(_) => return Ok(None),
7148    }
7149    if let Some(o) = fused_output {
7150        if Some(hash_fused_output(o).as_str()) != fused_output_hash {
7151            return Ok(None);
7152        }
7153    }
7154    Ok(Some(subject))
7155}
7156
7157/// The outcome of confirming an attestation's inputs against a perception log:
7158/// `ok` plus the input frame hashes not found. Surfaced by [`verify_fusion_inputs`].
7159#[derive(Debug, Clone)]
7160pub struct FusionInputsResult {
7161    pub ok: bool,
7162    pub missing: Vec<String>,
7163}
7164
7165/// Confirm every input frame the attestation names was actually recorded in the
7166/// robot's perception log. Returns `ok` plus `missing`, the input frame hashes that
7167/// do not appear as a recorded frame, so a dropped or substituted fused input is
7168/// named rather than hidden.
7169pub fn verify_fusion_inputs(credential: &Value, log_entries: &[Value]) -> FusionInputsResult {
7170    crate::nesting::deep_guard!(FusionInputsResult { ok: false, missing: Vec::new() }; credential, log_entries);
7171    let recorded: HashSet<&str> = log_entries
7172        .iter()
7173        .filter_map(|e| e.get("frameHash").and_then(|v| v.as_str()))
7174        .filter(|h| !h.is_empty())
7175        .collect();
7176    // A missing or empty input list is malformed: fail closed.
7177    let inputs = match credential
7178        .get("credentialSubject")
7179        .and_then(|s| s.get("inputFrameHashes"))
7180        .and_then(|v| v.as_array())
7181    {
7182        Some(a) if !a.is_empty() => a,
7183        _ => {
7184            return FusionInputsResult {
7185                ok: false,
7186                missing: Vec::new(),
7187            }
7188        }
7189    };
7190    let missing: Vec<String> = inputs
7191        .iter()
7192        .filter(|h| !h.as_str().is_some_and(|s| recorded.contains(s)))
7193        .map(|h| match h.as_str() {
7194            Some(s) => s.to_string(),
7195            None => h.to_string(),
7196        })
7197        .collect();
7198    FusionInputsResult {
7199        ok: missing.is_empty(),
7200        missing,
7201    }
7202}
7203
7204// ---------------------------------------------------------------------------
7205// Wear and degradation attestation (Phase 5.19)
7206// ---------------------------------------------------------------------------
7207//
7208// A robot does not stay as capable as it left the factory. Actuators wear, joints
7209// develop backlash, sensors drift out of calibration, and error rates creep up.
7210// This lets a robot sign its own degradation state, bound to its identity and
7211// hash-linked over time so the history is tamper-evident, and derives a narrowed
7212// physical capability scope from that state, so a worn robot operates inside a
7213// tighter, verifiable envelope instead of trusting the static limit it shipped
7214// with.
7215//
7216// A wear attestation carries a normalized wear level (0 for as-new, 1 for fully
7217// worn) and optional detailed metrics, signed by the robot. Linking each
7218// attestation to the previous one by its proof value forms a chain a verifier
7219// walks to see how the robot degraded over its life. `attenuate_for_wear` derives
7220// a physical scope whose numeric caps are scaled down by the wear level, and the
7221// result is a valid attenuation of the original scope, so the same attenuation
7222// rule the rest of Vouch uses carries the derating.
7223//
7224// This is the open layer: the robot signs its wear state and derives the narrowed
7225// scope credential in software. Firmware-level enforcement of the narrowed
7226// envelope and managed predictive-maintenance modeling are out of scope for the
7227// open layer.
7228
7229pub const WEAR_ATTESTATION_TYPE: &str = "RobotWearAttestation";
7230
7231/// Numeric caps that scale down with wear. Zones and shift windows are preserved
7232/// unchanged, so the derived scope stays a valid attenuation of the original.
7233const WEAR_DERATED_CAPS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
7234
7235/// Parameters for [`build_wear_attestation`]. The robot self-issues the credential
7236/// with its own Ed25519 seed. `metrics`, when present, is carried through into the
7237/// subject unchanged. `prev_proof`, when present, links this attestation to the
7238/// previous one, forming a wear history. `attested_at`, when `None`, defaults to
7239/// `valid_from`.
7240#[derive(Debug, Clone)]
7241pub struct BuildWearAttestation {
7242    pub robot_did: String,
7243    pub wear_level: f64,
7244    pub metrics: Option<Value>,
7245    pub prev_proof: Option<String>,
7246    pub attested_at: Option<String>,
7247    pub valid_from: String,
7248    pub valid_until: Option<String>,
7249    /// A verifier's challenge, echoed so a reading made for it can't be replayed.
7250    pub challenge: Option<String>,
7251}
7252
7253/// Build a signed `RobotWearAttestation`: the robot attests its own degradation as
7254/// a normalized `wear_level` in `[0, 1]`, optionally with detailed `metrics`. When
7255/// `prev_proof` is the proof value of the previous attestation, the new one links
7256/// to it, forming a tamper-evident wear history. Signed by the robot.
7257pub fn build_wear_attestation(robot_seed: &[u8], params: &BuildWearAttestation) -> Result<Value> {
7258    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
7259    if params.robot_did.is_empty() {
7260        return Err(CoreError::Json("robot_did is required".into()));
7261    }
7262    if params.wear_level < 0.0 || params.wear_level > 1.0 {
7263        return Err(CoreError::Json(
7264            "wear_level must be between 0.0 and 1.0".into(),
7265        ));
7266    }
7267
7268    let attested = params
7269        .attested_at
7270        .clone()
7271        .unwrap_or_else(|| params.valid_from.clone());
7272
7273    let mut subject = Map::new();
7274    subject.insert("id".into(), json!(params.robot_did));
7275    subject.insert("wearLevel".into(), json!(params.wear_level));
7276    subject.insert("attestedAt".into(), json!(attested));
7277    if let Some(m) = &params.metrics {
7278        subject.insert("metrics".into(), m.clone());
7279    }
7280    if let Some(prev) = &params.prev_proof {
7281        subject.insert("prevProof".into(), json!(prev));
7282    }
7283    if let Some(c) = &params.challenge {
7284        if c.is_empty() {
7285            return Err(CoreError::Json("challenge must not be empty".into()));
7286        }
7287        subject.insert("challenge".into(), json!(c));
7288    }
7289
7290    let mut cred = Map::new();
7291    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
7292    cred.insert(
7293        "type".into(),
7294        json!(["VerifiableCredential", WEAR_ATTESTATION_TYPE]),
7295    );
7296    cred.insert("issuer".into(), json!(params.robot_did));
7297    cred.insert("validFrom".into(), json!(params.valid_from));
7298    if let Some(vu) = &params.valid_until {
7299        cred.insert("validUntil".into(), json!(vu));
7300    }
7301    cred.insert("credentialSubject".into(), Value::Object(subject));
7302
7303    let opts = BuildProofOptions::new(
7304        crate::verification_method::ed25519_method(&params.robot_did),
7305        &params.valid_from,
7306    );
7307    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
7308}
7309
7310/// Verify a `RobotWearAttestation`: the robot's proof bound to the robot as
7311/// issuer (which must also be `credentialSubject.id`), the window at `now_iso`
7312/// (validFrom required), and that the wear level is a finite number in [0, 1]. Returns the credentialSubject on
7313/// success, `None` if invalid.
7314pub fn verify_wear_attestation(
7315    credential: &Value,
7316    keys: Keys<'_>,
7317    now_iso: &str,
7318) -> Result<Option<Value>> {
7319    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
7320    let v = match bound(
7321        credential,
7322        keys,
7323        WEAR_ATTESTATION_TYPE,
7324        now_iso,
7325        Window::FromRequired,
7326    )? {
7327        Some(v) if issuer_is_subject(&v) => v,
7328        _ => return Ok(None),
7329    };
7330    match rv::finite_number(v.subject.get("wearLevel")) {
7331        Some(level) if (0.0..=1.0).contains(&level) => Ok(Some(v.subject)),
7332        _ => Ok(None),
7333    }
7334}
7335
7336/// How fresh the newest wear reading must be, by default: one day.
7337pub const WEAR_MAX_AGE_SECONDS: i64 = 86_400;
7338
7339/// Clock skew allowed for a reading dated slightly after `now`.
7340const FRESHNESS_SKEW_NS: i128 = 300 * 1_000_000_000;
7341
7342/// What a verifier asks of a wear history beyond the links themselves.
7343#[derive(Debug, Clone, Default)]
7344pub struct WearChainCheck<'a> {
7345    /// The newest reading's `attestedAt` must be no older than this at `now`.
7346    /// `None` means [`WEAR_MAX_AGE_SECONDS`].
7347    pub max_age_seconds: Option<i64>,
7348    /// The proof value the history continues from, when the verifier already
7349    /// holds the earlier part. Without it the first reading must start the
7350    /// history (no `prevProof`).
7351    pub from_proof: Option<&'a str>,
7352    /// When given, the newest reading must carry exactly this challenge.
7353    pub challenge: Option<&'a str>,
7354}
7355
7356/// True when `subject.attestedAt` lies within `max_age_seconds` before `now`
7357/// (and no more than the clock skew after it).
7358pub(crate) fn fresh_at(subject: &Value, now_iso: &str, max_age_seconds: i64) -> bool {
7359    if max_age_seconds <= 0 {
7360        return false;
7361    }
7362    let (Some(at), Some(now)) = (
7363        rv::time_ns(subject.get("attestedAt")),
7364        rv::time_ns(Some(&Value::String(now_iso.to_string()))),
7365    ) else {
7366        return false;
7367    };
7368    let max = i128::from(max_age_seconds) * 1_000_000_000;
7369    at <= now + FRESHNESS_SKEW_NS && now - at <= max
7370}
7371
7372/// Verify an ordered wear history: each attestation verifies under the same
7373/// robot, each one after the first links to the previous by its proof value,
7374/// and they are in time order. Each earlier attestation must still have been
7375/// valid when the next was made, and the last at `now_iso`.
7376///
7377/// The history must be whole at both ends. The first reading starts it (no
7378/// `prevProof`), or links to `check.from_proof`. The newest reading was made
7379/// within `check.max_age_seconds` of `now_iso` and, when `check.challenge` is
7380/// given, carries that challenge, so a history that stops at an older, lower
7381/// reading is refused. Returns the latest credentialSubject on success, `None`
7382/// if the chain is empty or invalid.
7383pub fn verify_wear_chain(
7384    attestations: &[Value],
7385    keys: Keys<'_>,
7386    now_iso: &str,
7387    check: &WearChainCheck<'_>,
7388) -> Result<Option<Value>> {
7389    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attestations);
7390    rv::require_now(now_iso)?;
7391    if attestations.is_empty() {
7392        return Ok(None);
7393    }
7394    let mut prev_proof: Option<String> = check.from_proof.map(String::from);
7395    if let Some(first) = attestations.first() {
7396        let first_prev = first
7397            .get("credentialSubject")
7398            .and_then(|s| s.get("prevProof"))
7399            .filter(|v| !v.is_null());
7400        match (check.from_proof, first_prev) {
7401            (None, None) => {}
7402            (Some(_), Some(_)) => {}
7403            _ => return Ok(None),
7404        }
7405    }
7406    let mut prev_time: Option<i128> = None;
7407    let mut robot: Option<String> = None;
7408    let mut latest: Option<Value> = None;
7409    for (i, att) in attestations.iter().enumerate() {
7410        let at: String = match attestations.get(i + 1) {
7411            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
7412                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
7413                _ => return Ok(None),
7414            },
7415            None => now_iso.to_string(),
7416        };
7417        let subject = match verify_wear_attestation(att, keys, &at)? {
7418            Some(s) => s,
7419            None => return Ok(None),
7420        };
7421        let id = subject.get("id").and_then(|v| v.as_str()).map(String::from);
7422        match &robot {
7423            None => robot = id,
7424            Some(r) if id.as_deref() == Some(r.as_str()) => {}
7425            _ => return Ok(None),
7426        }
7427        if let Some(prev) = &prev_proof {
7428            if subject.get("prevProof").and_then(|v| v.as_str()) != Some(prev.as_str()) {
7429                return Ok(None);
7430            }
7431        }
7432        match rv::time_ns(att.get("validFrom")) {
7433            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
7434            _ => return Ok(None),
7435        }
7436        prev_proof = att
7437            .get("proof")
7438            .and_then(|p| p.get("proofValue"))
7439            .and_then(|v| v.as_str())
7440            .map(String::from);
7441        latest = Some(subject);
7442    }
7443    let Some(latest) = latest else {
7444        return Ok(None);
7445    };
7446    let max_age = check.max_age_seconds.unwrap_or(WEAR_MAX_AGE_SECONDS);
7447    if !fresh_at(&latest, now_iso, max_age) {
7448        return Ok(None);
7449    }
7450    if let Some(c) = check.challenge {
7451        if c.is_empty() || latest.get("challenge").and_then(|v| v.as_str()) != Some(c) {
7452            return Ok(None);
7453        }
7454    }
7455    Ok(Some(latest))
7456}
7457
7458/// Derive a physical scope narrowed for the given wear level: each numeric cap is
7459/// scaled by `(1 - wear_level)`, and the allowed zones and shift windows are
7460/// carried through unchanged. The result is a valid attenuation of `scope` (never
7461/// broader on any dimension), so the same attenuation check the rest of Vouch uses
7462/// accepts it. A wear level of 0 returns the caps unchanged.
7463pub fn attenuate_for_wear(scope: &Value, wear_level: f64) -> Result<Value> {
7464    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); scope);
7465    // `contains` is false for NaN, so a NaN wear level is refused here rather
7466    // than turning every cap into NaN (which a NaN-unaware check would ignore).
7467    if !(0.0..=1.0).contains(&wear_level) {
7468        return Err(CoreError::Json(
7469            "wear_level must be between 0.0 and 1.0".into(),
7470        ));
7471    }
7472    let problems = scope_problems(scope);
7473    if !problems.is_empty() {
7474        return Err(CoreError::Json(problems.join("; ")));
7475    }
7476    let factor = 1.0 - wear_level;
7477    let empty = Map::new();
7478    let src = scope.as_object().unwrap_or(&empty);
7479    let mut narrowed = Map::new();
7480    for (key, value) in src {
7481        if WEAR_DERATED_CAPS.contains(&key.as_str()) {
7482            if let Some(n) = value.as_f64() {
7483                narrowed.insert(key.clone(), json!(n * factor));
7484                continue;
7485            }
7486        }
7487        narrowed.insert(key.clone(), value.clone());
7488    }
7489    Ok(Value::Object(narrowed))
7490}
7491
7492// ---------------------------------------------------------------------------
7493// Bystander-consent evidence (Phase 5.20)
7494// ---------------------------------------------------------------------------
7495//
7496// A robot working in a shared or public space captures people incidentally
7497// through its cameras and microphones. This lets the robot record, at capture
7498// time, the basis on which a capture was permitted, bound to the specific capture
7499// and to the robot's identity, and lets a bystander (or their device) sign a
7500// consent token bound to that one capture. Only hashes and a consent basis are
7501// stored, never an image or a bystander's identifying data, so the evidence is
7502// verifiable without retaining anyone's biometrics.
7503//
7504// A bystander consent token is signed by the bystander over the hash of the
7505// capture and the robot's DID, so it verifies only against the capture it was
7506// given for and cannot be replayed to a different recording. A bystander-consent
7507// evidence credential is signed by the robot, binding the capture hash to a
7508// consent basis (an explicit token, posted notice, a legitimate interest, or a
7509// redaction that was applied) and, when the basis is explicit consent, to the
7510// tokens that cover it.
7511//
7512// This is the open layer: the cryptographic binding of a consent basis to a
7513// capture, and its verification, holding only hashes. On-device biometric
7514// detection and redaction, and managed consent-registry orchestration, are out of
7515// scope for the open layer.
7516
7517pub const CONSENT_EVIDENCE_TYPE: &str = "BystanderConsentEvidence";
7518pub const CONSENT_TOKEN_TYPE: &str = "BystanderConsentToken";
7519
7520/// Accepted consent bases: the interoperable set a verifier can rely on.
7521/// Implementers MAY use additional values.
7522pub const CONSENT_BASES: [&str; 4] = [
7523    "explicit-consent",
7524    "posted-notice",
7525    "legitimate-interest",
7526    "redacted",
7527];
7528
7529/// Multibase (base64url) SHA-256 of a raw capture. Only the hash travels in the
7530/// token and the evidence; the capture stays wherever the deployment keeps it.
7531pub fn hash_capture(capture: &[u8]) -> String {
7532    mb64(&Sha256::digest(capture))
7533}
7534
7535/// Parameters for [`build_consent_token`]. The signer is the bystander; the token
7536/// binds their consent to one capture (named by `capture_hash`) by one robot
7537/// (`robot_did`). `valid_until`, when set, bounds the window (the wrapper derives
7538/// it from a `valid_seconds` lifetime added to `granted_at`, keeping the core's
7539/// clock caller-supplied). `scope`, when set, records what the consent covers.
7540#[derive(Debug, Clone)]
7541pub struct BuildConsentToken {
7542    pub bystander_did: String,
7543    pub capture_hash: String,
7544    pub robot_did: String,
7545    pub scope: Option<String>,
7546    pub granted_at: String,
7547    pub valid_until: Option<String>,
7548}
7549
7550/// Build a signed `BystanderConsentToken`: a bystander grants consent for a
7551/// specific capture (named by `capture_hash`) by a specific robot (`robot_did`),
7552/// signed by the bystander. Binding the token to the capture hash means it cannot
7553/// be replayed to a different recording. Signed by the bystander.
7554pub fn build_consent_token(bystander_seed: &[u8], params: &BuildConsentToken) -> Result<Value> {
7555    if params.bystander_did.is_empty()
7556        || params.capture_hash.is_empty()
7557        || params.robot_did.is_empty()
7558    {
7559        return Err(CoreError::Json(
7560            "bystander_did, capture_hash, and robot_did are required".into(),
7561        ));
7562    }
7563
7564    let mut subject = Map::new();
7565    subject.insert("id".into(), json!(params.bystander_did));
7566    subject.insert("captureHash".into(), json!(params.capture_hash));
7567    subject.insert("robotDid".into(), json!(params.robot_did));
7568    if let Some(scope) = &params.scope {
7569        subject.insert("scope".into(), json!(scope));
7570    }
7571
7572    let mut cred = Map::new();
7573    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
7574    cred.insert(
7575        "type".into(),
7576        json!(["VerifiableCredential", CONSENT_TOKEN_TYPE]),
7577    );
7578    cred.insert("issuer".into(), json!(params.bystander_did));
7579    cred.insert("validFrom".into(), json!(params.granted_at));
7580    if let Some(vu) = &params.valid_until {
7581        cred.insert("validUntil".into(), json!(vu));
7582    }
7583    cred.insert("credentialSubject".into(), Value::Object(subject));
7584
7585    let opts = BuildProofOptions::new(
7586        crate::verification_method::ed25519_method(&params.bystander_did),
7587        &params.granted_at,
7588    );
7589    data_integrity::sign(&Value::Object(cred), bystander_seed, &opts)
7590}
7591
7592/// Verify a `BystanderConsentToken`: the bystander's proof bound to the issuer
7593/// (`bystander_keys` is a `{did: key}` source, or the bare key of a did:key
7594/// bystander), that the issuer is the bystander (`credentialSubject.id`), that
7595/// the token is bound to this capture and this robot, and that it is within its
7596/// window at `now_iso` (validFrom required, strict times). Returns the
7597/// credentialSubject on success, `None` if invalid.
7598pub fn verify_consent_token(
7599    token: &Value,
7600    bystander_keys: Keys<'_>,
7601    capture_hash: &str,
7602    robot_did: &str,
7603    now_iso: &str,
7604) -> Result<Option<Value>> {
7605    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); token);
7606    let v = match bound(
7607        token,
7608        bystander_keys,
7609        CONSENT_TOKEN_TYPE,
7610        now_iso,
7611        Window::FromRequired,
7612    )? {
7613        Some(v) if issuer_is_subject(&v) => v,
7614        _ => return Ok(None),
7615    };
7616    if v.subject.get("captureHash").and_then(|v| v.as_str()) != Some(capture_hash)
7617        || v.subject.get("robotDid").and_then(|v| v.as_str()) != Some(robot_did)
7618    {
7619        return Ok(None);
7620    }
7621    Ok(Some(v.subject))
7622}
7623
7624/// Parameters for [`build_consent_evidence`]. The signer is the robot; the
7625/// evidence records that a capture (named by `capture_hash`) was permitted on
7626/// `basis`, one of [`CONSENT_BASES`]. `consent_tokens`, when the basis is explicit
7627/// consent, are the bystander tokens that cover it, committed by their proof value.
7628/// `redaction_hash`, when set, records that a redacted output was produced.
7629/// `valid_until`, when set, bounds the window.
7630#[derive(Debug, Clone)]
7631pub struct BuildConsentEvidence {
7632    pub robot_did: String,
7633    pub capture_hash: String,
7634    pub basis: String,
7635    pub consent_tokens: Vec<Value>,
7636    pub redaction_hash: Option<String>,
7637    pub valid_from: String,
7638    pub valid_until: Option<String>,
7639}
7640
7641/// A privacy-preserving reference to a token: its proof value. Never embeds a
7642/// bystander's identifying data.
7643fn consent_token_ref(token: &Value) -> Result<String> {
7644    token
7645        .get("proof")
7646        .and_then(|p| p.get("proofValue"))
7647        .and_then(|v| v.as_str())
7648        .map(String::from)
7649        .ok_or_else(|| CoreError::Json("consent token is missing a proof value".into()))
7650}
7651
7652/// Build a signed `BystanderConsentEvidence` credential: the robot records that a
7653/// capture (named by `capture_hash`) was permitted on `basis`, one of
7654/// [`CONSENT_BASES`]. When the basis is explicit consent, the `consent_tokens` are
7655/// the bystander tokens that cover it, and the evidence commits to them by their
7656/// proof value (never embedding a bystander's identifying data). Signed by the
7657/// robot.
7658pub fn build_consent_evidence(robot_seed: &[u8], params: &BuildConsentEvidence) -> Result<Value> {
7659    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
7660    if params.robot_did.is_empty() || params.capture_hash.is_empty() {
7661        return Err(CoreError::Json(
7662            "robot_did and capture_hash are required".into(),
7663        ));
7664    }
7665    if !CONSENT_BASES.contains(&params.basis.as_str()) {
7666        return Err(CoreError::Json(format!(
7667            "basis must be one of {:?}, got {:?}",
7668            CONSENT_BASES, params.basis
7669        )));
7670    }
7671    if params.basis == "explicit-consent" && params.consent_tokens.is_empty() {
7672        return Err(CoreError::Json(
7673            "explicit-consent basis requires at least one consent token".into(),
7674        ));
7675    }
7676
7677    let mut subject = Map::new();
7678    subject.insert("id".into(), json!(params.robot_did));
7679    subject.insert("captureHash".into(), json!(params.capture_hash));
7680    subject.insert("basis".into(), json!(params.basis));
7681    if !params.consent_tokens.is_empty() {
7682        let mut refs = Vec::with_capacity(params.consent_tokens.len());
7683        for t in &params.consent_tokens {
7684            refs.push(consent_token_ref(t)?);
7685        }
7686        subject.insert("consentTokenRefs".into(), json!(refs));
7687    }
7688    if let Some(rh) = &params.redaction_hash {
7689        subject.insert("redactionHash".into(), json!(rh));
7690    }
7691
7692    let mut cred = Map::new();
7693    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
7694    cred.insert(
7695        "type".into(),
7696        json!(["VerifiableCredential", CONSENT_EVIDENCE_TYPE]),
7697    );
7698    cred.insert("issuer".into(), json!(params.robot_did));
7699    cred.insert("validFrom".into(), json!(params.valid_from));
7700    if let Some(vu) = &params.valid_until {
7701        cred.insert("validUntil".into(), json!(vu));
7702    }
7703    cred.insert("credentialSubject".into(), Value::Object(subject));
7704
7705    let opts = BuildProofOptions::new(
7706        crate::verification_method::ed25519_method(&params.robot_did),
7707        &params.valid_from,
7708    );
7709    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
7710}
7711
7712/// One bystander's public key, looked up by bystander DID, for
7713/// [`verify_consent_evidence`].
7714#[derive(Debug, Clone)]
7715pub struct BystanderKey {
7716    pub did: String,
7717    pub public_key: Vec<u8>,
7718}
7719
7720/// Verify a `BystanderConsentEvidence` credential: the robot's proof bound to
7721/// the robot as issuer (which must also be `credentialSubject.id`), the window
7722/// at `now_iso` (validFrom required), and an accepted basis. When `capture` is
7723/// supplied, its hash must reproduce the attested capture hash.
7724///
7725/// An explicit-consent evidence is only as good as its tokens, so for that
7726/// basis `consent_tokens` and `bystander_keys` are required: every committed
7727/// reference must be matched by a token that verifies, is bound to this
7728/// capture and this robot, and is in its window. For other bases, tokens that
7729/// are supplied are checked the same way. Returns the credentialSubject on
7730/// success, `None` if invalid.
7731pub fn verify_consent_evidence(
7732    evidence: &Value,
7733    robot_keys: Keys<'_>,
7734    capture: Option<&[u8]>,
7735    consent_tokens: Option<&[Value]>,
7736    bystander_keys: Option<&[BystanderKey]>,
7737    now_iso: &str,
7738) -> Result<Option<Value>> {
7739    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); evidence, consent_tokens);
7740    let v = match bound(
7741        evidence,
7742        robot_keys,
7743        CONSENT_EVIDENCE_TYPE,
7744        now_iso,
7745        Window::FromRequired,
7746    )? {
7747        Some(v) if issuer_is_subject(&v) => v,
7748        _ => return Ok(None),
7749    };
7750    let subject = v.subject;
7751    let basis = subject.get("basis").and_then(|v| v.as_str());
7752    match basis {
7753        Some(b) if CONSENT_BASES.contains(&b) => {}
7754        _ => return Ok(None),
7755    }
7756    let capture_hash = match non_empty_str(&subject, "captureHash") {
7757        Some(h) => h.to_string(),
7758        None => return Ok(None),
7759    };
7760    if let Some(c) = capture {
7761        if hash_capture(c) != capture_hash {
7762            return Ok(None);
7763        }
7764    }
7765
7766    let refs: Vec<&str> = match subject.get("consentTokenRefs") {
7767        None => Vec::new(),
7768        Some(Value::Array(a)) if a.iter().all(|r| r.is_string()) => {
7769            a.iter().filter_map(|r| r.as_str()).collect()
7770        }
7771        _ => return Ok(None),
7772    };
7773    let explicit = basis == Some("explicit-consent");
7774    if explicit && refs.is_empty() {
7775        return Ok(None);
7776    }
7777    if explicit && (consent_tokens.is_none() || bystander_keys.is_none()) {
7778        return Ok(None);
7779    }
7780
7781    if let (Some(tokens), Some(keys)) = (consent_tokens, bystander_keys) {
7782        let map = Keys::map_of(keys.iter().map(|k| (k.did.clone(), &k.public_key)));
7783        let mut matched: HashSet<String> = HashSet::new();
7784        for token in tokens {
7785            let tok_ok = !map.is_empty()
7786                && verify_consent_token(token, Keys::Map(&map), &capture_hash, &v.issuer, now_iso)?
7787                    .is_some();
7788            if !tok_ok {
7789                return Ok(None);
7790            }
7791            let r = match consent_token_ref(token) {
7792                Ok(r) if refs.contains(&r.as_str()) => r,
7793                _ => return Ok(None),
7794            };
7795            matched.insert(r);
7796        }
7797        if explicit {
7798            let all: HashSet<String> = refs.iter().map(|r| r.to_string()).collect();
7799            if matched != all {
7800                return Ok(None);
7801            }
7802        }
7803    }
7804
7805    Ok(Some(subject))
7806}
7807
7808// What the no_std depth guard checks in the JSON these types carry.
7809crate::nesting::nested_fields!(MintRobotIdentity; lifecycle);
7810crate::nesting::nested_fields!(BuildProvenance; config);
7811crate::nesting::nested_fields!(BuildSafetyEvidence; halos_stack);
7812crate::nesting::nested_fields!(BuildRobotHeartbeat; motion_digest);
7813crate::nesting::nested_fields!(BuildSafetyRecord; summary);
7814crate::nesting::nested_fields!(BuildDelegationLease; scope);
7815crate::nesting::nested_fields!(BuildConformanceAttestation; report);
7816crate::nesting::nested_fields!(BuildHandoff; release);
7817crate::nesting::nested_fields!(BuildWearAttestation; metrics);
7818crate::nesting::nested_fields!(BuildConsentEvidence; consent_tokens);
7819crate::nesting::nested_fields!(SafetyRecordCheck<'_>; entries);
7820crate::nesting::nested_fields!(CustodyCheck<'_>; head);
7821crate::nesting::nested_fields!(MotionCollector; scope);
7822
7823#[cfg(test)]
7824mod tests {
7825    use super::*;
7826    use crate::keys::Ed25519KeyPair;
7827    #[allow(unused_imports)]
7828    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
7829    #[allow(unused_imports)]
7830    use crate::robotics_verify::Keys;
7831    use std::fs;
7832
7833    fn load_vector() -> Value {
7834        let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
7835            .expect("interop vector present");
7836        serde_json::from_str(&raw).unwrap()
7837    }
7838
7839    fn software_root_attest(root_seed: &[u8], robot_did: &str, robot_key_mb: &str) -> Vec<u8> {
7840        let kp = Ed25519KeyPair::from_seed_slice(root_seed).unwrap();
7841        let binding = robot_identity_binding(robot_did, robot_key_mb);
7842        kp.sign(&binding).to_vec()
7843    }
7844
7845    // Cross-language interop: Go and TypeScript verify this same Python-minted
7846    // credential; the Rust core must too.
7847    #[test]
7848    fn verifies_python_interop_vector() {
7849        let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
7850            .expect("interop vector present");
7851        let vector: Value = serde_json::from_str(&raw).unwrap();
7852        let jwk_x = vector["robot_public_key_jwk"]["x"].as_str().unwrap();
7853        let robot_pub = URL_SAFE_NO_PAD.decode(jwk_x).unwrap();
7854        let cred = vector["robot_identity_credential"].clone();
7855
7856        let subject = verify_robot_identity(&cred, kd(&cred, &robot_pub), None, TNOW).unwrap();
7857        let subject = subject.expect("the Python interop vector must verify in Rust");
7858        assert_eq!(subject["make"], json!("Acme Robotics"));
7859    }
7860
7861    #[test]
7862    fn mint_verify_roundtrip() {
7863        let robot_seed = [3u8; 32];
7864        let root_seed = [7u8; 32];
7865        let robot_did = "did:web:robot.example.com";
7866        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
7867        let root_kp = Ed25519KeyPair::from_seed(&root_seed);
7868
7869        let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
7870        let params = MintRobotIdentity {
7871            robot_did: robot_did.into(),
7872            make: "Acme".into(),
7873            model: "AR-7".into(),
7874            serial: "SN-1".into(),
7875            owner: Some("did:web:owner.example.com".into()),
7876            root_kind: "TPM".into(),
7877            root_public_multibase: root_kp.public_multikey(),
7878            attestation,
7879            lifecycle: None,
7880            valid_from: "2026-01-01T00:00:00Z".into(),
7881            valid_until: None,
7882        };
7883        let cred = mint_robot_identity(&robot_seed, &params).unwrap();
7884        let subject =
7885            verify_robot_identity(&cred, kd(&cred, &robot_kp.public_key()), None, TNOW).unwrap();
7886        assert!(subject.is_some(), "round-trip identity must verify");
7887    }
7888
7889    // Cross-language interop: this HalosSafetyEvidenceCredential, its black-box
7890    // entries, and the robot public key were produced by the Python reference
7891    // (vouch/robotics/halos.py) from a fixed Ed25519 seed (0x05 x32), a fixed
7892    // black-box key, and a fixed `created` timestamp. The Rust verify must accept
7893    // it, and must reject a tampered entry or a wrong entry count.
7894    const PY_HALOS_CREDENTIAL: &str = r#"{"@context":["https://www.w3.org/ns/credentials/v2","https://vouch-protocol.com/contexts/v1"],"type":["VerifiableCredential","HalosSafetyEvidenceCredential"],"issuer":"did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2","validFrom":"2026-01-01T00:00:00Z","credentialSubject":{"id":"did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2","blackboxHead":"utfv4sSWc6TH-n0HrNqB35Hacy3lYVksU0QYz6gbHol8","entryCount":3,"halosStack":{"igxSom":"IGX-Orin-64","halosCore":"1.4.0","blueprint":["SAIM","SEI","SDM"]},"window":{"from":"2026-01-01T00:00:00Z","to":"2026-01-01T00:00:10Z"},"robotIdentity":"urn:uuid:robot-identity-1"},"proof":{"type":"DataIntegrityProof","cryptosuite":"eddsa-jcs-2022","created":"2026-01-01T00:00:00Z","verificationMethod":"did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2#key-1","proofPurpose":"assertionMethod","proofValue":"z5FjYsg9oQ543K8jtAsaYyYS3YG53ixoUYnhYop8oJWuLCoZp45uYos4416i13JR2bkt4tPtKB9hTk5xG9s8mQoQd"}}"#;
7895
7896    const PY_HALOS_ENTRIES: &str = r#"[{"version":"1.0","seq":0,"timestamp":"2026-01-01T00:00:01Z","event":"hazard_detected","ciphertext":"uzhrB2FNU_UNfM5ey2Dx1ogaX4_IuPx-0ylXC7022a7TqQ5ktnB9GmFqmrv9VzRx7ecoSyCAC6b6pcp1r7K2nQLSsDnmX2oar","prevHash":"uAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","entryHash":"uZm_cIGAA1kuQio4QWWwbE27xBVZE9QSuvAGweybxZZk"},{"version":"1.0","seq":1,"timestamp":"2026-01-01T00:00:02Z","event":"slow_stop","ciphertext":"ulQY1i5OnYlWdSJOS0Rp4esqwLIyh_4TM4WO-apHKoJde3AgFaGHgPIZ2GIb8q5sYKjtB9Az6kUnajkhzYA7VPQ6ChvF_3yQGfHuIM1lnaF5JEg","prevHash":"uZm_cIGAA1kuQio4QWWwbE27xBVZE9QSuvAGweybxZZk","entryHash":"uPulCLvRvEs_zV1R3koher2EMjyBZy5Rfe-Sv0Y64Tfk"},{"version":"1.0","seq":2,"timestamp":"2026-01-01T00:00:03Z","event":"cleared","ciphertext":"us7pdRfPVAGSeKCQU7RgEb1ee_2358wbs_P4epd4gPJoUUx9bw3hJSiVPGKwc2Xc3PjZySEaWKgK_F0h5mU2sxb0pEZ-E_FwwQQk3","prevHash":"uPulCLvRvEs_zV1R3koher2EMjyBZy5Rfe-Sv0Y64Tfk","entryHash":"utfv4sSWc6TH-n0HrNqB35Hacy3lYVksU0QYz6gbHol8"}]"#;
7897
7898    // Robot public key (raw 32-byte Ed25519) as base64url-no-pad.
7899    const PY_HALOS_ROBOT_PUB: &str = "bnoc3Smwt4_ROvTFWY_v9O8qlxZuPKby5Pv8zYBQW_E";
7900
7901    #[test]
7902    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
7903    fn build_verify_safety_evidence_roundtrip() {
7904        let robot_seed = [5u8; 32];
7905        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
7906
7907        // A black-box chain the robot recorded.
7908        let mut log = BlackBoxLog::new(&[9u8; 32], None).unwrap();
7909        log.append(
7910            "hazard_detected",
7911            &json!({"zone": "cell-3"}),
7912            "2026-01-01T00:00:01Z",
7913        )
7914        .unwrap();
7915        log.append(
7916            "slow_stop",
7917            &json!({"reason": "human"}),
7918            "2026-01-01T00:00:02Z",
7919        )
7920        .unwrap();
7921        let entries: Vec<Value> = log.entries().to_vec();
7922
7923        let params = BuildSafetyEvidence {
7924            halos_stack: json!({"igxSom": "IGX-Orin-64", "halosCore": "1.4.0"}),
7925            window_from: "2026-01-01T00:00:00Z".into(),
7926            window_to: "2026-01-01T00:00:10Z".into(),
7927            blackbox_head: log.head().to_string(),
7928            entry_count: entries.len() as u64,
7929            robot_identity: Some("urn:uuid:robot-identity-1".into()),
7930            valid_seconds: Some(3600),
7931            valid_from: "2026-01-01T00:00:00Z".into(),
7932            created: "2026-01-01T00:00:00Z".into(),
7933            robot_did: None,
7934        };
7935        let cred = build_safety_evidence(&robot_seed, &params).unwrap();
7936
7937        // The issuer is the did:key derived from the seed and the validUntil is
7938        // rendered from the valid_seconds lifetime.
7939        assert_eq!(
7940            cred["issuer"],
7941            json!("did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
7942        );
7943        assert_eq!(cred["validUntil"], json!("2026-01-01T01:00:00Z"));
7944
7945        let (ok, subject) = verify_safety_evidence(
7946            &cred,
7947            kd(&cred, &robot_kp.public_key()),
7948            Some(&entries),
7949            TNOW,
7950        )
7951        .unwrap();
7952        assert!(ok, "a Rust-built evidence credential must verify in Rust");
7953        assert_eq!(subject.unwrap()["entryCount"], json!(2));
7954
7955        // A credential whose issuer is not the subject id is rejected.
7956        let mut forged = cred.clone();
7957        forged["issuer"] = json!("did:key:z6Mkother");
7958        let (ok_forged, _) =
7959            verify_safety_evidence(&forged, kd(&forged, &robot_kp.public_key()), None, TNOW)
7960                .unwrap();
7961        assert!(!ok_forged, "issuer must equal credentialSubject.id");
7962    }
7963
7964    #[test]
7965    fn verifies_python_halos_evidence() {
7966        let credential: Value = serde_json::from_str(PY_HALOS_CREDENTIAL).unwrap();
7967        let entries: Vec<Value> = serde_json::from_str(PY_HALOS_ENTRIES).unwrap();
7968        let robot_pub = URL_SAFE_NO_PAD.decode(PY_HALOS_ROBOT_PUB).unwrap();
7969
7970        // The Python-produced credential and its entries verify in Rust.
7971        let (ok, subject) = verify_safety_evidence(
7972            &credential,
7973            kd(&credential, &robot_pub),
7974            Some(&entries),
7975            TNOW,
7976        )
7977        .unwrap();
7978        assert!(ok, "the Python Halos evidence must verify in Rust");
7979        let subject = subject.expect("subject present on success");
7980        assert_eq!(subject["entryCount"], json!(3));
7981        assert_eq!(
7982            subject["blackboxHead"],
7983            json!("utfv4sSWc6TH-n0HrNqB35Hacy3lYVksU0QYz6gbHol8")
7984        );
7985
7986        // The proof and issuer binding hold even without the entries.
7987        let (ok_no_entries, _) =
7988            verify_safety_evidence(&credential, kd(&credential, &robot_pub), None, TNOW).unwrap();
7989        assert!(
7990            ok_no_entries,
7991            "proof and issuer binding verify without entries"
7992        );
7993
7994        // Tampering one entry breaks the chain, so verification fails.
7995        let mut tampered = entries.clone();
7996        tampered[1]["ciphertext"] = json!("utampered_ciphertext_value_that_does_not_match_hash");
7997        let (ok_tampered, subj_tampered) = verify_safety_evidence(
7998            &credential,
7999            kd(&credential, &robot_pub),
8000            Some(&tampered),
8001            TNOW,
8002        )
8003        .unwrap();
8004        assert!(!ok_tampered, "a tampered entry must be rejected");
8005        assert!(subj_tampered.is_none());
8006
8007        // A wrong entry count (here a truncated log) is rejected against the seal.
8008        let truncated = entries[..2].to_vec();
8009        let (ok_truncated, _) = verify_safety_evidence(
8010            &credential,
8011            kd(&credential, &robot_pub),
8012            Some(&truncated),
8013            TNOW,
8014        )
8015        .unwrap();
8016        assert!(!ok_truncated, "a wrong entry count must be rejected");
8017    }
8018
8019    #[test]
8020    fn forged_hardware_root_fails() {
8021        let robot_seed = [3u8; 32];
8022        let root_seed = [7u8; 32];
8023        let attacker_seed = [9u8; 32];
8024        let robot_did = "did:web:robot.example.com";
8025        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
8026        let root_kp = Ed25519KeyPair::from_seed(&root_seed);
8027        let attacker_kp = Ed25519KeyPair::from_seed(&attacker_seed);
8028
8029        let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
8030        let params = MintRobotIdentity {
8031            robot_did: robot_did.into(),
8032            make: "Acme".into(),
8033            model: "AR-7".into(),
8034            serial: "SN-1".into(),
8035            owner: None,
8036            root_kind: "TPM".into(),
8037            root_public_multibase: root_kp.public_multikey(),
8038            attestation,
8039            lifecycle: None,
8040            valid_from: "2026-01-01T00:00:00Z".into(),
8041            valid_until: None,
8042        };
8043        let mut cred = mint_robot_identity(&robot_seed, &params).unwrap();
8044
8045        // Point the hardware-root key at an attacker's and re-sign the credential
8046        // proof; the attestation over the binding no longer matches.
8047        cred["credentialSubject"]["hardwareRoot"]["publicKeyMultibase"] =
8048            json!(attacker_kp.public_multikey());
8049        let resigned = {
8050            let mut bare = cred.clone();
8051            bare.as_object_mut().unwrap().remove("proof");
8052            let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), "2026-01-01T00:00:00Z");
8053            data_integrity::sign(&bare, &robot_seed, &opts).unwrap()
8054        };
8055        assert!(verify_robot_identity(
8056            &resigned,
8057            kd(&resigned, &robot_kp.public_key()),
8058            None,
8059            TNOW
8060        )
8061        .unwrap()
8062        .is_none());
8063    }
8064
8065    // Cross-language interop: Rust reproduces the exact configHash Python pinned.
8066    #[test]
8067    fn config_hash_matches_interop_vector() {
8068        let vector = load_vector();
8069        let got = config_hash(&vector["config"]);
8070        assert_eq!(got, vector["expected_config_hash"].as_str().unwrap());
8071        assert_eq!(got, "uMh9_H2Lk51-m9SpBhiEa1oqIwwwA7yT27e2QFS0YKUs");
8072    }
8073
8074    #[test]
8075    fn provenance_roundtrip_and_config_tamper() {
8076        let seed = [4u8; 32];
8077        let kp = Ed25519KeyPair::from_seed(&seed);
8078        let config = load_vector()["config"].clone();
8079        let params = BuildProvenance {
8080            issuer_did: "did:web:robot.example.com".into(),
8081            robot_did: "did:web:robot.example.com".into(),
8082            model_name: "openvla-7b".into(),
8083            weights_hash: "uABCDEF".into(),
8084            safety_policy: "did:web:authority.example.com#policy-v3".into(),
8085            config: Some(config.clone()),
8086            version: Some("2026.06".into()),
8087            supersedes: None,
8088            valid_from: "2026-01-01T00:00:00Z".into(),
8089            valid_until: None,
8090        };
8091        let att = build_provenance_attestation(&seed, &params).unwrap();
8092        assert!(verify_provenance_attestation(
8093            &att,
8094            kd(&att, &kp.public_key()),
8095            Some(&config),
8096            TNOW
8097        )
8098        .unwrap()
8099        .is_some());
8100        // A different config than the one signed must be rejected.
8101        let tampered = json!({"temperature": 1.0, "max_torque": 99.0});
8102        assert!(verify_provenance_attestation(
8103            &att,
8104            kd(&att, &kp.public_key()),
8105            Some(&tampered),
8106            TNOW
8107        )
8108        .unwrap()
8109        .is_none());
8110    }
8111
8112    #[test]
8113    fn capability_build_check_attenuate() {
8114        let seed = [6u8; 32];
8115        let kp = Ed25519KeyPair::from_seed(&seed);
8116        let params = BuildPhysicalScope {
8117            issuer_did: "did:web:fleet.example.com".into(),
8118            subject_did: "did:web:robot.example.com".into(),
8119            max_force_n: Some(80.0),
8120            max_speed_mps: Some(2.0),
8121            max_speed_near_humans_mps: Some(0.5),
8122            allowed_zones: Some(vec!["warehouse-a".into(), "dock-3".into()]),
8123            shift_windows: Some(vec![ShiftWindow {
8124                start: "08:00".into(),
8125                end: "18:00".into(),
8126            }]),
8127            valid_from: "2026-01-01T00:00:00Z".into(),
8128            valid_until: None,
8129        };
8130        let cred = build_physical_scope_credential(&seed, &params).unwrap();
8131        assert!(cred["type"]
8132            .as_array()
8133            .unwrap()
8134            .contains(&json!(PHYSICAL_SCOPE_TYPE)));
8135        assert!(data_integrity::verify_proof(&cred, &kp.public_key()).unwrap());
8136
8137        let scope = cred["credentialSubject"]["physicalScope"].clone();
8138        let within = check_physical_action(
8139            &scope,
8140            &PhysicalAction {
8141                force_n: Some(50.0),
8142                speed_mps: Some(1.5),
8143                zone: Some("warehouse-a".into()),
8144                time_hm: Some("09:30".into()),
8145                ..Default::default()
8146            },
8147        );
8148        assert!(within.ok, "within-scope action: {:?}", within.reasons);
8149        assert!(
8150            !check_physical_action(
8151                &scope,
8152                &PhysicalAction {
8153                    force_n: Some(120.0),
8154                    ..Default::default()
8155                }
8156            )
8157            .ok
8158        );
8159        // Near humans the 0.5 m/s cap applies; 1.5 is fine away from them.
8160        assert!(
8161            !check_physical_action(
8162                &scope,
8163                &PhysicalAction {
8164                    speed_mps: Some(1.5),
8165                    near_humans: true,
8166                    ..Default::default()
8167                }
8168            )
8169            .ok
8170        );
8171        assert!(
8172            check_physical_action(
8173                &scope,
8174                &PhysicalAction {
8175                    speed_mps: Some(1.5),
8176                    near_humans: false,
8177                    ..Default::default()
8178                }
8179            )
8180            .ok
8181        );
8182        assert!(
8183            !check_physical_action(
8184                &scope,
8185                &PhysicalAction {
8186                    zone: Some("loading-bay-9".into()),
8187                    ..Default::default()
8188                }
8189            )
8190            .ok
8191        );
8192        assert!(
8193            !check_physical_action(
8194                &scope,
8195                &PhysicalAction {
8196                    time_hm: Some("23:00".into()),
8197                    ..Default::default()
8198                }
8199            )
8200            .ok
8201        );
8202    }
8203
8204    #[test]
8205    fn attenuation_rules() {
8206        let parent = json!({
8207            "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
8208            "allowedZones": ["warehouse-a", "dock-3"],
8209            "shiftWindows": [{"start": "08:00", "end": "18:00"}]
8210        });
8211        let narrower = json!({
8212            "maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3,
8213            "allowedZones": ["warehouse-a"],
8214            "shiftWindows": [{"start": "09:00", "end": "17:00"}]
8215        });
8216        assert!(attenuates(&parent, &narrower));
8217        assert!(!attenuates(
8218            &parent,
8219            &json!({"maxForceN": 100.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"]})
8220        ));
8221        assert!(!attenuates(
8222            &parent,
8223            &json!({"maxForceN": 50.0, "allowedZones": ["warehouse-a"]})
8224        ));
8225        assert!(!attenuates(
8226            &parent,
8227            &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["loading-bay-9"]})
8228        ));
8229        assert!(!attenuates(
8230            &parent,
8231            &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"], "shiftWindows": [{"start": "06:00", "end": "20:00"}]})
8232        ));
8233    }
8234
8235    #[test]
8236    fn handshake_full_flow() {
8237        let a_seed = [11u8; 32];
8238        let b_seed = [12u8; 32];
8239        let a = Ed25519KeyPair::from_seed(&a_seed);
8240        let b = Ed25519KeyPair::from_seed(&b_seed);
8241        let a_did = "did:web:robot-a.example.com";
8242        let b_did = "did:web:robot-b.example.com";
8243        let policy_b = TrustPolicy::new(["robot-a.example.com".to_string()], false);
8244
8245        let hello = build_hello(
8246            &a_seed,
8247            &BuildHello {
8248                from_did: a_did.into(),
8249                proposed_scope: vec!["lift".into(), "carry".into(), "scan".into()],
8250                nonce: "abc123".into(),
8251                peer_did: Some(b_did.into()),
8252                issued_at: "2026-01-01T00:00:00Z".into(),
8253            },
8254        )
8255        .unwrap();
8256
8257        let accept = build_accept(
8258            &b_seed,
8259            &hello,
8260            Keys::One(a_did, &a.public_key()),
8261            &policy_b,
8262            &BuildAccept {
8263                from_did: b_did.into(),
8264                offered_scope: vec!["carry".into(), "scan".into(), "weld".into()],
8265                session_id: "urn:uuid:sess-1".into(),
8266                valid_until: "2026-01-01T00:05:00Z".into(),
8267                created: "2026-01-01T00:00:01Z".into(),
8268            },
8269        )
8270        .unwrap();
8271
8272        let session = verify_accept(
8273            &accept,
8274            Keys::One(b_did, &b.public_key()),
8275            &hello,
8276            Some("abc123"),
8277            None,
8278            "2026-01-01T00:00:01Z",
8279        )
8280        .unwrap()
8281        .expect("accept verifies");
8282        // A bare key cannot vouch for a did:web peer, and a stale or expired
8283        // exchange is refused.
8284        assert!(verify_accept(
8285            &accept,
8286            Keys::Bare(&b.public_key()),
8287            &hello,
8288            None,
8289            None,
8290            "2026-01-01T00:00:01Z"
8291        )
8292        .unwrap()
8293        .is_none());
8294        assert!(verify_accept(
8295            &accept,
8296            Keys::One(b_did, &b.public_key()),
8297            &hello,
8298            None,
8299            None,
8300            "2026-01-01T00:06:00Z"
8301        )
8302        .unwrap()
8303        .is_none());
8304        // An ACCEPT replayed against another HELLO is refused.
8305        let other_hello = build_hello(
8306            &a_seed,
8307            &BuildHello {
8308                from_did: a_did.into(),
8309                proposed_scope: vec!["carry".into()],
8310                nonce: "zzz".into(),
8311                peer_did: Some(b_did.into()),
8312                issued_at: "2026-01-01T00:00:00Z".into(),
8313            },
8314        )
8315        .unwrap();
8316        assert!(verify_accept(
8317            &accept,
8318            Keys::One(b_did, &b.public_key()),
8319            &other_hello,
8320            None,
8321            None,
8322            "2026-01-01T00:00:01Z"
8323        )
8324        .unwrap()
8325        .is_none());
8326        assert_eq!(session.scope, vec!["carry".to_string(), "scan".to_string()]);
8327        assert_eq!(session.initiator, a_did);
8328        assert_eq!(session.responder, b_did);
8329
8330        let confirm = build_confirm(&a_seed, a_did, &session, "2026-01-01T00:00:02Z").unwrap();
8331        assert!(verify_confirm(
8332            &confirm,
8333            Keys::One(a_did, &a.public_key()),
8334            &accept,
8335            "2026-01-01T00:00:02Z"
8336        )
8337        .unwrap());
8338        assert!(!verify_confirm(
8339            &confirm,
8340            Keys::One(a_did, &a.public_key()),
8341            &accept,
8342            "2026-01-01T00:06:00Z"
8343        )
8344        .unwrap());
8345        // A stale HELLO is refused by the responder.
8346        assert!(build_accept(
8347            &b_seed,
8348            &hello,
8349            Keys::One(a_did, &a.public_key()),
8350            &policy_b,
8351            &BuildAccept {
8352                from_did: b_did.into(),
8353                offered_scope: vec!["carry".into()],
8354                session_id: "s2".into(),
8355                valid_until: "2026-01-01T01:00:00Z".into(),
8356                created: "2026-01-01T00:10:00Z".into(),
8357            }
8358        )
8359        .is_err());
8360    }
8361
8362    #[test]
8363    fn handshake_untrusted_tamper_and_nonce() {
8364        let a_seed = [11u8; 32];
8365        let b_seed = [12u8; 32];
8366        let a = Ed25519KeyPair::from_seed(&a_seed);
8367        let b = Ed25519KeyPair::from_seed(&b_seed);
8368        let a_did = "did:web:robot-a.example.com";
8369        let b_did = "did:web:robot-b.example.com";
8370
8371        let hello = build_hello(
8372            &a_seed,
8373            &BuildHello {
8374                from_did: a_did.into(),
8375                proposed_scope: vec!["lift".into()],
8376                nonce: "n1".into(),
8377                peer_did: None,
8378                issued_at: "2026-01-01T00:00:00Z".into(),
8379            },
8380        )
8381        .unwrap();
8382
8383        // Untrusted initiator.
8384        let strict = TrustPolicy::new(["someone-else.example.com".to_string()], false);
8385        assert!(build_accept(
8386            &b_seed,
8387            &hello,
8388            Keys::One(a_did, &a.public_key()),
8389            &strict,
8390            &BuildAccept {
8391                from_did: b_did.into(),
8392                offered_scope: vec!["lift".into()],
8393                session_id: "s".into(),
8394                valid_until: "2026-01-01T00:05:00Z".into(),
8395                created: "2026-01-01T00:00:01Z".into(),
8396            },
8397        )
8398        .is_err());
8399
8400        // Tampered HELLO (scope broadened after signing) fails signature check.
8401        let open = TrustPolicy::new(Vec::<String>::new(), true);
8402        let mut tampered = hello.clone();
8403        tampered["proposedScope"] = json!(["lift", "weld"]);
8404        assert!(build_accept(
8405            &b_seed,
8406            &tampered,
8407            Keys::One(a_did, &a.public_key()),
8408            &open,
8409            &BuildAccept {
8410                from_did: b_did.into(),
8411                offered_scope: vec!["lift".into(), "weld".into()],
8412                session_id: "s".into(),
8413                valid_until: "2026-01-01T00:05:00Z".into(),
8414                created: "2026-01-01T00:00:01Z".into(),
8415            },
8416        )
8417        .is_err());
8418
8419        // Nonce mismatch on a valid ACCEPT.
8420        let accept = build_accept(
8421            &b_seed,
8422            &hello,
8423            Keys::One(a_did, &a.public_key()),
8424            &open,
8425            &BuildAccept {
8426                from_did: b_did.into(),
8427                offered_scope: vec!["lift".into()],
8428                session_id: "s".into(),
8429                valid_until: "2026-01-01T00:05:00Z".into(),
8430                created: "2026-01-01T00:00:01Z".into(),
8431            },
8432        )
8433        .unwrap();
8434        assert!(verify_accept(
8435            &accept,
8436            Keys::One(b_did, &b.public_key()),
8437            &hello,
8438            Some("wrong-nonce"),
8439            Some(&open),
8440            "2026-01-01T00:00:01Z"
8441        )
8442        .unwrap()
8443        .is_none());
8444    }
8445
8446    #[test]
8447    fn did_web_domain_parsing() {
8448        let domain = |did: &str| did_web_domain(did);
8449        assert_eq!(
8450            domain("did:web:example.com").as_deref(),
8451            Some("example.com")
8452        );
8453        // A path is part of the name, so a bare-domain entry never covers it.
8454        assert_eq!(
8455            domain("did:web:robot.example.com:agent").as_deref(),
8456            Some("robot.example.com:agent")
8457        );
8458        assert_eq!(domain("did:web:robot.example.com:"), None);
8459        assert_eq!(domain("did:key:z6Mk"), None);
8460        // A did:webvh DID gives its parsed host, never read as did:web.
8461        let scid = "QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ";
8462        assert_eq!(
8463            domain(&format!("did:webvh:{scid}:Robot.Example.com%3A8443:agents")).as_deref(),
8464            Some("robot.example.com:agents")
8465        );
8466        // One that does not parse has no domain.
8467        assert_eq!(domain("did:webvh:{SCID}:robot.example.com"), None);
8468        assert_eq!(domain(&format!("did:webvh:{scid}:127.0.0.1")), None);
8469        assert_eq!(domain("did:webvhx:robot.example.com"), None);
8470        let policy = TrustPolicy::new(["robot.example.com".to_string()], false);
8471        assert!(policy.is_trusted(&format!("did:webvh:{scid}:robot.example.com")));
8472        assert!(!policy.is_trusted(&format!("did:webvh:{scid}:other.example.com")));
8473        assert!(!policy.is_trusted("did:webvh:{SCID}:robot.example.com"));
8474    }
8475
8476    #[test]
8477    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
8478    fn blackbox_append_open_and_chain() {
8479        let key = [0x11u8; 32];
8480        let mut log = BlackBoxLog::new(&key, None).unwrap();
8481        let e0 = log
8482            .append(
8483                "motion",
8484                &json!({"speed": 1.5, "joint": "elbow"}),
8485                "2026-01-01T00:00:00Z",
8486            )
8487            .unwrap();
8488        log.append("stop", &json!({"reason": "human"}), "2026-01-01T00:00:01Z")
8489            .unwrap();
8490
8491        // Round-trip decrypt.
8492        let opened = log.open(&e0).unwrap();
8493        assert_eq!(opened["joint"], json!("elbow"));
8494
8495        // Chain verifies, in memory and after a JSON round trip.
8496        assert!(verify_blackbox_chain(log.entries(), None).ok);
8497        let wire: Vec<Value> =
8498            serde_json::from_str(&serde_json::to_string(log.entries()).unwrap()).unwrap();
8499        assert!(verify_blackbox_chain(&wire, None).ok);
8500        assert_eq!(open_entry(&wire[0], &key).unwrap()["joint"], json!("elbow"));
8501
8502        // Tamper detection.
8503        let mut tampered = wire.clone();
8504        tampered[1]["event"] = json!("tampered");
8505        assert!(!verify_blackbox_chain(&tampered, None).ok);
8506
8507        // Wrong key fails decryption; bad key length rejected.
8508        assert!(open_entry(&e0, &[0x22u8; 32]).is_err());
8509        assert!(BlackBoxLog::new(&[0u8; 16], None).is_err());
8510
8511        // Genesis constant matches the multibase of 32 zero bytes.
8512        assert_eq!(genesis_prev_hash(), format!("u{}", "A".repeat(43)));
8513    }
8514
8515    #[test]
8516    fn killswitch_build_verify_and_trust() {
8517        let seed = [13u8; 32];
8518        let kp = Ed25519KeyPair::from_seed(&seed);
8519        let cred = build_killswitch_credential(
8520            &seed,
8521            &BuildKillswitch {
8522                issuer_did: "did:web:safety.example.com".into(),
8523                target: "did:web:robot.example.com".into(),
8524                reason: "human in path".into(),
8525                command: None,
8526                scope: Some(vec!["arm".into(), "drive".into()]),
8527                valid_from: "2026-01-01T00:00:00Z".into(),
8528                valid_until: None,
8529            },
8530        )
8531        .unwrap();
8532
8533        let mut trusted = HashSet::new();
8534        trusted.insert("did:web:safety.example.com".to_string());
8535        let subject =
8536            verify_killswitch_credential(&cred, kd(&cred, &kp.public_key()), Some(&trusted), TNOW)
8537                .unwrap()
8538                .expect("trusted authority verifies");
8539        assert_eq!(subject["command"], json!(EMERGENCY_STOP));
8540
8541        // Untrusted issuer rejected though the signature is valid.
8542        let mut other = HashSet::new();
8543        other.insert("did:web:someone-else.example.com".to_string());
8544        assert!(verify_killswitch_credential(
8545            &cred,
8546            kd(&cred, &kp.public_key()),
8547            Some(&other),
8548            TNOW
8549        )
8550        .unwrap()
8551        .is_none());
8552
8553        // Wrong type rejected.
8554        let mut wrong = cred.clone();
8555        wrong["type"] = json!(["VerifiableCredential"]);
8556        assert!(
8557            verify_killswitch_credential(&wrong, kd(&wrong, &kp.public_key()), None, TNOW)
8558                .unwrap()
8559                .is_none()
8560        );
8561    }
8562
8563    #[test]
8564    fn passport_build_encode_verify() {
8565        let seed = [14u8; 32];
8566        let kp = Ed25519KeyPair::from_seed(&seed);
8567        let did = "did:web:robot.example.com";
8568        let pass = build_passport(
8569            &seed,
8570            &BuildPassport {
8571                issuer_did: did.into(),
8572                robot_did: did.into(),
8573                make: "Acme Robotics".into(),
8574                model: "AR-7".into(),
8575                owner: "did:web:owner.example.com".into(),
8576                authorized_actions: vec!["lift".into(), "carry".into()],
8577                certification: Some("ISO-10218".into()),
8578                status: None,
8579                valid_from: "2026-01-01T00:00:00Z".into(),
8580                valid_until: None,
8581            },
8582        )
8583        .unwrap();
8584
8585        // Direct verify.
8586        let subject = verify_passport(
8587            &pass,
8588            kd(&pass, &kp.public_key()),
8589            None,
8590            "2026-06-01T00:00:00Z",
8591        )
8592        .unwrap()
8593        .expect("passport verifies");
8594        assert_eq!(subject["owner"], json!("did:web:owner.example.com"));
8595        assert_eq!(subject["status"], json!(STATUS_ACTIVE));
8596
8597        // Encode to a URI, decode, and verify the offline-scan path.
8598        let uri = encode_passport(&pass);
8599        assert!(uri.starts_with("vouch-passport:u"));
8600        let decoded = decode_passport(&uri).unwrap();
8601        assert!(verify_passport(
8602            &decoded,
8603            kd(&decoded, &kp.public_key()),
8604            None,
8605            "2026-06-01T00:00:00Z"
8606        )
8607        .unwrap()
8608        .is_some());
8609        assert!(verify_passport_uri(
8610            &uri,
8611            Keys::Resolver(&any_did(&kp.public_key())),
8612            None,
8613            "2026-06-01T00:00:00Z"
8614        )
8615        .unwrap()
8616        .is_some());
8617
8618        // Tamper and wrong type rejected.
8619        let mut tampered = pass.clone();
8620        tampered["credentialSubject"]["owner"] = json!("did:web:attacker.example.com");
8621        assert!(verify_passport(
8622            &tampered,
8623            kd(&tampered, &kp.public_key()),
8624            None,
8625            "2026-06-01T00:00:00Z"
8626        )
8627        .unwrap()
8628        .is_none());
8629
8630        // Malformed URI.
8631        assert!(decode_passport("https://example.com/x").is_err());
8632    }
8633
8634    #[test]
8635    fn passport_expiry_and_suspended() {
8636        let seed = [15u8; 32];
8637        let kp = Ed25519KeyPair::from_seed(&seed);
8638        let did = "did:web:robot.example.com";
8639
8640        // Expiry: valid inside the window, expired past validUntil.
8641        let timed = build_passport(
8642            &seed,
8643            &BuildPassport {
8644                issuer_did: did.into(),
8645                robot_did: did.into(),
8646                make: "Acme".into(),
8647                model: "AR-7".into(),
8648                owner: "did:web:owner.example.com".into(),
8649                authorized_actions: vec!["lift".into()],
8650                certification: None,
8651                status: None,
8652                valid_from: "2026-01-01T00:00:00Z".into(),
8653                valid_until: Some("2026-01-01T00:01:00Z".into()),
8654            },
8655        )
8656        .unwrap();
8657        assert!(verify_passport(
8658            &timed,
8659            kd(&timed, &kp.public_key()),
8660            None,
8661            "2026-01-01T00:00:30Z"
8662        )
8663        .unwrap()
8664        .is_some());
8665        assert!(verify_passport(
8666            &timed,
8667            kd(&timed, &kp.public_key()),
8668            None,
8669            "2026-01-01T00:02:00Z"
8670        )
8671        .unwrap()
8672        .is_none());
8673
8674        // Suspended still verifies but the status is surfaced.
8675        let suspended = build_passport(
8676            &seed,
8677            &BuildPassport {
8678                issuer_did: did.into(),
8679                robot_did: did.into(),
8680                make: "Acme".into(),
8681                model: "AR-7".into(),
8682                owner: "did:web:owner.example.com".into(),
8683                authorized_actions: vec!["lift".into()],
8684                certification: None,
8685                status: Some(STATUS_SUSPENDED.into()),
8686                valid_from: "2026-01-01T00:00:00Z".into(),
8687                valid_until: None,
8688            },
8689        )
8690        .unwrap();
8691        let subject = verify_passport(
8692            &suspended,
8693            kd(&suspended, &kp.public_key()),
8694            None,
8695            "2026-06-01T00:00:00Z",
8696        )
8697        .unwrap()
8698        .expect("a suspended passport still verifies");
8699        assert_eq!(subject["status"], json!(STATUS_SUSPENDED));
8700    }
8701
8702    // Cross-language interop: Rust reproduces the exact motion digest Python
8703    // pinned from the same fixed samples against the same physical scope.
8704    #[test]
8705    fn motion_digest_matches_interop_vector() {
8706        let vector = load_vector();
8707        let scope = vector["physical_scope"].clone();
8708        let mut collector = MotionCollector::new(Some(scope));
8709        collector
8710            .record(&MotionSample {
8711                force_n: Some(12.0),
8712                speed_mps: Some(0.4),
8713                near_humans: false,
8714                zone: Some("cell-3".into()),
8715                time_hm: None,
8716            })
8717            .unwrap();
8718        collector
8719            .record(&MotionSample {
8720                force_n: Some(20.0),
8721                speed_mps: Some(0.2),
8722                near_humans: true,
8723                zone: Some("cell-3".into()),
8724                time_hm: None,
8725            })
8726            .unwrap();
8727        assert_eq!(collector.digest(), vector["expected_motion_digest"]);
8728    }
8729
8730    #[test]
8731    fn heartbeat_build_verify_and_liveness() {
8732        let seed = [21u8; 32];
8733        let kp = Ed25519KeyPair::from_seed(&seed);
8734        let did = "did:web:robot.example.com";
8735        let digest = json!({
8736            "samples": 2, "maxForceN": 20.0, "maxSpeedMps": 0.4,
8737            "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 0,
8738            "withinEnvelope": true
8739        });
8740        let hb = build_robot_heartbeat(
8741            &seed,
8742            &BuildRobotHeartbeat {
8743                robot_did: did.into(),
8744                session_id: "urn:uuid:sess-1".into(),
8745                interval_index: 0,
8746                interval_seconds: 60,
8747                motion_digest: digest,
8748                valid_from: "2026-01-01T00:00:00Z".into(),
8749            },
8750        )
8751        .unwrap();
8752
8753        let subject = verify_robot_heartbeat(&hb, kd(&hb, &kp.public_key()), TNOW)
8754            .unwrap()
8755            .expect("heartbeat verifies");
8756        assert_eq!(subject["sessionId"], json!("urn:uuid:sess-1"));
8757
8758        // Fresh and in-envelope: live. Stale: not live.
8759        assert!(is_live(&hb, "2026-01-01T00:01:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
8760        assert!(!is_live(&hb, "2026-01-01T01:00:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
8761
8762        // Out-of-envelope heartbeat is never live, even when fresh.
8763        let breached = json!({
8764            "samples": 1, "maxForceN": 99.0, "maxSpeedMps": 0.4,
8765            "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 1,
8766            "withinEnvelope": false
8767        });
8768        let hb2 = build_robot_heartbeat(
8769            &seed,
8770            &BuildRobotHeartbeat {
8771                robot_did: did.into(),
8772                session_id: "s".into(),
8773                interval_index: 1,
8774                interval_seconds: 60,
8775                motion_digest: breached,
8776                valid_from: "2026-01-01T00:00:00Z".into(),
8777            },
8778        )
8779        .unwrap();
8780        assert!(!is_live(&hb2, "2026-01-01T00:00:30Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
8781
8782        // Tamper and wrong type rejected.
8783        let mut tampered = hb.clone();
8784        tampered["credentialSubject"]["sessionId"] = json!("urn:uuid:other");
8785        assert!(
8786            verify_robot_heartbeat(&tampered, kd(&tampered, &kp.public_key()), TNOW)
8787                .unwrap()
8788                .is_none()
8789        );
8790    }
8791
8792    // Cross-language interop: Rust reproduces the exact hash-linked ledger and
8793    // the summary Python pinned from the same fixed events and timestamps.
8794    #[test]
8795    fn safety_log_matches_interop_vector() {
8796        let vector = load_vector();
8797        let mut log = SafetyEventLog::new(None);
8798        log.append(
8799            "near_miss",
8800            "low",
8801            Some(&json!({"zone": "cell-3"})),
8802            None,
8803            "2026-01-01T00:00:00Z",
8804        )
8805        .unwrap();
8806        log.append(
8807            "envelope_breach",
8808            "high",
8809            None,
8810            None,
8811            "2026-01-01T00:01:00Z",
8812        )
8813        .unwrap();
8814
8815        assert_eq!(
8816            Value::Array(log.entries().to_vec()),
8817            vector["safety_log_entries"]
8818        );
8819        assert_eq!(
8820            log.head(),
8821            vector["expected_safety_log_head"].as_str().unwrap()
8822        );
8823        assert_eq!(log.summarize(), vector["expected_safety_summary"]);
8824        assert!(verify_safety_log(log.entries(), None).ok);
8825    }
8826
8827    #[test]
8828    fn safety_record_build_verify_and_tamper() {
8829        let seed = [22u8; 32];
8830        let kp = Ed25519KeyPair::from_seed(&seed);
8831        let mut log = SafetyEventLog::new(None);
8832        log.append("near_miss", "low", None, None, "2026-01-01T00:00:00Z")
8833            .unwrap();
8834        let summary = log.summarize();
8835
8836        let record = build_safety_record(
8837            &seed,
8838            &BuildSafetyRecord {
8839                issuer_did: "did:web:owner.example.com".into(),
8840                robot_did: "did:web:robot.example.com".into(),
8841                summary,
8842                period_start: Some("2026-01-01T00:00:00Z".into()),
8843                period_end: Some("2026-01-31T00:00:00Z".into()),
8844                valid_from: "2026-02-01T00:00:00Z".into(),
8845                valid_until: None,
8846            },
8847        )
8848        .unwrap();
8849
8850        // A summary alone is the issuer's own count: refused unless the
8851        // verifier names the issuer as trusted (or recounts the ledger).
8852        assert!(verify_safety_record(
8853            &record,
8854            kd(&record, &kp.public_key()),
8855            SafetyRecordCheck::default(),
8856            "2026-03-01T00:00:00Z",
8857        )
8858        .unwrap()
8859        .is_none());
8860        let trusted: HashSet<String> = ["did:web:owner.example.com".to_string()]
8861            .into_iter()
8862            .collect();
8863        let subject = verify_safety_record(
8864            &record,
8865            kd(&record, &kp.public_key()),
8866            SafetyRecordCheck {
8867                trusted_issuers: Some(&trusted),
8868                ..Default::default()
8869            },
8870            "2026-03-01T00:00:00Z",
8871        )
8872        .unwrap()
8873        .expect("safety record verifies");
8874        assert_eq!(subject["totalEvents"], json!(1));
8875        assert_eq!(subject["period"]["start"], json!("2026-01-01T00:00:00Z"));
8876
8877        let mut tampered = record.clone();
8878        tampered["credentialSubject"]["totalEvents"] = json!(99);
8879        assert!(verify_safety_record(
8880            &tampered,
8881            kd(&tampered, &kp.public_key()),
8882            SafetyRecordCheck::default(),
8883            "2026-03-01T00:00:00Z"
8884        )
8885        .unwrap()
8886        .is_none());
8887
8888        // Tamper detection in the ledger itself.
8889        let mut entries = log.entries().to_vec();
8890        entries[0]["severity"] = json!("critical");
8891        assert!(!verify_safety_log(&entries, None).ok);
8892    }
8893
8894    // Cross-language interop: Rust reproduces the exact credentialStatus entry.
8895    #[test]
8896    fn status_entry_matches_interop_vector() {
8897        let vector = load_vector();
8898        let entry = build_status_list_entry(
8899            "https://fleet.example.com/status/1",
8900            42,
8901            STATUS_PURPOSE_REVOCATION,
8902            None,
8903        )
8904        .unwrap();
8905        assert_eq!(entry, vector["expected_credential_status_entry"]);
8906    }
8907
8908    #[test]
8909    #[cfg_attr(not(feature = "std"), ignore = "needs gunzip (std)")]
8910    fn attach_and_check_credential_status() {
8911        let seed = [23u8; 32];
8912        let kp = Ed25519KeyPair::from_seed(&seed);
8913        let did = "did:web:robot.example.com";
8914
8915        // Mint a passport, then attach a revocation status and re-sign.
8916        let pass = build_passport(
8917            &seed,
8918            &BuildPassport {
8919                issuer_did: did.into(),
8920                robot_did: did.into(),
8921                make: "Acme".into(),
8922                model: "AR-7".into(),
8923                owner: "did:web:owner.example.com".into(),
8924                authorized_actions: vec!["lift".into()],
8925                certification: None,
8926                status: None,
8927                valid_from: "2026-01-01T00:00:00Z".into(),
8928                valid_until: None,
8929            },
8930        )
8931        .unwrap();
8932
8933        let with_status = attach_credential_status(
8934            &pass,
8935            &seed,
8936            &AttachCredentialStatus {
8937                status_list_credential: "https://fleet.example.com/status/1".into(),
8938                status_list_index: 42,
8939                status_purpose: STATUS_PURPOSE_REVOCATION.into(),
8940                entry_id: None,
8941                created: "2026-01-01T00:00:00Z".into(),
8942            },
8943        )
8944        .unwrap();
8945
8946        // The re-signed credential still verifies and now carries the entry.
8947        assert!(data_integrity::verify_proof(&with_status, &kp.public_key()).unwrap());
8948        assert_eq!(
8949            with_status["credentialStatus"]["statusListIndex"],
8950            json!("42")
8951        );
8952
8953        // Build a status list with bit 42 set, then check the entry resolves.
8954        let mut bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
8955        crate::status_list::set_status(&mut bits, 42, true).unwrap();
8956        let encoded = crate::status_list::encode_bitstring(&bits).unwrap();
8957        let status_list = json!({
8958            "id": "https://fleet.example.com/status/1",
8959            "issuer": did,
8960            "type": ["VerifiableCredential", "BitstringStatusListCredential"],
8961            "credentialSubject": {
8962                "type": "BitstringStatusList",
8963                "statusPurpose": "revocation",
8964                "encodedList": encoded,
8965            }
8966        });
8967        assert!(
8968            check_credential_status(&with_status, &status_list, STATUS_PURPOSE_REVOCATION).unwrap()
8969        );
8970
8971        // A credential with no status entry is not revoked.
8972        assert!(!check_credential_status(&pass, &status_list, STATUS_PURPOSE_REVOCATION).unwrap());
8973
8974        // A list with the bit clear reports not-revoked.
8975        let clear_bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
8976        let clear_encoded = crate::status_list::encode_bitstring(&clear_bits).unwrap();
8977        let mut clear_list = status_list.clone();
8978        clear_list["credentialSubject"]["encodedList"] = json!(clear_encoded);
8979        assert!(
8980            !check_credential_status(&with_status, &clear_list, STATUS_PURPOSE_REVOCATION).unwrap()
8981        );
8982
8983        // A list from another issuer, or a list the entry does not name, cannot
8984        // answer: an error, never "not revoked".
8985        let mut foreign = status_list.clone();
8986        foreign["issuer"] = json!("did:web:someone-else.example.com");
8987        assert!(
8988            check_credential_status(&with_status, &foreign, STATUS_PURPOSE_REVOCATION).is_err()
8989        );
8990        let mut other = status_list.clone();
8991        other["id"] = json!("https://fleet.example.com/status/2");
8992        assert!(check_credential_status(&with_status, &other, STATUS_PURPOSE_REVOCATION).is_err());
8993    }
8994
8995    // Cross-language interop: Rust reproduces the exact frame hash Python pinned.
8996    #[test]
8997    fn frame_hash_matches_interop_vector() {
8998        let vector = load_vector();
8999        let sample_frame: Vec<u8> = (0u8..64).collect();
9000        let got = hash_frame(&sample_frame);
9001        assert_eq!(got, vector["expected_frame_hash"].as_str().unwrap());
9002        assert_eq!(got, "u_eq5rPNxA2K9JljNyaKej5x1f8-YEWA6jER80dkVEQg");
9003    }
9004
9005    // Cross-language interop: Rust reproduces the exact hash-linked perception log
9006    // Python pinned from the same fixed frames and timestamps.
9007    #[test]
9008    fn perception_log_matches_interop_vector() {
9009        let vector = load_vector();
9010        let sample_frame: Vec<u8> = (0u8..64).collect();
9011        let mut log = PerceptionLog::new(None);
9012        log.record(
9013            "cam-front",
9014            "camera",
9015            Some(&sample_frame),
9016            None,
9017            "2026-01-01T00:00:00Z",
9018        )
9019        .unwrap();
9020        log.record(
9021            "lidar-top",
9022            "lidar",
9023            None,
9024            Some(&hash_frame(b"scan-0")),
9025            "2026-01-01T00:00:01Z",
9026        )
9027        .unwrap();
9028
9029        assert_eq!(
9030            Value::Array(log.entries().to_vec()),
9031            vector["perception_log_entries"]
9032        );
9033        assert_eq!(
9034            log.head(),
9035            vector["expected_perception_log_head"].as_str().unwrap()
9036        );
9037        assert!(verify_perception_log(log.entries(), None).ok);
9038    }
9039
9040    #[test]
9041    fn perception_record_validation_and_tamper() {
9042        let mut log = PerceptionLog::new(None);
9043        // Unknown modality rejected.
9044        assert!(log
9045            .record("cam", "sonar", Some(b"x"), None, "2026-01-01T00:00:00Z")
9046            .is_err());
9047        // Both frame and frame_hash rejected.
9048        assert!(log
9049            .record(
9050                "cam",
9051                "camera",
9052                Some(b"x"),
9053                Some("uABC"),
9054                "2026-01-01T00:00:00Z"
9055            )
9056            .is_err());
9057        // Neither frame nor frame_hash rejected.
9058        assert!(log
9059            .record("cam", "camera", None, None, "2026-01-01T00:00:00Z")
9060            .is_err());
9061        // Empty sensor id rejected.
9062        assert!(log
9063            .record("", "camera", Some(b"x"), None, "2026-01-01T00:00:00Z")
9064            .is_err());
9065
9066        log.record(
9067            "cam",
9068            "camera",
9069            Some(b"frame-0"),
9070            None,
9071            "2026-01-01T00:00:00Z",
9072        )
9073        .unwrap();
9074        log.record(
9075            "cam",
9076            "camera",
9077            Some(b"frame-1"),
9078            None,
9079            "2026-01-01T00:00:01Z",
9080        )
9081        .unwrap();
9082        assert!(verify_perception_log(log.entries(), None).ok);
9083
9084        // Tamper detection in the chain.
9085        let mut entries = log.entries().to_vec();
9086        entries[0]["frameHash"] = json!("uTAMPERED");
9087        assert!(!verify_perception_log(&entries, None).ok);
9088    }
9089
9090    #[test]
9091    fn perception_attestation_build_verify_and_tamper() {
9092        let seed = [24u8; 32];
9093        let kp = Ed25519KeyPair::from_seed(&seed);
9094        let did = "did:web:robot.example.com";
9095        let frame = b"sensor-frame-bytes";
9096        let frame_hash = hash_frame(frame);
9097
9098        let cred = build_perception_attestation(
9099            &seed,
9100            &BuildPerception {
9101                robot_did: did.into(),
9102                sensor_id: "cam-front".into(),
9103                modality: "camera".into(),
9104                frame_hash: frame_hash.clone(),
9105                captured_at: Some("2026-01-01T00:00:00Z".into()),
9106                log_head: Some("uHEAD".into()),
9107                log_count: None,
9108                valid_from: "2026-01-01T00:00:00Z".into(),
9109                valid_until: None,
9110            },
9111        )
9112        .unwrap();
9113
9114        // Verify the proof and the embedded provenance, and recompute the frame.
9115        let subject =
9116            verify_perception_attestation(&cred, kd(&cred, &kp.public_key()), Some(frame), TNOW)
9117                .unwrap()
9118                .expect("perception attestation verifies");
9119        assert_eq!(subject["sensorId"], json!("cam-front"));
9120        assert_eq!(subject["frameHash"], json!(frame_hash));
9121        assert_eq!(subject["logHead"], json!("uHEAD"));
9122
9123        // Verify without the raw frame still passes (proof only).
9124        assert!(
9125            verify_perception_attestation(&cred, kd(&cred, &kp.public_key()), None, TNOW)
9126                .unwrap()
9127                .is_some()
9128        );
9129
9130        // A different frame than the one attested is rejected.
9131        assert!(verify_perception_attestation(
9132            &cred,
9133            kd(&cred, &kp.public_key()),
9134            Some(b"other-frame"),
9135            TNOW
9136        )
9137        .unwrap()
9138        .is_none());
9139
9140        // Tampered subject fails the proof.
9141        let mut tampered = cred.clone();
9142        tampered["credentialSubject"]["sensorId"] = json!("cam-rear");
9143        assert!(verify_perception_attestation(
9144            &tampered,
9145            kd(&tampered, &kp.public_key()),
9146            None,
9147            TNOW
9148        )
9149        .unwrap()
9150        .is_none());
9151
9152        // Wrong type rejected.
9153        let mut wrong = cred.clone();
9154        wrong["type"] = json!(["VerifiableCredential"]);
9155        assert!(
9156            verify_perception_attestation(&wrong, kd(&wrong, &kp.public_key()), None, TNOW)
9157                .unwrap()
9158                .is_none()
9159        );
9160
9161        // Bad modality and missing frame_hash rejected at build time.
9162        assert!(build_perception_attestation(
9163            &seed,
9164            &BuildPerception {
9165                robot_did: did.into(),
9166                sensor_id: "s".into(),
9167                modality: "sonar".into(),
9168                frame_hash: frame_hash.clone(),
9169                captured_at: None,
9170                log_head: None,
9171                log_count: None,
9172                valid_from: "2026-01-01T00:00:00Z".into(),
9173                valid_until: None,
9174            },
9175        )
9176        .is_err());
9177        assert!(build_perception_attestation(
9178            &seed,
9179            &BuildPerception {
9180                robot_did: did.into(),
9181                sensor_id: "s".into(),
9182                modality: "camera".into(),
9183                frame_hash: String::new(),
9184                captured_at: None,
9185                log_head: None,
9186                log_count: None,
9187                valid_from: "2026-01-01T00:00:00Z".into(),
9188                valid_until: None,
9189            },
9190        )
9191        .is_err());
9192    }
9193
9194    fn jwk_pub(jwk: &Value) -> Vec<u8> {
9195        URL_SAFE_NO_PAD
9196            .decode(jwk["x"].as_str().unwrap())
9197            .expect("base64url JWK x")
9198    }
9199
9200    // Cross-language interop: Go and TypeScript verify this same Python-signed
9201    // delegation lease; the Rust core must too.
9202    #[test]
9203    fn verifies_python_lease_interop_vector() {
9204        let vector = load_vector();
9205        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
9206        let lease = vector["delegation_lease_credential"].clone();
9207
9208        let subject = verify_delegation_lease(
9209            &lease,
9210            kd(&lease, &robot_pub),
9211            "did:web:robot.example.com",
9212            None,
9213            None,
9214            "2026-06-01T00:00:00Z",
9215        )
9216        .unwrap()
9217        .expect("the Python lease interop vector must verify in Rust");
9218        assert_eq!(subject["leaseId"], json!("lease-vector-1"));
9219    }
9220
9221    // Cross-language interop: Rust authorizes the Python-signed quorum with the
9222    // same two approver keys and a threshold of 2.
9223    #[test]
9224    fn verifies_python_quorum_interop_vector() {
9225        let vector = load_vector();
9226        let approvals = vector["quorum_approvals"].as_array().unwrap().clone();
9227        let action_id = vector["quorum_action_id"].as_str().unwrap();
9228        let keys: Vec<ApproverKey> = vector["quorum_approver_keys"]
9229            .as_object()
9230            .unwrap()
9231            .iter()
9232            .map(|(did, jwk)| ApproverKey {
9233                did: did.clone(),
9234                public_key: jwk_pub(jwk),
9235            })
9236            .collect();
9237
9238        let (ok, approvers) = verify_action_authorization(
9239            &approvals,
9240            action_id,
9241            "did:web:robot.example.com",
9242            &keys,
9243            2,
9244            None,
9245            vector["quorum_now"].as_str().unwrap(),
9246        )
9247        .unwrap();
9248        assert!(
9249            ok,
9250            "the Python quorum interop vector must authorize in Rust"
9251        );
9252        assert_eq!(approvers.len(), 2);
9253        assert_eq!(approvers[0], "did:web:approver-1.example.com");
9254        assert_eq!(approvers[1], "did:web:approver-2.example.com");
9255    }
9256
9257    #[test]
9258    fn lease_build_verify_permits_and_expiry() {
9259        let seed = [31u8; 32];
9260        let kp = Ed25519KeyPair::from_seed(&seed);
9261        let did = "did:web:robot.example.com";
9262        let scope = json!({
9263            "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
9264            "allowedZones": ["warehouse-a", "dock-3"]
9265        });
9266        let lease = build_delegation_lease(
9267            &seed,
9268            &BuildDelegationLease {
9269                issuer_did: did.into(),
9270                robot_did: did.into(),
9271                lease_id: "lease-1".into(),
9272                scope: scope.clone(),
9273                parent_lease_id: None,
9274                valid_from: "2026-01-01T00:00:00Z".into(),
9275                valid_until: "2026-01-01T01:00:00Z".into(),
9276            },
9277        )
9278        .unwrap();
9279
9280        // Round-trip verify, in-window.
9281        let subject = verify_delegation_lease(
9282            &lease,
9283            kd(&lease, &kp.public_key()),
9284            "did:web:robot.example.com",
9285            None,
9286            None,
9287            "2026-01-01T00:30:00Z",
9288        )
9289        .unwrap()
9290        .expect("lease verifies in window");
9291        assert_eq!(subject["leaseId"], json!("lease-1"));
9292
9293        // Permits a within-scope action, denies an out-of-scope one.
9294        assert!(lease_permits(
9295            &subject,
9296            &PhysicalAction {
9297                force_n: Some(50.0),
9298                zone: Some("warehouse-a".into()),
9299                ..Default::default()
9300            },
9301            Some(&lease),
9302            kd(&lease, &kp.public_key()),
9303            None,
9304            "2026-01-01T00:30:00Z",
9305        )
9306        .unwrap());
9307        assert!(!lease_permits(
9308            &subject,
9309            &PhysicalAction {
9310                force_n: Some(120.0),
9311                ..Default::default()
9312            },
9313            Some(&lease),
9314            kd(&lease, &kp.public_key()),
9315            None,
9316            "2026-01-01T00:30:00Z",
9317        )
9318        .unwrap());
9319
9320        // Expired window: verify fails and the lease no longer permits.
9321        assert!(verify_delegation_lease(
9322            &lease,
9323            kd(&lease, &kp.public_key()),
9324            "did:web:robot.example.com",
9325            None,
9326            None,
9327            "2026-01-01T02:00:00Z"
9328        )
9329        .unwrap()
9330        .is_none());
9331        assert!(!lease_permits(
9332            &subject,
9333            &PhysicalAction {
9334                force_n: Some(50.0),
9335                ..Default::default()
9336            },
9337            Some(&lease),
9338            kd(&lease, &kp.public_key()),
9339            None,
9340            "2026-01-01T02:00:00Z",
9341        )
9342        .unwrap());
9343
9344        // Tamper and wrong type rejected.
9345        let mut tampered = lease.clone();
9346        tampered["credentialSubject"]["leaseId"] = json!("lease-other");
9347        assert!(verify_delegation_lease(
9348            &tampered,
9349            kd(&tampered, &kp.public_key()),
9350            "did:web:robot.example.com",
9351            None,
9352            None,
9353            "2026-01-01T00:30:00Z"
9354        )
9355        .unwrap()
9356        .is_none());
9357    }
9358
9359    #[test]
9360    fn lease_sub_grant_attenuation() {
9361        let parent_seed = [32u8; 32];
9362        let child_seed = [33u8; 32];
9363        let parent_kp = Ed25519KeyPair::from_seed(&parent_seed);
9364        let child_kp = Ed25519KeyPair::from_seed(&child_seed);
9365        let parent_scope = json!({
9366            "maxForceN": 80.0, "maxSpeedMps": 2.0,
9367            "allowedZones": ["warehouse-a", "dock-3"]
9368        });
9369
9370        // A narrower sub-lease attenuates the parent: accepted.
9371        let narrower = build_delegation_lease(
9372            &child_seed,
9373            &BuildDelegationLease {
9374                issuer_did: "did:web:integrator.example.com".into(),
9375                robot_did: "did:web:robot.example.com".into(),
9376                lease_id: "lease-2".into(),
9377                scope: json!({
9378                    "maxForceN": 50.0, "maxSpeedMps": 1.0,
9379                    "allowedZones": ["warehouse-a"]
9380                }),
9381                parent_lease_id: Some("lease-1".into()),
9382                valid_from: "2026-01-01T00:00:00Z".into(),
9383                valid_until: "2026-01-01T01:00:00Z".into(),
9384            },
9385        )
9386        .unwrap();
9387        assert!(verify_delegation_lease(
9388            &narrower,
9389            kd(&narrower, &child_kp.public_key()),
9390            "did:web:robot.example.com",
9391            Some(&parent_scope),
9392            None,
9393            "2026-01-01T00:30:00Z"
9394        )
9395        .unwrap()
9396        .is_some());
9397
9398        // A widening sub-lease (force above the parent) is rejected against the
9399        // parent scope.
9400        let wider = build_delegation_lease(
9401            &parent_seed,
9402            &BuildDelegationLease {
9403                issuer_did: "did:web:integrator.example.com".into(),
9404                robot_did: "did:web:robot.example.com".into(),
9405                lease_id: "lease-3".into(),
9406                scope: json!({
9407                    "maxForceN": 200.0, "maxSpeedMps": 1.0,
9408                    "allowedZones": ["warehouse-a"]
9409                }),
9410                parent_lease_id: Some("lease-1".into()),
9411                valid_from: "2026-01-01T00:00:00Z".into(),
9412                valid_until: "2026-01-01T01:00:00Z".into(),
9413            },
9414        )
9415        .unwrap();
9416        assert!(verify_delegation_lease(
9417            &wider,
9418            kd(&wider, &parent_kp.public_key()),
9419            "did:web:robot.example.com",
9420            Some(&parent_scope),
9421            None,
9422            "2026-01-01T00:30:00Z"
9423        )
9424        .unwrap()
9425        .is_none());
9426    }
9427
9428    #[test]
9429    fn quorum_threshold_and_distinct_counting() {
9430        let s1 = [41u8; 32];
9431        let s2 = [42u8; 32];
9432        let k1 = Ed25519KeyPair::from_seed(&s1);
9433        let k2 = Ed25519KeyPair::from_seed(&s2);
9434        let a1 = "did:web:approver-1.example.com";
9435        let a2 = "did:web:approver-2.example.com";
9436        let robot = "did:web:robot.example.com";
9437        let action = "action-x";
9438
9439        let build = |seed: &[u8], did: &str, decision: &str| {
9440            build_action_approval(
9441                seed,
9442                &BuildActionApproval {
9443                    approver_did: did.into(),
9444                    action_id: action.into(),
9445                    robot_did: robot.into(),
9446                    decision: decision.into(),
9447                    valid_from: "2026-01-01T00:00:00Z".into(),
9448                    valid_until: None,
9449                },
9450            )
9451            .unwrap()
9452        };
9453
9454        let ap1 = build(&s1, a1, APPROVE);
9455        let ap2 = build(&s2, a2, APPROVE);
9456        let keys = vec![
9457            ApproverKey {
9458                did: a1.into(),
9459                public_key: k1.public_key().to_vec(),
9460            },
9461            ApproverKey {
9462                did: a2.into(),
9463                public_key: k2.public_key().to_vec(),
9464            },
9465        ];
9466
9467        // Two distinct approvers meet a threshold of 2.
9468        let (ok, approvers) = verify_action_authorization(
9469            &[ap1.clone(), ap2],
9470            action,
9471            robot,
9472            &keys,
9473            2,
9474            None,
9475            "2026-01-01T00:01:00Z",
9476        )
9477        .unwrap();
9478        assert!(ok);
9479        assert_eq!(approvers, vec![a1.to_string(), a2.to_string()]);
9480
9481        // Duplicate approvals from one approver count once: threshold 2 not met.
9482        let dup = build(&s1, a1, APPROVE);
9483        let (ok2, approvers2) = verify_action_authorization(
9484            &[ap1.clone(), dup],
9485            action,
9486            robot,
9487            &keys,
9488            2,
9489            None,
9490            "2026-01-01T00:01:00Z",
9491        )
9492        .unwrap();
9493        assert!(!ok2);
9494        assert_eq!(approvers2, vec![a1.to_string()]);
9495
9496        // A single valid approver does not meet a threshold of 2.
9497        let (ok3, _) = verify_action_authorization(
9498            &[ap1],
9499            action,
9500            robot,
9501            &keys,
9502            2,
9503            None,
9504            "2026-01-01T00:01:00Z",
9505        )
9506        .unwrap();
9507        assert!(!ok3);
9508
9509        // A rejection vetoes the action (each approver's latest decision counts).
9510        let rej = build(&s1, a1, REJECT);
9511        let approve2 = build(&s2, a2, APPROVE);
9512        let (ok4, approvers4) = verify_action_authorization(
9513            &[rej, approve2],
9514            action,
9515            robot,
9516            &keys,
9517            2,
9518            None,
9519            "2026-01-01T00:01:00Z",
9520        )
9521        .unwrap();
9522        assert!(!ok4);
9523        assert!(approvers4.is_empty());
9524    }
9525
9526    // Cross-language interop: Rust verifies the Python-signed ownership transfer
9527    // under the owner's key from the vector.
9528    #[test]
9529    fn verifies_python_ownership_transfer_interop_vector() {
9530        let vector = load_vector();
9531        let owner_pub = jwk_pub(&vector["ownership_transfer_owner_key"]);
9532        let cred = vector["ownership_transfer_credential"].clone();
9533
9534        let subject = verify_ownership_transfer(&cred, kd(&cred, &owner_pub), None, TNOW)
9535            .unwrap()
9536            .expect("the Python ownership-transfer interop vector must verify in Rust");
9537        assert_eq!(subject["toOwner"], json!("did:web:owner-b.example.com"));
9538    }
9539
9540    // Cross-language interop: Rust verifies the Python-signed key rotation under
9541    // the robot key from robot_public_key_jwk.
9542    #[test]
9543    fn verifies_python_key_rotation_interop_vector() {
9544        let vector = load_vector();
9545        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
9546        let cred = vector["key_rotation_credential"].clone();
9547
9548        let subject = verify_key_rotation(&cred, Keys::Bare(&robot_pub), None, TNOW)
9549            .unwrap()
9550            .expect("the Python key-rotation interop vector must verify in Rust");
9551        assert_eq!(
9552            subject["newKey"],
9553            json!("z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
9554        );
9555    }
9556
9557    // Cross-language interop: Rust verifies the Python-signed decommission under
9558    // the authority key from the vector.
9559    #[test]
9560    fn verifies_python_decommission_interop_vector() {
9561        let vector = load_vector();
9562        let authority_pub = jwk_pub(&vector["decommission_authority_key"]);
9563        let cred = vector["decommission_credential"].clone();
9564
9565        let subject = verify_decommission(&cred, kd(&cred, &authority_pub), None, None, TNOW)
9566            .unwrap()
9567            .expect("the Python decommission interop vector must verify in Rust");
9568        assert_eq!(subject["reason"], json!("end of service life"));
9569        assert_eq!(subject["finalDisposition"], json!("recycled"));
9570    }
9571
9572    #[test]
9573    fn ownership_transfer_roundtrip_and_issuer_rule() {
9574        let owner_a_seed = [51u8; 32];
9575        let owner_b_seed = [52u8; 32];
9576        let a = Ed25519KeyPair::from_seed(&owner_a_seed);
9577        let b = Ed25519KeyPair::from_seed(&owner_b_seed);
9578        let owner_a = "did:web:owner-a.example.com";
9579        let owner_b = "did:web:owner-b.example.com";
9580        let robot = "did:web:robot.example.com";
9581
9582        let transfer = build_ownership_transfer(
9583            &owner_a_seed,
9584            &BuildOwnershipTransfer {
9585                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000101".into(),
9586                issuer_did: owner_a.into(),
9587                robot_did: robot.into(),
9588                to_owner: owner_b.into(),
9589                from_owner: None,
9590                prev_transfer_id: None,
9591                valid_from: "2026-01-01T00:00:00Z".into(),
9592            },
9593        )
9594        .unwrap();
9595
9596        let subject =
9597            verify_ownership_transfer(&transfer, kd(&transfer, &a.public_key()), None, TNOW)
9598                .unwrap()
9599                .expect("transfer verifies under the current owner key");
9600        assert_eq!(subject["fromOwner"], json!(owner_a));
9601        assert_eq!(subject["toOwner"], json!(owner_b));
9602
9603        // Wrong type rejected.
9604        let mut wrong = transfer.clone();
9605        wrong["type"] = json!(["VerifiableCredential"]);
9606        assert!(
9607            verify_ownership_transfer(&wrong, kd(&wrong, &a.public_key()), None, TNOW)
9608                .unwrap()
9609                .is_none()
9610        );
9611
9612        // The issuer must equal fromOwner: forge a transfer whose issuer is not the
9613        // declared seller and re-sign it. It must be rejected even with a valid
9614        // proof under the signing key.
9615        let forged = build_ownership_transfer(
9616            &owner_b_seed,
9617            &BuildOwnershipTransfer {
9618                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000102".into(),
9619                issuer_did: owner_b.into(),
9620                robot_did: robot.into(),
9621                to_owner: "did:web:owner-c.example.com".into(),
9622                // Claim the robot was sold by owner A while owner B signs.
9623                from_owner: Some(owner_a.into()),
9624                prev_transfer_id: None,
9625                valid_from: "2026-01-01T00:00:00Z".into(),
9626            },
9627        )
9628        .unwrap();
9629        assert!(
9630            verify_ownership_transfer(&forged, kd(&forged, &b.public_key()), None, TNOW)
9631                .unwrap()
9632                .is_none()
9633        );
9634    }
9635
9636    /// The links of a custody chain, checked without a head.
9637    fn links_only(
9638        transfers: &[Value],
9639        keys: &[OwnerKey],
9640        robot: &str,
9641        origin: Option<&str>,
9642        now: &str,
9643    ) -> Result<(bool, Option<String>)> {
9644        let check = CustodyCheck {
9645            history_only: true,
9646            ..Default::default()
9647        };
9648        let r = verify_custody_chain(transfers, keys, robot, origin, now, &check)?;
9649        assert!(
9650            r.current_owner.is_none(),
9651            "history alone never names a current owner"
9652        );
9653        Ok((r.ok, r.last_owner))
9654    }
9655
9656    #[test]
9657    fn custody_chain_links_and_rejects() {
9658        let owner_a_seed = [51u8; 32];
9659        let owner_b_seed = [52u8; 32];
9660        let owner_c_seed = [53u8; 32];
9661        let a = Ed25519KeyPair::from_seed(&owner_a_seed);
9662        let b = Ed25519KeyPair::from_seed(&owner_b_seed);
9663        let c = Ed25519KeyPair::from_seed(&owner_c_seed);
9664        let owner_a = "did:web:owner-a.example.com";
9665        let owner_b = "did:web:owner-b.example.com";
9666        let owner_c = "did:web:owner-c.example.com";
9667        let robot = "did:web:robot.example.com";
9668
9669        let t1 = build_ownership_transfer(
9670            &owner_a_seed,
9671            &BuildOwnershipTransfer {
9672                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000103".into(),
9673                issuer_did: owner_a.into(),
9674                robot_did: robot.into(),
9675                to_owner: owner_b.into(),
9676                from_owner: None,
9677                prev_transfer_id: None,
9678                valid_from: "2026-01-01T00:00:00Z".into(),
9679            },
9680        )
9681        .unwrap();
9682        let t2 = build_ownership_transfer(
9683            &owner_b_seed,
9684            &BuildOwnershipTransfer {
9685                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000104".into(),
9686                issuer_did: owner_b.into(),
9687                robot_did: robot.into(),
9688                to_owner: owner_c.into(),
9689                from_owner: None,
9690                prev_transfer_id: Some("urn:uuid:00000000-0000-4000-8000-000000000103".into()),
9691                valid_from: "2026-02-01T00:00:00Z".into(),
9692            },
9693        )
9694        .unwrap();
9695
9696        let keys = vec![
9697            OwnerKey {
9698                did: owner_a.into(),
9699                public_key: a.public_key().to_vec(),
9700            },
9701            OwnerKey {
9702                did: owner_b.into(),
9703                public_key: b.public_key().to_vec(),
9704            },
9705            OwnerKey {
9706                did: owner_c.into(),
9707                public_key: c.public_key().to_vec(),
9708            },
9709        ];
9710
9711        // A clean two-link chain rooted at owner A ends at owner C.
9712        let (ok, current) = links_only(
9713            &[t1.clone(), t2.clone()],
9714            &keys,
9715            "did:web:robot.example.com",
9716            Some(owner_a),
9717            "2026-03-01T00:00:00Z",
9718        )
9719        .unwrap();
9720        assert!(ok);
9721        assert_eq!(current.as_deref(), Some(owner_c));
9722
9723        // A wrong declared origin breaks the first link.
9724        let (bad_origin, _) = links_only(
9725            &[t1.clone(), t2.clone()],
9726            &keys,
9727            "did:web:robot.example.com",
9728            Some(owner_c),
9729            "2026-03-01T00:00:00Z",
9730        )
9731        .unwrap();
9732        assert!(!bad_origin);
9733
9734        // A gap (link two without link one) breaks the toOwner -> fromOwner join.
9735        let (gap, _) = links_only(
9736            core::slice::from_ref(&t2),
9737            &keys,
9738            "did:web:robot.example.com",
9739            Some(owner_a),
9740            "2026-03-01T00:00:00Z",
9741        )
9742        .unwrap();
9743        assert!(!gap);
9744
9745        // A missing key for an issuer fails the chain.
9746        let partial = vec![OwnerKey {
9747            did: owner_a.into(),
9748            public_key: a.public_key().to_vec(),
9749        }];
9750        let (no_key, _) = links_only(
9751            &[t1, t2],
9752            &partial,
9753            "did:web:robot.example.com",
9754            Some(owner_a),
9755            "2026-03-01T00:00:00Z",
9756        )
9757        .unwrap();
9758        assert!(!no_key);
9759    }
9760
9761    #[test]
9762    fn key_rotation_roundtrip_and_history() {
9763        let k1_seed = [61u8; 32];
9764        let k2_seed = [62u8; 32];
9765        let k3_seed = [63u8; 32];
9766        let k1 = Ed25519KeyPair::from_seed(&k1_seed);
9767        let k2 = Ed25519KeyPair::from_seed(&k2_seed);
9768        let k3 = Ed25519KeyPair::from_seed(&k3_seed);
9769        let robot = "did:web:robot.example.com";
9770
9771        // Rotate k1 -> k2, signed by k1.
9772        let r1 = build_key_rotation(
9773            &k1_seed,
9774            &BuildKeyRotation {
9775                robot_did: robot.into(),
9776                new_key_multibase: k2.public_multikey(),
9777                reason: Some("scheduled rotation".into()),
9778                valid_from: "2026-01-01T00:00:00Z".into(),
9779            },
9780        )
9781        .unwrap();
9782
9783        let subject = verify_key_rotation(&r1, Keys::Bare(&k1.public_key()), None, TNOW)
9784            .unwrap()
9785            .expect("rotation verifies under the old key");
9786        assert_eq!(subject["previousKey"], json!(k1.public_multikey()));
9787        assert_eq!(subject["newKey"], json!(k2.public_multikey()));
9788
9789        // The new key cannot verify a rotation that the old key signed.
9790        assert!(
9791            verify_key_rotation(&r1, Keys::Bare(&k2.public_key()), None, TNOW)
9792                .unwrap()
9793                .is_none()
9794        );
9795
9796        // Wrong type rejected.
9797        let mut wrong = r1.clone();
9798        wrong["type"] = json!(["VerifiableCredential"]);
9799        assert!(
9800            verify_key_rotation(&wrong, Keys::Bare(&k1.public_key()), None, TNOW)
9801                .unwrap()
9802                .is_none()
9803        );
9804
9805        // Rotate k2 -> k3, signed by k2, forming a history.
9806        let r2 = build_key_rotation(
9807            &k2_seed,
9808            &BuildKeyRotation {
9809                robot_did: robot.into(),
9810                new_key_multibase: k3.public_multikey(),
9811                reason: None,
9812                valid_from: "2026-02-01T00:00:00Z".into(),
9813            },
9814        )
9815        .unwrap();
9816
9817        let (ok, current) = verify_key_history(
9818            &[r1.clone(), r2.clone()],
9819            &k1.public_multikey(),
9820            None,
9821            "2026-03-01T00:00:00Z",
9822        )
9823        .unwrap();
9824        assert!(ok);
9825        assert_eq!(current.as_deref(), Some(k3.public_multikey().as_str()));
9826
9827        // A wrong origin key breaks the first previousKey match.
9828        let (bad_origin, _) = verify_key_history(
9829            &[r1, r2],
9830            &k3.public_multikey(),
9831            None,
9832            "2026-03-01T00:00:00Z",
9833        )
9834        .unwrap();
9835        assert!(!bad_origin);
9836    }
9837
9838    #[test]
9839    fn decommission_roundtrip_and_trusted_authority() {
9840        let seed = [71u8; 32];
9841        let kp = Ed25519KeyPair::from_seed(&seed);
9842        let authority = "did:web:authority.example.com";
9843        let robot = "did:web:robot.example.com";
9844
9845        let cred = build_decommission(
9846            &seed,
9847            &BuildDecommission {
9848                issuer_did: authority.into(),
9849                robot_did: robot.into(),
9850                reason: "end of service life".into(),
9851                final_disposition: Some("recycled".into()),
9852                valid_from: "2026-01-01T00:00:00Z".into(),
9853                valid_until: None,
9854            },
9855        )
9856        .unwrap();
9857
9858        let mut trusted = HashSet::new();
9859        trusted.insert(authority.to_string());
9860        let subject = verify_decommission(
9861            &cred,
9862            kd(&cred, &kp.public_key()),
9863            Some(&trusted),
9864            None,
9865            TNOW,
9866        )
9867        .unwrap()
9868        .expect("a trusted authority decommission verifies");
9869        assert_eq!(subject["decommissionedBy"], json!(authority));
9870
9871        // An untrusted issuer is rejected even with a valid proof.
9872        let mut other = HashSet::new();
9873        other.insert("did:web:someone-else.example.com".to_string());
9874        assert!(
9875            verify_decommission(&cred, kd(&cred, &kp.public_key()), Some(&other), None, TNOW)
9876                .unwrap()
9877                .is_none()
9878        );
9879
9880        // No trusted-authority set: a valid proof verifies.
9881        assert!(
9882            verify_decommission(&cred, kd(&cred, &kp.public_key()), None, None, TNOW)
9883                .unwrap()
9884                .is_some()
9885        );
9886
9887        // Wrong type rejected.
9888        let mut wrong = cred.clone();
9889        wrong["type"] = json!(["VerifiableCredential"]);
9890        assert!(
9891            verify_decommission(&wrong, kd(&wrong, &kp.public_key()), None, None, TNOW)
9892                .unwrap()
9893                .is_none()
9894        );
9895
9896        // reason is required at build time.
9897        assert!(build_decommission(
9898            &seed,
9899            &BuildDecommission {
9900                issuer_did: authority.into(),
9901                robot_did: robot.into(),
9902                reason: String::new(),
9903                final_disposition: None,
9904                valid_from: "2026-01-01T00:00:00Z".into(),
9905                valid_until: None,
9906            },
9907        )
9908        .is_err());
9909    }
9910
9911    // Cross-language interop: Rust reproduces the exact conformance report and
9912    // digest Python pinned, from the same credential set and profile.
9913    #[test]
9914    fn conformance_matches_interop_vector() {
9915        let vector = load_vector();
9916        let credentials: Vec<Value> = vector["conformance_credentials"]
9917            .as_array()
9918            .expect("conformance_credentials present")
9919            .clone();
9920        let profile_id = vector["conformance_profile_id"].as_str().unwrap();
9921
9922        let report = check_conformance(&credentials, profile_id).unwrap();
9923        assert_eq!(report, vector["expected_conformance_report"]);
9924
9925        let digest = report_digest(&report);
9926        assert_eq!(
9927            digest,
9928            vector["expected_conformance_report_digest"]
9929                .as_str()
9930                .unwrap()
9931        );
9932    }
9933
9934    // Presence alone is not evidence. A heartbeat that reports an envelope
9935    // breach must not satisfy the continuous-monitoring requirement just by
9936    // carrying a motionDigest.
9937    #[test]
9938    fn a_breaching_heartbeat_does_not_evidence_monitoring() {
9939        let breaching = json!({
9940            "type": ["VerifiableCredential", "RobotHeartbeatCredential"],
9941            "credentialSubject": {
9942                "motionDigest": {"withinEnvelope": false, "samples": 120}
9943            }
9944        });
9945        let report = check_conformance(core::slice::from_ref(&breaching), "iso-ts-15066").unwrap();
9946        let monitoring = report["requirements"]
9947            .as_array()
9948            .unwrap()
9949            .iter()
9950            .find(|r| r["id"] == json!("iso15066-monitoring"))
9951            .expect("monitoring requirement present");
9952        assert_eq!(monitoring["satisfied"], json!(false));
9953
9954        // The same heartbeat reporting no breach does satisfy it.
9955        let mut clean = breaching;
9956        clean["credentialSubject"]["motionDigest"]["withinEnvelope"] = json!(true);
9957        let report = check_conformance(&[clean], "iso-ts-15066").unwrap();
9958        let monitoring = report["requirements"]
9959            .as_array()
9960            .unwrap()
9961            .iter()
9962            .find(|r| r["id"] == json!("iso15066-monitoring"))
9963            .unwrap();
9964        assert_eq!(monitoring["satisfied"], json!(true));
9965    }
9966
9967    // Every requirement declares where its clause number came from, and the
9968    // report totals them, so CONFORMS never reads as more authoritative about
9969    // the regulation than its sources are.
9970    #[test]
9971    fn conformance_report_carries_citation_provenance() {
9972        for profile_id in [
9973            "iso-10218",
9974            "iso-ts-15066",
9975            "eu-machinery-2023-1230",
9976            "eu-ai-act-high-risk",
9977            "ul-3300",
9978        ] {
9979            let report = check_conformance(&[], profile_id).unwrap();
9980            let citations = report["citations"].as_object().unwrap();
9981            assert_eq!(citations.len(), CITATION_STATUSES.len());
9982            let counted: i64 = citations.values().map(|v| v.as_i64().unwrap()).sum();
9983            assert_eq!(counted, report["totalCount"].as_i64().unwrap());
9984            for result in report["requirements"].as_array().unwrap() {
9985                let citation = result["citation"].as_str().unwrap();
9986                assert!(CITATION_STATUSES.contains(&citation));
9987            }
9988        }
9989
9990        // UL 3300 is paywalled with no clause numbering available, so none of
9991        // its "clauses" are citable.
9992        let ul = check_conformance(&[], "ul-3300").unwrap();
9993        assert_eq!(ul["citations"][CITATION_DESCRIPTIVE], ul["totalCount"]);
9994        assert_eq!(ul["citations"][CITATION_VERIFIED_PRIMARY], json!(0));
9995    }
9996
9997    #[test]
9998    fn conformance_unknown_profile_and_missing_field() {
9999        assert!(check_conformance(&[], "no-such-profile").is_err());
10000
10001        // An empty credential set satisfies nothing.
10002        let empty = check_conformance(&[], "eu-ai-act-high-risk").unwrap();
10003        assert_eq!(empty["conforms"], json!(false));
10004        assert_eq!(empty["satisfiedCount"], json!(0));
10005        assert_eq!(empty["totalCount"], json!(4));
10006
10007        // A safety record with no logHead does not satisfy the record-keeping
10008        // requirement (a missing field counts as unsatisfied).
10009        let creds = vec![json!({
10010            "type": ["VerifiableCredential", "RobotSafetyRecordCredential"],
10011            "credentialSubject": { "id": "did:web:robot.example.com", "totalEvents": 2 }
10012        })];
10013        let report = check_conformance(&creds, "eu-ai-act-high-risk").unwrap();
10014        let record_keeping = report["requirements"]
10015            .as_array()
10016            .unwrap()
10017            .iter()
10018            .find(|r| r["id"] == json!("eu-aia-record-keeping"))
10019            .unwrap();
10020        assert_eq!(record_keeping["satisfied"], json!(false));
10021
10022        // An empty allowedZones array is also unsatisfied.
10023        let zone_creds = vec![json!({
10024            "type": ["VerifiableCredential", "PhysicalCapabilityScope"],
10025            "credentialSubject": {
10026                "id": "did:web:robot.example.com",
10027                "physicalScope": { "maxSpeedMps": 1.5, "allowedZones": [] }
10028            }
10029        })];
10030        let ul = check_conformance(&zone_creds, "ul-3300").unwrap();
10031        let limits = ul["requirements"]
10032            .as_array()
10033            .unwrap()
10034            .iter()
10035            .find(|r| r["id"] == json!("ul3300-operating-limits"))
10036            .unwrap();
10037        assert_eq!(limits["satisfied"], json!(false));
10038    }
10039
10040    #[test]
10041    fn conformance_attestation_roundtrip_and_rejections() {
10042        let seed = [77u8; 32];
10043        let kp = Ed25519KeyPair::from_seed(&seed);
10044        let vector = load_vector();
10045        let credentials: Vec<Value> = vector["conformance_credentials"]
10046            .as_array()
10047            .unwrap()
10048            .clone();
10049        let report = check_conformance(&credentials, "eu-ai-act-high-risk").unwrap();
10050
10051        let att = build_conformance_attestation(
10052            &seed,
10053            &BuildConformanceAttestation {
10054                issuer_did: "did:web:authority.example.com".into(),
10055                robot_did: "did:web:robot.example.com".into(),
10056                report: report.clone(),
10057                valid_from: "2026-01-01T00:00:00Z".into(),
10058                valid_until: Some("2027-01-01T00:00:00Z".into()),
10059            },
10060        )
10061        .unwrap();
10062
10063        // Round-trip: a well-formed attestation verifies and surfaces the subject.
10064        let subject =
10065            verify_conformance_attestation(&att, kd(&att, &kp.public_key()), None, None, TNOW)
10066                .unwrap()
10067                .expect("a valid conformance attestation verifies");
10068        assert_eq!(subject["profileId"], json!("eu-ai-act-high-risk"));
10069        assert_eq!(subject["conforms"], json!(true));
10070        assert_eq!(
10071            subject["reportDigest"],
10072            vector["expected_conformance_report_digest"]
10073        );
10074
10075        // Wrong key is rejected.
10076        let wrong_kp = Ed25519KeyPair::from_seed(&[88u8; 32]);
10077        assert!(verify_conformance_attestation(
10078            &att,
10079            kd(&att, &wrong_kp.public_key()),
10080            None,
10081            None,
10082            TNOW
10083        )
10084        .unwrap()
10085        .is_none());
10086
10087        // A tampered embedded report no longer matches the bound digest.
10088        let mut tampered = att.clone();
10089        tampered["credentialSubject"]["report"]["conforms"] = json!(false);
10090        assert!(verify_conformance_attestation(
10091            &tampered,
10092            kd(&tampered, &kp.public_key()),
10093            None,
10094            None,
10095            TNOW
10096        )
10097        .unwrap()
10098        .is_none());
10099
10100        // Wrong type is rejected.
10101        let mut wrong_type = att.clone();
10102        wrong_type["type"] = json!(["VerifiableCredential"]);
10103        assert!(verify_conformance_attestation(
10104            &wrong_type,
10105            kd(&wrong_type, &kp.public_key()),
10106            None,
10107            None,
10108            TNOW
10109        )
10110        .unwrap()
10111        .is_none());
10112
10113        // robot_did is required at build time.
10114        assert!(build_conformance_attestation(
10115            &seed,
10116            &BuildConformanceAttestation {
10117                issuer_did: "did:web:authority.example.com".into(),
10118                robot_did: String::new(),
10119                report,
10120                valid_from: "2026-01-01T00:00:00Z".into(),
10121                valid_until: None,
10122            },
10123        )
10124        .is_err());
10125    }
10126
10127    // -- post-quantum robot credentials ------------------------------------
10128
10129    fn classical_robot_credential(issuer: &str, seed: &[u8]) -> Value {
10130        let cred = json!({
10131            "@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
10132            "type": ["VerifiableCredential", ROBOT_IDENTITY_TYPE],
10133            "issuer": issuer,
10134            "validFrom": "2026-01-01T00:00:00Z",
10135            "credentialSubject": {
10136                "id": issuer,
10137                "make": "Acme Robotics",
10138                "model": "AR-7",
10139                "serial": "SN-000123"
10140            }
10141        });
10142        let opts = BuildProofOptions::new(format!("{issuer}#key-1"), "2026-01-01T00:00:00Z");
10143        data_integrity::sign(&cred, seed, &opts).unwrap()
10144    }
10145
10146    // Cross-language interop: Rust verifies the Python-signed hybrid PQ robot
10147    // identity under the Ed25519 key and the ML-DSA-44 multikey from the vector.
10148    #[test]
10149    fn verifies_python_pq_robot_identity_interop_vector() {
10150        let vector = load_vector();
10151        let ed_pub = jwk_pub(&vector["robot_public_key_jwk"]);
10152        let ml_multikey = vector["robot_mldsa44_public_multikey"].as_str().unwrap();
10153        let cred = vector["pq_robot_identity_credential"].clone();
10154
10155        // (b) the credential is detected as post-quantum.
10156        assert!(is_pq(&cred));
10157
10158        // (a) dual verify auto-detected from the proof, with the ML-DSA multikey.
10159        let ok = verify_robot_credential(
10160            &cred,
10161            kd(&cred, &ed_pub),
10162            Some(ml_multikey.as_bytes()),
10163            None,
10164            TNOW,
10165        )
10166        .expect("the Python hybrid PQ interop vector must verify in Rust");
10167        assert!(ok);
10168
10169        // verify_pq accepts the multikey string form directly.
10170        let resolved = mldsa44_public_from_multikey(ml_multikey).unwrap();
10171        assert!(verify_pq(&cred, &ed_pub, &resolved).unwrap());
10172    }
10173
10174    #[test]
10175    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
10176    fn pq_sign_verify_roundtrip_and_rejects() {
10177        let issuer = "did:web:robot.example.com";
10178        let seed = [21u8; 32];
10179        let kp = Ed25519KeyPair::from_seed(&seed);
10180        let ml = MlDsa44KeyPair::generate().unwrap();
10181
10182        let classical = classical_robot_credential(issuer, &seed);
10183        assert!(!is_pq(&classical));
10184
10185        // Sign post-quantum; any prior proof is replaced by a proof set holding
10186        // one classical and one ML-DSA-44 proof.
10187        let signed = sign_pq(&classical, &seed, &ml, "2026-02-01T00:00:00Z").unwrap();
10188        assert!(is_pq(&signed));
10189        let proofs = signed["proof"].as_array().expect("proof set");
10190        assert_eq!(proofs.len(), 2);
10191        assert_eq!(
10192            proofs[0]["cryptosuite"],
10193            json!(hybrid::EDDSA_CRYPTOSUITE_ID)
10194        );
10195        assert_eq!(
10196            proofs[1]["cryptosuite"],
10197            json!(hybrid::MLDSA44_CRYPTOSUITE_ID)
10198        );
10199        // Each proof carries the Multibase encoding its cryptosuite specifies.
10200        assert!(proofs[0]["proofValue"].as_str().unwrap().starts_with('z'));
10201        assert!(proofs[1]["proofValue"].as_str().unwrap().starts_with('u'));
10202
10203        // Round-trip: both signatures validate under the correct keys.
10204        assert!(verify_pq(&signed, &kp.public_key(), &ml.public_key()).unwrap());
10205        assert!(verify_robot_credential(
10206            &signed,
10207            kd(&signed, &kp.public_key()),
10208            Some(&ml.public_key()),
10209            None,
10210            TNOW
10211        )
10212        .unwrap());
10213
10214        // The multikey string form is accepted too (as UTF-8 bytes).
10215        let ml_mk = multikey::encode_mldsa44_public(&ml.public_key()).unwrap();
10216        assert!(verify_robot_credential(
10217            &signed,
10218            kd(&signed, &kp.public_key()),
10219            Some(ml_mk.as_bytes()),
10220            None,
10221            TNOW
10222        )
10223        .unwrap());
10224
10225        // Tampering the body breaks verification.
10226        let mut tampered = signed.clone();
10227        tampered["credentialSubject"]["model"] = json!("AR-9");
10228        assert!(!verify_pq(&tampered, &kp.public_key(), &ml.public_key()).unwrap());
10229
10230        // Wrong Ed25519 key is rejected.
10231        let other_ed = Ed25519KeyPair::from_seed(&[99u8; 32]);
10232        assert!(!verify_pq(&signed, &other_ed.public_key(), &ml.public_key()).unwrap());
10233
10234        // Wrong ML-DSA-44 key is rejected.
10235        let other_ml = MlDsa44KeyPair::generate().unwrap();
10236        assert!(!verify_pq(&signed, &kp.public_key(), &other_ml.public_key()).unwrap());
10237
10238        // A hybrid credential without the ML-DSA key returns false, not true.
10239        assert!(
10240            !verify_robot_credential(&signed, kd(&signed, &kp.public_key()), None, None, TNOW)
10241                .unwrap()
10242        );
10243
10244        // Downgrade by extraction: an attacker strips the proof set to the lone
10245        // standalone classical proof. A verifier that supplies the ML-DSA key
10246        // (so requires post-quantum) must reject it, not accept it as classical.
10247        let proofs = signed["proof"].as_array().unwrap();
10248        let classical_proof = proofs
10249            .iter()
10250            .find(|p| p["cryptosuite"] == json!(hybrid::EDDSA_CRYPTOSUITE_ID))
10251            .unwrap()
10252            .clone();
10253        let mut stripped = signed.clone();
10254        stripped["proof"] = classical_proof;
10255        assert!(!is_pq(&stripped));
10256        assert!(
10257            !verify_robot_credential(
10258                &stripped,
10259                kd(&stripped, &kp.public_key()),
10260                Some(&ml.public_key()),
10261                None,
10262                TNOW
10263            )
10264            .unwrap(),
10265            "a stripped proof set must not verify when the caller requires post-quantum"
10266        );
10267        // The extracted classical proof is genuine, so a caller that only does
10268        // classical verification (no ML-DSA key) still accepts it.
10269        assert!(verify_robot_credential(
10270            &stripped,
10271            kd(&stripped, &kp.public_key()),
10272            None,
10273            None,
10274            TNOW
10275        )
10276        .unwrap());
10277    }
10278
10279    #[test]
10280    fn classical_credential_passes_dual_verify_without_pq_key() {
10281        let issuer = "did:web:robot.example.com";
10282        let seed = [22u8; 32];
10283        let kp = Ed25519KeyPair::from_seed(&seed);
10284        let classical = classical_robot_credential(issuer, &seed);
10285
10286        assert!(!is_pq(&classical));
10287        // A classical credential verifies through the dual path with no ML-DSA key.
10288        assert!(verify_robot_credential(
10289            &classical,
10290            kd(&classical, &kp.public_key()),
10291            None,
10292            None,
10293            TNOW
10294        )
10295        .unwrap());
10296
10297        // A wrong key still fails.
10298        let other = Ed25519KeyPair::from_seed(&[7u8; 32]);
10299        assert!(!verify_robot_credential(
10300            &classical,
10301            kd(&classical, &other.public_key()),
10302            None,
10303            None,
10304            TNOW
10305        )
10306        .unwrap());
10307    }
10308
10309    #[test]
10310    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
10311    fn migrate_to_pq_resigns_classical_credential() {
10312        let issuer = "did:web:robot.example.com";
10313        let seed = [23u8; 32];
10314        let kp = Ed25519KeyPair::from_seed(&seed);
10315        let ml = MlDsa44KeyPair::generate().unwrap();
10316
10317        let classical = classical_robot_credential(issuer, &seed);
10318        assert!(verify_robot_credential(
10319            &classical,
10320            kd(&classical, &kp.public_key()),
10321            None,
10322            None,
10323            TNOW
10324        )
10325        .unwrap());
10326
10327        let migrated = migrate_to_pq(&classical, &seed, &ml, "2026-03-01T00:00:00Z").unwrap();
10328        assert!(is_pq(&migrated));
10329        // The body is preserved across migration.
10330        assert_eq!(
10331            migrated["credentialSubject"],
10332            classical["credentialSubject"]
10333        );
10334        assert!(verify_robot_credential(
10335            &migrated,
10336            kd(&migrated, &kp.public_key()),
10337            Some(&ml.public_key()),
10338            None,
10339            TNOW
10340        )
10341        .unwrap());
10342    }
10343
10344    // Cross-language interop: Rust verifies the Python-signed embodiment continuity
10345    // chain under the one agent key from the vector, ending on body-b, with no fork.
10346    #[test]
10347    fn verifies_python_embodiment_interop_vector() {
10348        let vector = load_vector();
10349        let agent_pub = jwk_pub(&vector["embodiment_agent_key"]);
10350        let chain: Vec<Value> = vector["embodiment_chain"]
10351            .as_array()
10352            .expect("embodiment_chain array")
10353            .clone();
10354
10355        let (ok, current) = verify_continuity_chain(
10356            &chain,
10357            Keys::Resolver(&any_did(&agent_pub)),
10358            None,
10359            None,
10360            "2026-06-01T00:00:00Z",
10361        )
10362        .unwrap();
10363        assert!(ok, "the Python embodiment chain must verify in Rust");
10364        assert_eq!(
10365            current.as_deref(),
10366            Some("did:web:body-b.example.com"),
10367            "the chain ends on body-b"
10368        );
10369
10370        let (no_fork, conflict) = check_no_fork(&chain).unwrap();
10371        assert!(no_fork, "the Python embodiment chain has no fork");
10372        assert!(conflict.is_none());
10373    }
10374
10375    #[test]
10376    fn embodiment_roundtrip_and_issuer_rule() {
10377        let agent_seed = [61u8; 32];
10378        let other_seed = [62u8; 32];
10379        let agent = Ed25519KeyPair::from_seed(&agent_seed);
10380        let other = Ed25519KeyPair::from_seed(&other_seed);
10381        let agent_did = "did:web:agent.example.com";
10382        let body_a = "did:web:body-a.example.com";
10383
10384        let cred = build_embodiment(
10385            &agent_seed,
10386            &BuildEmbodiment {
10387                agent_did: agent_did.into(),
10388                body_did: body_a.into(),
10389                body_hardware_root: "uROOTA".into(),
10390                from_body: None,
10391                embodied_at: "2026-01-01T00:00:00Z".into(),
10392                valid_until: None,
10393            },
10394        )
10395        .unwrap();
10396
10397        let subject = verify_embodiment(&cred, kd(&cred, &agent.public_key()), None, TNOW)
10398            .unwrap()
10399            .expect("embodiment verifies under the agent key");
10400        assert_eq!(subject["body"], json!(body_a));
10401        assert_eq!(subject["bodyHardwareRoot"], json!("uROOTA"));
10402
10403        // The issuer must equal the subject id: forge a credential issued by an
10404        // impostor over an unchanged subject (still the agent) and re-sign it. It
10405        // must be rejected even with a valid proof under the signing key, because a
10406        // mind only authorizes its own embodiment.
10407        let forged = {
10408            let mut bare = cred.clone();
10409            bare.as_object_mut().unwrap().remove("proof");
10410            bare["issuer"] = json!("did:web:impostor.example.com");
10411            let opts = BuildProofOptions::new(
10412                "did:web:impostor.example.com#key-1".to_string(),
10413                "2026-01-01T00:00:00Z",
10414            );
10415            data_integrity::sign(&bare, &other_seed, &opts).unwrap()
10416        };
10417        assert!(
10418            verify_embodiment(&forged, kd(&forged, &other.public_key()), None, TNOW)
10419                .unwrap()
10420                .is_none()
10421        );
10422    }
10423
10424    #[test]
10425    fn continuity_chain_links_and_rejects() {
10426        let agent_seed = [61u8; 32];
10427        let stranger_seed = [63u8; 32];
10428        let agent = Ed25519KeyPair::from_seed(&agent_seed);
10429        let stranger = Ed25519KeyPair::from_seed(&stranger_seed);
10430        let agent_did = "did:web:agent.example.com";
10431        let body_a = "did:web:body-a.example.com";
10432        let body_b = "did:web:body-b.example.com";
10433
10434        let e1 = build_embodiment(
10435            &agent_seed,
10436            &BuildEmbodiment {
10437                agent_did: agent_did.into(),
10438                body_did: body_a.into(),
10439                body_hardware_root: "uROOTA".into(),
10440                from_body: None,
10441                embodied_at: "2026-01-01T00:00:00Z".into(),
10442                valid_until: Some("2026-01-01T01:00:00Z".into()),
10443            },
10444        )
10445        .unwrap();
10446        let e2 = build_embodiment(
10447            &agent_seed,
10448            &BuildEmbodiment {
10449                agent_did: agent_did.into(),
10450                body_did: body_b.into(),
10451                body_hardware_root: "uROOTB".into(),
10452                from_body: Some(body_a.into()),
10453                embodied_at: "2026-01-01T01:00:00Z".into(),
10454                valid_until: None,
10455            },
10456        )
10457        .unwrap();
10458
10459        // A clean two-link chain ends at body-b: the first link opens on body-a
10460        // and the second link's fromBody re-binds to it.
10461        let (ok, current) = verify_continuity_chain(
10462            &[e1.clone(), e2.clone()],
10463            Keys::Resolver(&any_did(&agent.public_key())),
10464            None,
10465            None,
10466            "2026-06-01T00:00:00Z",
10467        )
10468        .unwrap();
10469        assert!(ok);
10470        assert_eq!(current.as_deref(), Some(body_b));
10471
10472        // Declaring the wrong origin body breaks the first link, since the first
10473        // link's fromBody must match the origin when given.
10474        let (bad_origin, _) = verify_continuity_chain(
10475            &[e1.clone(), e2.clone()],
10476            Keys::Resolver(&any_did(&agent.public_key())),
10477            Some(body_b),
10478            None,
10479            "2026-06-01T00:00:00Z",
10480        )
10481        .unwrap();
10482        assert!(!bad_origin);
10483
10484        // A broken link (second link's fromBody does not match the first's body)
10485        // fails the chain.
10486        let broken = build_embodiment(
10487            &agent_seed,
10488            &BuildEmbodiment {
10489                agent_did: agent_did.into(),
10490                body_did: body_b.into(),
10491                body_hardware_root: "uROOTB".into(),
10492                from_body: Some("did:web:body-x.example.com".into()),
10493                embodied_at: "2026-01-01T01:00:00Z".into(),
10494                valid_until: None,
10495            },
10496        )
10497        .unwrap();
10498        let (bad_link, _) = verify_continuity_chain(
10499            &[e1.clone(), broken],
10500            Keys::Resolver(&any_did(&agent.public_key())),
10501            None,
10502            None,
10503            "2026-06-01T00:00:00Z",
10504        )
10505        .unwrap();
10506        assert!(!bad_link);
10507
10508        // Every link must verify under the SAME agent key: a link signed by a
10509        // different key breaks the chain (a mind is one persistent identity).
10510        let e2_stranger = build_embodiment(
10511            &stranger_seed,
10512            &BuildEmbodiment {
10513                agent_did: agent_did.into(),
10514                body_did: body_b.into(),
10515                body_hardware_root: "uROOTB".into(),
10516                from_body: Some(body_a.into()),
10517                embodied_at: "2026-01-01T01:00:00Z".into(),
10518                valid_until: None,
10519            },
10520        )
10521        .unwrap();
10522        assert!(verify_embodiment(
10523            &e2_stranger,
10524            kd(&e2_stranger, &stranger.public_key()),
10525            None,
10526            "2026-06-01T00:00:00Z"
10527        )
10528        .unwrap()
10529        .is_some());
10530        let (mixed_keys, _) = verify_continuity_chain(
10531            &[e1, e2_stranger],
10532            Keys::Resolver(&any_did(&agent.public_key())),
10533            None,
10534            None,
10535            "2026-06-01T00:00:00Z",
10536        )
10537        .unwrap();
10538        assert!(!mixed_keys);
10539    }
10540
10541    #[test]
10542    fn fork_detection_flags_overlapping_bodies() {
10543        let agent_seed = [61u8; 32];
10544        let agent_did = "did:web:agent.example.com";
10545        let body_a = "did:web:body-a.example.com";
10546        let body_b = "did:web:body-b.example.com";
10547
10548        let build = |body: &str, root: &str, from: &str, until: &str| {
10549            build_embodiment(
10550                &agent_seed,
10551                &BuildEmbodiment {
10552                    agent_did: agent_did.into(),
10553                    body_did: body.into(),
10554                    body_hardware_root: root.into(),
10555                    from_body: None,
10556                    embodied_at: from.into(),
10557                    valid_until: Some(until.into()),
10558                },
10559            )
10560            .unwrap()
10561        };
10562
10563        // A clean handover: body-a's window ends exactly where body-b's begins.
10564        // Half-open intervals do not overlap, so this is not a fork.
10565        let clean_a = build(
10566            body_a,
10567            "uROOTA",
10568            "2026-01-01T00:00:00Z",
10569            "2026-01-01T01:00:00Z",
10570        );
10571        let clean_b = build(
10572            body_b,
10573            "uROOTB",
10574            "2026-01-01T01:00:00Z",
10575            "2026-01-01T02:00:00Z",
10576        );
10577        let (clean, conflict) = check_no_fork(&[clean_a, clean_b]).unwrap();
10578        assert!(clean);
10579        assert!(conflict.is_none());
10580
10581        // Overlapping windows on different bodies are a fork; the conflict names
10582        // both bodies.
10583        let fork_a = build(
10584            body_a,
10585            "uROOTA",
10586            "2026-01-01T00:00:00Z",
10587            "2026-01-01T02:00:00Z",
10588        );
10589        let fork_b = build(
10590            body_b,
10591            "uROOTB",
10592            "2026-01-01T01:00:00Z",
10593            "2026-01-01T03:00:00Z",
10594        );
10595        let (forked, conflict) = check_no_fork(&[fork_a, fork_b]).unwrap();
10596        assert!(!forked);
10597        let conflict = conflict.expect("a fork names the two conflicting bodies");
10598        assert_eq!(conflict.body_a, body_a);
10599        assert_eq!(conflict.body_b, body_b);
10600    }
10601
10602    // Custody handoff (Phase 5.16) -----------------------------------------
10603
10604    fn actor_keys_from_vector(map: &Value) -> Vec<ActorKey> {
10605        map.as_object()
10606            .expect("custody_actor_keys object")
10607            .iter()
10608            .map(|(did, jwk)| ActorKey {
10609                did: did.clone(),
10610                public_key: jwk_pub(jwk),
10611            })
10612            .collect()
10613    }
10614
10615    // Cross-language interop: Rust verifies the Python-signed custody chain under
10616    // the actor keys from the vector, ending on robot-b, and localizes the
10617    // condition change to the hop robot-a was responsible for.
10618    #[test]
10619    fn verifies_python_custody_interop_vector() {
10620        let vector = load_vector();
10621        let chain: Vec<Value> = vector["custody_chain"]
10622            .as_array()
10623            .expect("custody_chain array")
10624            .clone();
10625        let keys = actor_keys_from_vector(&vector["custody_actor_keys"]);
10626        let origin = vector["custody_origin_actor"].as_str().unwrap();
10627
10628        let (ok, current) =
10629            verify_handoff_chain(&chain, &keys, "tote-42", Some(origin), false, TNOW).unwrap();
10630        assert!(ok, "the Python custody chain must verify in Rust");
10631        assert_eq!(
10632            current.as_deref(),
10633            Some("did:web:robot-b.example.com"),
10634            "the chain ends holding at robot-b"
10635        );
10636
10637        let change = locate_condition_change(&chain).expect("the condition changed");
10638        assert_eq!(
10639            change.responsible_holder.as_deref(),
10640            Some("did:web:robot-a.example.com"),
10641            "robot-a held the task while its condition changed"
10642        );
10643        assert_eq!(change.from_condition, "intact");
10644        assert_eq!(change.to_condition, "damaged");
10645    }
10646
10647    #[test]
10648    fn handoff_roundtrip_and_receiver_rule() {
10649        let robot_seed = [71u8; 32];
10650        let other_seed = [72u8; 32];
10651        let robot = Ed25519KeyPair::from_seed(&robot_seed);
10652        let other = Ed25519KeyPair::from_seed(&other_seed);
10653        let worker = "did:web:worker-jane.example.com";
10654        let robot_a = "did:web:robot-a.example.com";
10655
10656        let cred = build_handoff(
10657            &robot_seed,
10658            &BuildHandoff {
10659                release: None,
10660                prev_handoff_id: None,
10661                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000105".into(),
10662                task_id: "tote-42".into(),
10663                from_actor: worker.into(),
10664                to_actor: robot_a.into(),
10665                condition: Some("intact".into()),
10666                handoff_at: "2026-01-01T00:00:00Z".into(),
10667                valid_until: None,
10668            },
10669        )
10670        .unwrap();
10671
10672        let subject = verify_handoff(
10673            &cred,
10674            kd(&cred, &robot.public_key()),
10675            HandoffCheck::default(),
10676            TNOW,
10677        )
10678        .unwrap()
10679        .expect("handoff verifies under the receiver key");
10680        assert_eq!(subject["fromActor"], json!(worker));
10681        assert_eq!(subject["toActor"], json!(robot_a));
10682
10683        // The issuer must be the receiver: forge a handoff issued by a different
10684        // party over the same subject and re-sign it. It must be rejected even with
10685        // a valid proof under the signing key, because a party attests its own
10686        // acceptance of custody.
10687        let forged = {
10688            let mut bare = cred.clone();
10689            bare.as_object_mut().unwrap().remove("proof");
10690            bare["issuer"] = json!("did:web:impostor.example.com");
10691            let opts = BuildProofOptions::new(
10692                "did:web:impostor.example.com#key-1".to_string(),
10693                "2026-01-01T00:00:00Z",
10694            );
10695            data_integrity::sign(&bare, &other_seed, &opts).unwrap()
10696        };
10697        assert!(verify_handoff(
10698            &forged,
10699            kd(&forged, &other.public_key()),
10700            HandoffCheck::default(),
10701            TNOW
10702        )
10703        .unwrap()
10704        .is_none());
10705    }
10706
10707    #[test]
10708    fn handoff_chain_links_and_rejects() {
10709        let a_seed = [73u8; 32];
10710        let b_seed = [74u8; 32];
10711        let a = Ed25519KeyPair::from_seed(&a_seed);
10712        let b = Ed25519KeyPair::from_seed(&b_seed);
10713        let worker = "did:web:worker-jane.example.com";
10714        let robot_a = "did:web:robot-a.example.com";
10715        let robot_b = "did:web:robot-b.example.com";
10716
10717        let h1 = build_handoff(
10718            &a_seed,
10719            &BuildHandoff {
10720                release: None,
10721                prev_handoff_id: None,
10722                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000106".into(),
10723                task_id: "tote-42".into(),
10724                from_actor: worker.into(),
10725                to_actor: robot_a.into(),
10726                condition: Some("intact".into()),
10727                handoff_at: "2026-01-01T00:00:00Z".into(),
10728                valid_until: None,
10729            },
10730        )
10731        .unwrap();
10732        let h2 = build_handoff(
10733            &b_seed,
10734            &BuildHandoff {
10735                release: None,
10736                prev_handoff_id: Some("urn:uuid:00000000-0000-4000-8000-000000000106".into()),
10737                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000107".into(),
10738                task_id: "tote-42".into(),
10739                from_actor: robot_a.into(),
10740                to_actor: robot_b.into(),
10741                condition: Some("damaged".into()),
10742                handoff_at: "2026-01-01T00:10:00Z".into(),
10743                valid_until: None,
10744            },
10745        )
10746        .unwrap();
10747
10748        let keys = vec![
10749            ActorKey {
10750                did: robot_a.into(),
10751                public_key: a.public_key().to_vec(),
10752            },
10753            ActorKey {
10754                did: robot_b.into(),
10755                public_key: b.public_key().to_vec(),
10756            },
10757        ];
10758
10759        // A clean two-link chain ends holding at robot-b: the first link's
10760        // fromActor is the origin worker and the second link re-binds to robot-a.
10761        let (ok, current) = verify_handoff_chain(
10762            &[h1.clone(), h2.clone()],
10763            &keys,
10764            "tote-42",
10765            Some(worker),
10766            false,
10767            TNOW,
10768        )
10769        .unwrap();
10770        assert!(ok);
10771        assert_eq!(current.as_deref(), Some(robot_b));
10772
10773        // Declaring the wrong origin actor breaks the first link.
10774        let (bad_origin, _) = verify_handoff_chain(
10775            &[h1.clone(), h2.clone()],
10776            &keys,
10777            "tote-42",
10778            Some(robot_b),
10779            false,
10780            TNOW,
10781        )
10782        .unwrap();
10783        assert!(!bad_origin);
10784
10785        // A broken link (second link's fromActor does not match the first's
10786        // toActor) fails the chain.
10787        let broken = build_handoff(
10788            &b_seed,
10789            &BuildHandoff {
10790                release: None,
10791                prev_handoff_id: Some("urn:uuid:00000000-0000-4000-8000-000000000106".into()),
10792                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000108".into(),
10793                task_id: "tote-42".into(),
10794                from_actor: "did:web:robot-x.example.com".into(),
10795                to_actor: robot_b.into(),
10796                condition: Some("damaged".into()),
10797                handoff_at: "2026-01-01T00:10:00Z".into(),
10798                valid_until: None,
10799            },
10800        )
10801        .unwrap();
10802        let (bad_link, _) = verify_handoff_chain(
10803            &[h1.clone(), broken],
10804            &keys,
10805            "tote-42",
10806            Some(worker),
10807            false,
10808            TNOW,
10809        )
10810        .unwrap();
10811        assert!(!bad_link);
10812
10813        // A missing receiver key for a link fails the chain.
10814        let partial = vec![ActorKey {
10815            did: robot_a.into(),
10816            public_key: a.public_key().to_vec(),
10817        }];
10818        let (no_key, _) = verify_handoff_chain(
10819            &[h1.clone(), h2.clone()],
10820            &partial,
10821            "tote-42",
10822            Some(worker),
10823            false,
10824            TNOW,
10825        )
10826        .unwrap();
10827        assert!(!no_key);
10828
10829        // holder_at reports who held the task at a moment: robot-a right after the
10830        // first handoff, robot-b right after the second.
10831        assert_eq!(
10832            holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:05:00Z").as_deref(),
10833            Some(robot_a)
10834        );
10835        assert_eq!(
10836            holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:15:00Z").as_deref(),
10837            Some(robot_b)
10838        );
10839
10840        // A chain whose condition never changes localizes nothing.
10841        let steady = build_handoff(
10842            &b_seed,
10843            &BuildHandoff {
10844                release: None,
10845                prev_handoff_id: None,
10846                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000109".into(),
10847                task_id: "tote-42".into(),
10848                from_actor: robot_a.into(),
10849                to_actor: robot_b.into(),
10850                condition: Some("intact".into()),
10851                handoff_at: "2026-01-01T00:10:00Z".into(),
10852                valid_until: None,
10853            },
10854        )
10855        .unwrap();
10856        assert!(locate_condition_change(&[h1, steady]).is_none());
10857    }
10858
10859    // Robot-to-infrastructure bounded access (Phase 5.17) ------------------
10860
10861    // Cross-language interop: Rust authorizes the Python-signed grant and request
10862    // from the vector under the operator and robot keys, offline.
10863    #[test]
10864    fn authorizes_python_access_interop_vector() {
10865        let vector = load_vector();
10866        let grant = vector["access_grant_credential"].clone();
10867        let request = vector["access_request_credential"].clone();
10868        let operator_pub = jwk_pub(&vector["access_operator_key"]);
10869        let robot_pub = jwk_pub(&vector["access_robot_key"]);
10870
10871        // The request was made at VALID_FROM; a resource checks it within the
10872        // 60 s age limit and remembers its nonce.
10873        let mut seen = HashSet::new();
10874        let res = authorize_access(
10875            &grant,
10876            &request,
10877            kd(&grant, &operator_pub),
10878            kd(&request, &robot_pub),
10879            RequestReplay::new(&mut seen),
10880            "2026-01-01T00:00:30Z",
10881        )
10882        .unwrap();
10883        assert!(
10884            res.ok,
10885            "the Python grant and request must authorize in Rust: {:?}",
10886            res.reasons
10887        );
10888        assert!(res.reasons.is_empty());
10889        // A replay of the same request is refused, and so is a stale one.
10890        let again = authorize_access(
10891            &grant,
10892            &request,
10893            kd(&grant, &operator_pub),
10894            kd(&request, &robot_pub),
10895            RequestReplay::new(&mut seen),
10896            "2026-01-01T00:00:30Z",
10897        )
10898        .unwrap();
10899        assert!(!again.ok);
10900        let mut fresh = HashSet::new();
10901        let stale = authorize_access(
10902            &grant,
10903            &request,
10904            kd(&grant, &operator_pub),
10905            kd(&request, &robot_pub),
10906            RequestReplay::new(&mut fresh),
10907            "2026-01-01T00:05:00Z",
10908        )
10909        .unwrap();
10910        assert!(!stale.ok);
10911    }
10912
10913    // Fused-sensor provenance (Phase 5.18) ---------------------------------
10914
10915    // Cross-language interop: Rust reproduces the exact inputs digest and fused
10916    // output hash Python pinned, and verifies the Python-signed attestation.
10917    #[test]
10918    fn verifies_python_fused_interop_vector() {
10919        let vector = load_vector();
10920        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
10921
10922        let inputs: Vec<String> = vector["fused_input_frame_hashes"]
10923            .as_array()
10924            .unwrap()
10925            .iter()
10926            .map(|v| v.as_str().unwrap().to_string())
10927            .collect();
10928        assert_eq!(
10929            fusion_inputs_digest_version(&inputs, INPUTS_DIGEST_V1).unwrap(),
10930            vector["expected_fusion_inputs_digest"].as_str().unwrap()
10931        );
10932        assert_eq!(
10933            fusion_inputs_digest(&inputs).unwrap(),
10934            vector["expected_fusion_inputs_digest_v2"].as_str().unwrap()
10935        );
10936
10937        assert_eq!(
10938            hash_fused_output(b"world-model-0"),
10939            vector["expected_fused_output_hash"].as_str().unwrap()
10940        );
10941
10942        let cred = vector["fused_perception_attestation"].clone();
10943        let subject = verify_fused_attestation(&cred, kd(&cred, &robot_pub), None, TNOW)
10944            .unwrap()
10945            .expect("fused attestation verifies");
10946        assert_eq!(subject["fusionMethod"], "occupancy-grid-v1");
10947        assert_eq!(
10948            subject["inputsDigest"].as_str().unwrap(),
10949            vector["expected_fusion_inputs_digest_v2"].as_str().unwrap()
10950        );
10951    }
10952
10953    // Wear and degradation attestation (Phase 5.19) ------------------------
10954
10955    // Cross-language interop: Rust verifies the Python-signed wear history and
10956    // reproduces the physical scope narrowed for the pinned wear level.
10957    #[test]
10958    fn verifies_python_wear_interop_vector() {
10959        let vector = load_vector();
10960        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
10961
10962        let chain: Vec<Value> = vector["wear_chain"].as_array().unwrap().clone();
10963        // Checked at the vector's moment, when its newest reading is fresh.
10964        let at = vector["wear_now"].as_str().unwrap();
10965        let latest = verify_wear_chain(
10966            &chain,
10967            Keys::Resolver(&any_did(&robot_pub)),
10968            at,
10969            &WearChainCheck::default(),
10970        )
10971        .unwrap()
10972        .expect("wear chain verifies");
10973        assert_eq!(latest["wearLevel"].as_f64().unwrap(), 0.3);
10974
10975        let scope = vector["wear_input_scope"].clone();
10976        let level = vector["wear_attenuation_level"].as_f64().unwrap();
10977        let narrowed = attenuate_for_wear(&scope, level).unwrap();
10978        assert_eq!(narrowed, vector["expected_attenuated_scope"]);
10979        assert_eq!(narrowed["maxForceN"].as_f64().unwrap(), 60.0);
10980        assert_eq!(narrowed["maxSpeedMps"].as_f64().unwrap(), 1.125);
10981        assert_eq!(narrowed["maxSpeedNearHumansMps"].as_f64().unwrap(), 0.1875);
10982        assert!(attenuates(&scope, &narrowed));
10983    }
10984
10985    // Bystander-consent evidence (Phase 5.20) ------------------------------
10986
10987    // Cross-language interop: Rust reproduces the capture hash Python pinned,
10988    // verifies the bystander-signed token is bound to that capture, and verifies
10989    // the robot-signed evidence with the token and the bystander key.
10990    #[test]
10991    fn verifies_python_consent_interop_vector() {
10992        let vector = load_vector();
10993        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
10994        let bystander_pub = jwk_pub(&vector["consent_bystander_key"]);
10995
10996        let capture = b"bystander-frame-0";
10997        let capture_hash = hash_capture(capture);
10998        assert_eq!(
10999            capture_hash,
11000            vector["expected_consent_capture_hash"].as_str().unwrap()
11001        );
11002
11003        let token = vector["consent_token_credential"].clone();
11004        let robot_did = token["credentialSubject"]["robotDid"].as_str().unwrap();
11005        let tok_subject = verify_consent_token(
11006            &token,
11007            kd(&token, &bystander_pub),
11008            &capture_hash,
11009            robot_did,
11010            "2026-01-01T00:05:00Z",
11011        )
11012        .unwrap()
11013        .expect("consent token verifies bound to the capture");
11014        assert_eq!(tok_subject["captureHash"].as_str().unwrap(), capture_hash);
11015
11016        let evidence = vector["consent_evidence_credential"].clone();
11017        let bystander_did = token["issuer"].as_str().unwrap();
11018        let keys = [BystanderKey {
11019            did: bystander_did.to_string(),
11020            public_key: bystander_pub.clone(),
11021        }];
11022        let ev_subject = verify_consent_evidence(
11023            &evidence,
11024            kd(&evidence, &robot_pub),
11025            Some(capture),
11026            Some(core::slice::from_ref(&token)),
11027            Some(&keys),
11028            "2026-01-01T00:05:00Z",
11029        )
11030        .unwrap()
11031        .expect("consent evidence verifies with token and bystander key");
11032        assert_eq!(ev_subject["basis"].as_str().unwrap(), "explicit-consent");
11033    }
11034}
11035
11036#[cfg(test)]
11037mod robot_root_identity_tests {
11038    use super::*;
11039    use crate::keys::Ed25519KeyPair;
11040    #[allow(unused_imports)]
11041    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
11042    #[allow(unused_imports)]
11043    use crate::robotics_verify::Keys;
11044    use std::path::PathBuf;
11045
11046    const NOW: &str = "2026-07-01T00:00:00Z";
11047    const VALID_FROM: &str = "2026-01-01T00:00:00Z";
11048    const CREATED: &str = "2026-01-01T00:00:00Z";
11049    const VALID_SECONDS: i64 = 100 * 365 * 24 * 3600;
11050    // Matches the manufacturer seed recorded in the interop vector (0x04 x32).
11051    const MANUFACTURER_SEED: [u8; 32] = [0x04; 32];
11052    const FORGED_ID: &str = "urn:uuid:66666666-6666-6666-6666-666666666666";
11053
11054    fn load_vector() -> Value {
11055        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11056            .join("../../test-vectors/root-of-trust/vector.json");
11057        let text = std::fs::read_to_string(&path)
11058            .unwrap_or_else(|e| panic!("read vector {}: {e}", path.display()));
11059        serde_json::from_str(&text).expect("vector is valid JSON")
11060    }
11061
11062    fn robot_pub(vector: &Value) -> Vec<u8> {
11063        let x = vector["robotPublicKey"]["x"].as_str().unwrap();
11064        URL_SAFE_NO_PAD.decode(x).unwrap()
11065    }
11066
11067    fn stray_multikey(seed: &[u8]) -> String {
11068        let kp = Ed25519KeyPair::from_seed_slice(seed).unwrap();
11069        multikey::encode_ed25519_public(&kp.public_key()).unwrap()
11070    }
11071
11072    fn stray_did(seed: &[u8]) -> String {
11073        Ed25519KeyPair::from_seed_slice(seed).unwrap().did_key()
11074    }
11075
11076    fn robot_attributes() -> Value {
11077        json!({ "make": "Acme Robotics", "model": "AR-7", "serial": "SN-000123" })
11078    }
11079
11080    // The committed Python-minted robot chain must verify in Rust: recognized
11081    // manufacturer provenance plus hardware-rooting.
11082    #[test]
11083    fn verifies_python_robot_identity_interop_vector() {
11084        let v = load_vector();
11085        let root = v["trustedRoot"].as_str().unwrap();
11086        let r = verify_robot_identity_chain(
11087            &v["robotAuthorityIdentity"],
11088            &v["robotRecognizedIssuer"],
11089            &v["robotHardwareCredential"],
11090            root,
11091            &robot_pub(&v),
11092            Some(&v["rootOfTrust"]),
11093            NOW,
11094            30,
11095        );
11096        assert!(r.ok, "robot chain must verify: {:?}", r.reason);
11097        assert_eq!(
11098            Some(r.hardware_rooted),
11099            v["expected"]["hardwareRooted"].as_bool(),
11100            "the manufacturer pinned the hardware-root key"
11101        );
11102        assert_eq!(r.robot_did.as_deref(), v["expected"]["robotDid"].as_str());
11103        assert_eq!(
11104            r.issuer_did.as_deref(),
11105            v["expected"]["robotIssuerDid"].as_str()
11106        );
11107        assert_eq!(r.root_did.as_deref(), Some(root));
11108        assert_eq!(
11109            v["expected"]["verifyRobotIdentityChain"].as_bool(),
11110            Some(true)
11111        );
11112    }
11113
11114    // Adversarial: pinning a different root breaks the recognition anchor.
11115    #[test]
11116    fn wrong_pinned_root_rejected() {
11117        let v = load_vector();
11118        let other_root = stray_did(&[0x09; 32]);
11119        let r = verify_robot_identity_chain(
11120            &v["robotAuthorityIdentity"],
11121            &v["robotRecognizedIssuer"],
11122            &v["robotHardwareCredential"],
11123            &other_root,
11124            &robot_pub(&v),
11125            None,
11126            NOW,
11127            30,
11128        );
11129        assert!(!r.ok);
11130        assert_eq!(r.reason.as_deref(), Some("recognized_issuer_not_from_root"));
11131    }
11132
11133    // Adversarial: the manufacturer vouched a key that is not the robot's real
11134    // key. Provenance holds but the hardware key does not match.
11135    #[test]
11136    fn manufacturer_vouched_a_different_key() {
11137        let v = load_vector();
11138        let root = v["trustedRoot"].as_str().unwrap();
11139        let robot_did = v["expected"]["robotDid"].as_str().unwrap();
11140        let forged = build_robot_identity(
11141            &MANUFACTURER_SEED,
11142            robot_did,
11143            &stray_multikey(&[0x09; 32]),
11144            &robot_attributes(),
11145            VALID_SECONDS,
11146            VALID_FROM,
11147            CREATED,
11148            None,
11149            FORGED_ID,
11150            None,
11151        )
11152        .unwrap();
11153        let r = verify_robot_identity_chain(
11154            &forged,
11155            &v["robotRecognizedIssuer"],
11156            &v["robotHardwareCredential"],
11157            root,
11158            &robot_pub(&v),
11159            Some(&v["rootOfTrust"]),
11160            NOW,
11161            30,
11162        );
11163        assert!(!r.ok);
11164        assert_eq!(r.reason.as_deref(), Some("hardware_key_mismatch"));
11165    }
11166
11167    // Adversarial: an impostor key is presented for the hardware credential, so
11168    // the secure-element attestation no longer verifies.
11169    #[test]
11170    fn impostor_key_fails_hardware_root() {
11171        let v = load_vector();
11172        let root = v["trustedRoot"].as_str().unwrap();
11173        let impostor = Ed25519KeyPair::from_seed(&[0x09; 32]).public_key();
11174        let r = verify_robot_identity_chain(
11175            &v["robotAuthorityIdentity"],
11176            &v["robotRecognizedIssuer"],
11177            &v["robotHardwareCredential"],
11178            root,
11179            &impostor,
11180            Some(&v["rootOfTrust"]),
11181            NOW,
11182            30,
11183        );
11184        assert!(!r.ok);
11185        assert_eq!(r.reason.as_deref(), Some("hardware_root_invalid"));
11186    }
11187}
11188
11189#[cfg(test)]
11190mod port_hardening_tests {
11191    use super::*;
11192    use crate::keys::Ed25519KeyPair;
11193    #[allow(unused_imports)]
11194    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
11195    #[allow(unused_imports)]
11196    use crate::robotics_verify::Keys;
11197    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
11198    use base64::Engine;
11199
11200    // A missing or empty input list is malformed: the log check fails closed
11201    // instead of reporting "every input was logged".
11202    #[test]
11203    fn fusion_inputs_check_fails_closed_on_an_empty_list() {
11204        let empty = json!({"credentialSubject": {"inputFrameHashes": []}});
11205        assert!(!verify_fusion_inputs(&empty, &[]).ok);
11206        let missing = json!({"credentialSubject": {}});
11207        assert!(!verify_fusion_inputs(&missing, &[]).ok);
11208        let odd = json!({"credentialSubject": {"inputFrameHashes": ["ua", 5]}});
11209        let res = verify_fusion_inputs(&odd, &[json!({"frameHash": "ua"})]);
11210        assert!(!res.ok);
11211        assert_eq!(res.missing, vec!["5".to_string()]);
11212    }
11213
11214    fn load_vector() -> Value {
11215        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11216            .join("../../test-vectors/robotics/vector.json");
11217        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
11218    }
11219
11220    fn jwk_pub(jwk: &Value) -> Vec<u8> {
11221        URL_SAFE_NO_PAD.decode(jwk["x"].as_str().unwrap()).unwrap()
11222    }
11223
11224    fn lease(valid_until: &str) -> (Value, Vec<u8>) {
11225        let seed = [51u8; 32];
11226        let kp = Ed25519KeyPair::from_seed(&seed);
11227        let cred = build_delegation_lease(
11228            &seed,
11229            &BuildDelegationLease {
11230                issuer_did: "did:web:robot.example.com".into(),
11231                robot_did: "did:web:robot.example.com".into(),
11232                lease_id: "lease-h".into(),
11233                scope: json!({"maxForceN": 80.0}),
11234                parent_lease_id: None,
11235                valid_from: "2026-01-01T00:00:00Z".into(),
11236                valid_until: valid_until.into(),
11237            },
11238        )
11239        .unwrap();
11240        (cred, kp.public_key().to_vec())
11241    }
11242
11243    // The core needs a clock: an empty or malformed `now` is an error, never a
11244    // skipped window check, in every verifier that checks a window.
11245    #[test]
11246    fn a_missing_or_malformed_clock_is_an_error() {
11247        let (cred, key) = lease("2026-01-01T01:00:00Z");
11248        for bad in ["", "null", "not-a-date", "2026-01-01"] {
11249            assert!(
11250                verify_delegation_lease(
11251                    &cred,
11252                    kd(&cred, &key),
11253                    "did:web:robot.example.com",
11254                    None,
11255                    None,
11256                    bad
11257                )
11258                .is_err(),
11259                "{bad:?}"
11260            );
11261            assert!(
11262                lease_permits(
11263                    &json!({}),
11264                    &PhysicalAction::default(),
11265                    Some(&cred),
11266                    kd(&cred, &key),
11267                    None,
11268                    bad
11269                )
11270                .is_err(),
11271                "{bad:?}"
11272            );
11273            assert!(verify_action_authorization(&[], "a", "r", &[], 1, None, bad).is_err());
11274            assert!(verify_access_grant(&cred, kd(&cred, &key), None, bad).is_err());
11275            assert!(authorize_access(
11276                &cred,
11277                &cred,
11278                kd(&cred, &key),
11279                kd(&cred, &key),
11280                RequestReplay::new(&mut HashSet::new()),
11281                bad
11282            )
11283            .is_err());
11284            assert!(verify_consent_token(&cred, kd(&cred, &key), "h", "r", bad).is_err());
11285            assert!(
11286                verify_consent_evidence(&cred, kd(&cred, &key), None, None, None, bad).is_err()
11287            );
11288        }
11289    }
11290
11291    // The shared vector's expired lease is refused at any time after its window,
11292    // and accepted inside it.
11293    #[test]
11294    fn expired_vector_lease_refused_after_its_window() {
11295        let v = load_vector();
11296        let key = jwk_pub(&v["robot_public_key_jwk"]);
11297        let cred = &v["delegation_lease_expired_credential"];
11298        assert!(verify_delegation_lease(
11299            cred,
11300            kd(cred, &key),
11301            "did:web:robot.example.com",
11302            None,
11303            None,
11304            "2026-01-01T00:30:00Z"
11305        )
11306        .unwrap()
11307        .is_some());
11308        assert!(verify_delegation_lease(
11309            cred,
11310            kd(cred, &key),
11311            "did:web:robot.example.com",
11312            None,
11313            None,
11314            "2026-06-01T00:00:00Z"
11315        )
11316        .unwrap()
11317        .is_none());
11318    }
11319
11320    // A validity bound that is present must be a string that parses.
11321    #[test]
11322    fn non_string_window_bounds_are_invalid() {
11323        for (key, bad) in [
11324            ("validFrom", json!(5)),
11325            ("validFrom", json!(null)),
11326            ("validUntil", json!(["2099-01-01T00:00:00Z"])),
11327            ("validUntil", json!(4102444800i64)),
11328            ("validUntil", json!("")),
11329        ] {
11330            let mut cred = json!({
11331                "validFrom": "2026-01-01T00:00:00Z",
11332                "validUntil": "2026-01-01T01:00:00Z"
11333            });
11334            cred[key] = bad.clone();
11335            assert!(
11336                rv::window_reason(&cred, Window::IfPresent, 1_767_225_660 * 1_000_000_000, 0)
11337                    .is_some(),
11338                "{key}={bad}"
11339            );
11340        }
11341    }
11342
11343    // One malformed approval from a listed approver is skipped; it does not fail
11344    // the whole authorization (shared vector).
11345    #[test]
11346    fn malformed_approvals_are_skipped_not_fatal() {
11347        let v = load_vector();
11348        let approvals = v["quorum_approvals_with_malformed"]
11349            .as_array()
11350            .unwrap()
11351            .clone();
11352        let keys: Vec<ApproverKey> = v["quorum_approver_keys"]
11353            .as_object()
11354            .unwrap()
11355            .iter()
11356            .map(|(did, jwk)| ApproverKey {
11357                did: did.clone(),
11358                public_key: jwk_pub(jwk),
11359            })
11360            .collect();
11361        let (ok, approvers) = verify_action_authorization(
11362            &approvals,
11363            v["quorum_action_id"].as_str().unwrap(),
11364            "did:web:robot.example.com",
11365            &keys,
11366            2,
11367            None,
11368            v["quorum_now"].as_str().unwrap(),
11369        )
11370        .unwrap();
11371        let expected = &v["expected_quorum_with_malformed"];
11372        assert_eq!(json!(ok), expected["authorized"]);
11373        assert_eq!(json!(approvers), expected["approvers"]);
11374    }
11375
11376    // A malformed scope field the action is checked against is a violation.
11377    #[test]
11378    fn malformed_scope_fields_are_violations() {
11379        let force = PhysicalAction {
11380            force_n: Some(5000.0),
11381            ..Default::default()
11382        };
11383        for cap in [json!("100"), json!(null), json!(true), json!([100])] {
11384            let r = check_physical_action(&json!({"maxForceN": cap}), &force);
11385            assert!(!r.ok, "maxForceN={cap}");
11386        }
11387        let speed = PhysicalAction {
11388            speed_mps: Some(9.0),
11389            near_humans: true,
11390            ..Default::default()
11391        };
11392        let r = check_physical_action(
11393            &json!({"maxSpeedMps": 1.0, "maxSpeedNearHumansMps": null}),
11394            &speed,
11395        );
11396        assert!(!r.ok);
11397        let zone = PhysicalAction {
11398            zone: Some("A".into()),
11399            ..Default::default()
11400        };
11401        for zones in [json!("A"), json!({"A": true}), json!(7)] {
11402            assert!(!check_physical_action(&json!({"allowedZones": zones}), &zone).ok);
11403        }
11404        let late = PhysicalAction {
11405            time_hm: Some("23:00".into()),
11406            ..Default::default()
11407        };
11408        for ws in [
11409            json!("08:00-18:00"),
11410            json!({"start": "08:00", "end": "18:00"}),
11411            json!(["08:00"]),
11412            json!([{"start": 800, "end": "18:00"}]),
11413        ] {
11414            assert!(
11415                !check_physical_action(&json!({"shiftWindows": ws}), &late).ok,
11416                "{ws}"
11417            );
11418        }
11419        // Native NaN in an action never passes a cap.
11420        let nan = PhysicalAction {
11421            force_n: Some(f64::NAN),
11422            ..Default::default()
11423        };
11424        assert!(!check_physical_action(&json!({"maxForceN": 10.0}), &nan).ok);
11425    }
11426
11427    #[test]
11428    fn malformed_child_fields_never_attenuate() {
11429        let parent = json!({
11430            "maxForceN": 80.0,
11431            "allowedZones": ["A", "B"],
11432            "shiftWindows": [{"start": "08:00", "end": "18:00"}]
11433        });
11434        let good = json!({
11435            "maxForceN": 50.0,
11436            "allowedZones": ["A"],
11437            "shiftWindows": [{"start": "09:00", "end": "17:00"}]
11438        });
11439        assert!(attenuates(&parent, &good));
11440        for (k, bad) in [
11441            ("shiftWindows", json!("00:00-23:59")),
11442            ("shiftWindows", json!({"start": "00:00"})),
11443            ("shiftWindows", json!([{"start": 0, "end": "23:59"}])),
11444            ("maxForceN", json!("50")),
11445            ("maxForceN", json!(null)),
11446            ("allowedZones", json!("A")),
11447            ("allowedZones", json!(["A", 7])),
11448            ("maxSpeedMps", json!("unlimited")),
11449        ] {
11450            let mut child = good.clone();
11451            child[k] = bad.clone();
11452            assert!(!attenuates(&parent, &child), "{k}={bad}");
11453        }
11454        // A malformed parent cap refuses rather than being skipped.
11455        assert!(!attenuates(&json!({"maxForceN": "80"}), &good));
11456    }
11457
11458    #[test]
11459    fn nan_wear_level_is_refused() {
11460        assert!(attenuate_for_wear(&json!({"maxForceN": 80.0}), f64::NAN).is_err());
11461        assert!(attenuate_for_wear(&json!({"maxForceN": 80.0}), 0.5).is_ok());
11462    }
11463}
11464
11465#[cfg(test)]
11466mod fork_check_tests {
11467    use super::*;
11468
11469    fn iso(offset: i64) -> String {
11470        // 2026-01-01T00:00:00Z plus offset seconds, offsets kept within one day.
11471        let s = offset.rem_euclid(86_400);
11472        let day = if offset < 0 { 31 } else { 1 };
11473        let month = if offset < 0 { "2025-12" } else { "2026-01" };
11474        format!(
11475            "{month}-{day:02}T{:02}:{:02}:{:02}Z",
11476            s / 3600,
11477            (s / 60) % 60,
11478            s % 60
11479        )
11480    }
11481
11482    fn emb(body: &str, start: i64, end: Option<i64>) -> Value {
11483        let mut e = json!({"credentialSubject": {"body": body}, "validFrom": iso(start)});
11484        if let Some(end) = end {
11485            e["validUntil"] = json!(iso(end));
11486        }
11487        e
11488    }
11489
11490    fn pairwise(windows: &[(String, i64, Option<i64>)]) -> (bool, Option<(String, String)>) {
11491        for (i, (bi, si, ei)) in windows.iter().enumerate() {
11492            for (bj, sj, ej) in &windows[i + 1..] {
11493                if bi == bj {
11494                    continue;
11495                }
11496                let a_before_b = ei.is_some_and(|e| e <= *sj);
11497                let b_before_a = ej.is_some_and(|e| e <= *si);
11498                if !(a_before_b || b_before_a) {
11499                    return (false, Some((bi.clone(), bj.clone())));
11500                }
11501            }
11502        }
11503        (true, None)
11504    }
11505
11506    fn run(list: &[Value]) -> (bool, Option<(String, String)>) {
11507        let (ok, conflict) = check_no_fork(list).unwrap();
11508        (ok, conflict.map(|c| (c.body_a, c.body_b)))
11509    }
11510
11511    #[test]
11512    fn fork_check_matches_the_shared_vector() {
11513        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11514            .join("../../test-vectors/robotics/fork_vector.json");
11515        let vector: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
11516        let cases = vector["cases"].as_array().unwrap();
11517        assert!(cases.len() > 40);
11518        for case in cases {
11519            let list = case["embodiments"].as_array().unwrap();
11520            let (ok, conflict) = check_no_fork(list).unwrap();
11521            let expected = &case["expected"];
11522            assert_eq!(ok, expected["ok"].as_bool().unwrap(), "{}", case["name"]);
11523            let got = conflict.map(|c| json!({"bodyA": c.body_a, "bodyB": c.body_b}));
11524            assert_eq!(got.as_ref(), expected.get("conflict"), "{}", case["name"]);
11525        }
11526    }
11527
11528    #[test]
11529    fn fork_check_matches_the_pairwise_scan_on_random_lists() {
11530        // A small fixed-seed generator keeps this free of extra dependencies.
11531        let mut state: u64 = 0x5eed_2026_1204;
11532        let mut next = |n: u64| {
11533            state = state
11534                .wrapping_mul(6364136223846793005)
11535                .wrapping_add(1442695040888963407);
11536            (state >> 33) % n
11537        };
11538        for _ in 0..3000 {
11539            let bodies = 1 + next(5);
11540            let len = next(15);
11541            let windows: Vec<(String, i64, Option<i64>)> = (0..len)
11542                .map(|_| {
11543                    let body = ((b'a' + next(bodies) as u8) as char).to_string();
11544                    let start = next(41) as i64;
11545                    let end = if next(100) < 15 {
11546                        None
11547                    } else {
11548                        Some(start + next(25) as i64 - 4)
11549                    };
11550                    (body, start, end)
11551                })
11552                .collect();
11553            let list: Vec<Value> = windows.iter().map(|(b, s, e)| emb(b, *s, *e)).collect();
11554            assert_eq!(run(&list), pairwise(&windows), "{windows:?}");
11555        }
11556    }
11557
11558    #[test]
11559    fn fork_check_handles_a_large_list_with_a_late_fork() {
11560        // Many overlapping windows on one body, then one other body overlapping
11561        // only the last of them: the pairwise scan needs about 2e8 steps here.
11562        let n = 20_000i64;
11563        let mut list: Vec<Value> = (0..n).map(|i| emb("body-a", i, Some(n + 5))).collect();
11564        list.push(emb("body-b", n + 4, Some(n + 6)));
11565        let began = std::time::Instant::now();
11566        assert_eq!(
11567            run(&list),
11568            (false, Some(("body-a".into(), "body-b".into())))
11569        );
11570        assert!(began.elapsed() < core::time::Duration::from_secs(10));
11571
11572        let clean: Vec<Value> = (0..n)
11573            .map(|i| {
11574                emb(
11575                    &format!("body-{i}"),
11576                    i,
11577                    if i + 1 < n { Some(i + 1) } else { None },
11578                )
11579            })
11580            .collect();
11581        let began = std::time::Instant::now();
11582        assert_eq!(run(&clean), (true, None));
11583        assert!(began.elapsed() < core::time::Duration::from_secs(10));
11584    }
11585
11586    #[test]
11587    fn fork_check_still_refuses_malformed_entries() {
11588        let good = emb("a", 0, Some(10));
11589        assert_eq!(
11590            run(&[good.clone(), json!({"validFrom": iso(0)})]),
11591            (false, None)
11592        );
11593        assert_eq!(
11594            run(&[good.clone(), json!({"credentialSubject": {"body": "b"}})]),
11595            (false, None)
11596        );
11597        let mut bad_end = emb("b", 0, None);
11598        bad_end["validUntil"] = json!("not a time");
11599        assert_eq!(run(&[good, bad_end]), (false, None));
11600    }
11601}