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
19use serde_json::{json, Map, Value};
20
21use crate::data_integrity::{self, BuildProofOptions};
22use crate::error::{CoreError, Result};
23use crate::keys;
24use crate::pq::{MlDsa44KeyPair, MLDSA44_PUBLIC_LEN};
25use crate::robotics_verify::{self as rv, Keys, VerifyOptions, Window};
26use crate::root_of_trust::{self, ACTION_ISSUE_ROBOT_IDENTITY};
27use crate::{hybrid, jcs, multikey};
28
29use aes_gcm::aead::{Aead, Payload};
30use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
31use base64::engine::general_purpose::URL_SAFE_NO_PAD;
32use base64::Engine;
33use sha2::{Digest, Sha256};
34use std::collections::HashSet;
35
36pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
37pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
38pub const ROBOT_IDENTITY_TYPE: &str = "RobotIdentityCredential";
39
40/// Multibase ('u') base64url-no-pad encoding, matching the Python/TS/Go `mb64`.
41pub(crate) fn mb64(bytes: &[u8]) -> String {
42    format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
43}
44
45/// Decode a multibase ('u') base64url-no-pad string.
46pub(crate) fn unmb64(s: &str) -> Result<Vec<u8>> {
47    let body = s
48        .strip_prefix('u')
49        .ok_or_else(|| CoreError::Json("expected multibase 'u' prefix".into()))?;
50    URL_SAFE_NO_PAD
51        .decode(body)
52        .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))
53}
54
55/// The canonical bytes a hardware root signs to bind a robot's identity key to
56/// its hardware: JCS of `{"key": robot_key_multibase, "robotDid": robot_did}`.
57pub fn robot_identity_binding(robot_did: &str, robot_key_multibase: &str) -> Vec<u8> {
58    jcs::canonicalize(&json!({
59        "key": robot_key_multibase,
60        "robotDid": robot_did,
61    }))
62}
63
64/// Parameters for [`mint_robot_identity`]. Timestamps are ISO-8601 strings the
65/// caller supplies. `attestation` is the hardware root's signature over
66/// [`robot_identity_binding`]; `root_public_multibase` is that root's public key.
67#[derive(Debug, Clone)]
68pub struct MintRobotIdentity {
69    pub robot_did: String,
70    pub make: String,
71    pub model: String,
72    pub serial: String,
73    pub owner: Option<String>,
74    pub root_kind: String,
75    pub root_public_multibase: String,
76    pub attestation: Vec<u8>,
77    /// Optional explicit lifecycle array; defaults to a single "commissioned" entry.
78    pub lifecycle: Option<Value>,
79    pub valid_from: String,
80    pub valid_until: Option<String>,
81}
82
83/// Mint a hardware-attested `RobotIdentityCredential`, signed by the robot's own
84/// Ed25519 seed. The hardware-root attestation is embedded as
85/// `credentialSubject.hardwareRoot.attestation`.
86pub fn mint_robot_identity(robot_seed: &[u8], params: &MintRobotIdentity) -> Result<Value> {
87    let lifecycle = params
88        .lifecycle
89        .clone()
90        .unwrap_or_else(|| json!([{ "event": "commissioned", "timestamp": params.valid_from }]));
91
92    let mut subject = Map::new();
93    subject.insert("id".into(), json!(params.robot_did));
94    subject.insert("make".into(), json!(params.make));
95    subject.insert("model".into(), json!(params.model));
96    subject.insert("serial".into(), json!(params.serial));
97    subject.insert(
98        "hardwareRoot".into(),
99        json!({
100            "kind": params.root_kind,
101            "publicKeyMultibase": params.root_public_multibase,
102            "attestation": mb64(&params.attestation),
103        }),
104    );
105    subject.insert("lifecycle".into(), lifecycle);
106    if let Some(owner) = &params.owner {
107        subject.insert("owner".into(), json!(owner));
108    }
109
110    let mut cred = Map::new();
111    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
112    cred.insert(
113        "type".into(),
114        json!(["VerifiableCredential", ROBOT_IDENTITY_TYPE]),
115    );
116    cred.insert("issuer".into(), json!(params.robot_did));
117    cred.insert("validFrom".into(), json!(params.valid_from));
118    if let Some(vu) = &params.valid_until {
119        cred.insert("validUntil".into(), json!(vu));
120    }
121    cred.insert("credentialSubject".into(), Value::Object(subject));
122
123    let opts = BuildProofOptions::new(
124        format!("{}#key-1", params.robot_did),
125        params.valid_from.clone(),
126    );
127    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
128}
129
130/// Verify a credential through the shared issuer-binding helper
131/// ([`crate::robotics_verify`]) at `now_iso`. Errors only on a malformed
132/// `now_iso`; any problem with the credential itself is `Ok(None)`.
133pub(crate) fn bound(
134    credential: &Value,
135    keys: Keys<'_>,
136    expected_type: &str,
137    now_iso: &str,
138    window: Window,
139) -> Result<Option<rv::Verified>> {
140    let now = rv::require_now(now_iso)?;
141    Ok(rv::verify_robotics_credential(
142        credential,
143        keys,
144        Some(expected_type),
145        now,
146        VerifyOptions::window(window),
147    )
148    .ok())
149}
150
151/// True when a self-attestation names its issuer as `credentialSubject.id`.
152pub(crate) fn issuer_is_subject(v: &rv::Verified) -> bool {
153    v.subject.get("id").and_then(|x| x.as_str()) == Some(v.issuer.as_str())
154}
155
156/// Verify a `RobotIdentityCredential`: the credential proof bound to the robot
157/// as issuer (which must also be `credentialSubject.id`), the validity window
158/// at `now_iso` (validFrom required), AND the hardware-root attestation binding
159/// the robot key to the hardware. `robot_keys` is a `{robot_did: key}` source
160/// (or, for a did:key robot, the bare key). When `hardware_root_key` is given,
161/// the credential's hardware-root key must be exactly that key. Returns the
162/// credentialSubject on success, `None` if invalid.
163pub fn verify_robot_identity(
164    credential: &Value,
165    robot_keys: Keys<'_>,
166    hardware_root_key: Option<&[u8]>,
167    now_iso: &str,
168) -> Result<Option<Value>> {
169    let v = match bound(
170        credential,
171        robot_keys,
172        ROBOT_IDENTITY_TYPE,
173        now_iso,
174        Window::FromRequired,
175    )? {
176        Some(v) if issuer_is_subject(&v) => v,
177        _ => return Ok(None),
178    };
179    let robot_key =
180        match rv::resolve_issuer_key(&v.issuer, rv::pin_if_keyless(robot_keys, Some(&v.issuer))) {
181            Ok(k) => k,
182            Err(_) => return Ok(None),
183        };
184    let subject = match v.subject.as_object() {
185        Some(s) => s,
186        None => return Ok(None),
187    };
188    let hw = match subject.get("hardwareRoot").and_then(|h| h.as_object()) {
189        Some(h) => h,
190        None => return Ok(None),
191    };
192    let hw_mb = match hw.get("publicKeyMultibase").and_then(|v| v.as_str()) {
193        Some(s) => s,
194        None => return Ok(None),
195    };
196    let attestation_mb = match hw.get("attestation").and_then(|v| v.as_str()) {
197        Some(s) => s,
198        None => return Ok(None),
199    };
200
201    let decoded = match multikey::decode(hw_mb) {
202        Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => d,
203        _ => return Ok(None),
204    };
205    if let Some(pin) = hardware_root_key {
206        if pin != decoded.raw_key.as_slice() {
207            return Ok(None);
208        }
209    }
210    let attestation = match unmb64(attestation_mb) {
211        Ok(a) => a,
212        Err(_) => return Ok(None),
213    };
214
215    let robot_key_mb = multikey::encode_ed25519_public(&robot_key)?;
216    let binding = robot_identity_binding(&v.issuer, &robot_key_mb);
217
218    if !matches!(
219        keys::verify(&decoded.raw_key, &binding, &attestation),
220        Ok(true)
221    ) {
222        return Ok(None);
223    }
224    Ok(Some(v.subject))
225}
226
227// ---------------------------------------------------------------------------
228// Root of Trust for robot identity (Phase 5.1, authority binding)
229// ---------------------------------------------------------------------------
230//
231// Byte-exact port of the Python reference `vouch/robotics/root_identity.py`.
232//
233// The Root of Trust for Machine Identity lets one pinned Vouch root recognize
234// issuers, and a recognized issuer bind a subject DID to attributes, verified
235// offline against that one pinned root. This extends it to robots. A recognized
236// manufacturer (an issuer the root granted the `issueRobotIdentity` action)
237// issues an identity that binds a robot's DID and its hardware-rooted key to
238// attributes such as make, model, serial, and owner. The robot separately holds
239// a hardware-attested `RobotIdentityCredential` proving its key is bound to a
240// secure element.
241//
242// [`verify_robot_identity_chain`] closes the loop: from one pinned root a
243// verifier confirms both that the robot is a legitimate robot from a recognized
244// manufacturer (the authority chain via [`root_of_trust::verify_identity_chain`])
245// and that the key the manufacturer vouched for is genuinely hardware-rooted (the
246// secure-element attestation via [`verify_robot_identity`]), and that the two
247// name the same robot and the same key. It follows the anchor-once model and the
248// reason-code style of the underlying root_of_trust.
249
250/// Outcome of [`verify_robot_identity_chain`].
251///
252/// `ok` is true only if the authority chain verified against the pinned root AND
253/// the robot's own credential names the same robot and the vouched key.
254/// `hardware_rooted` is true only when the manufacturer also bound the
255/// hardware-root key and the attestation was made by exactly that key. On failure `reason`
256/// carries a structured code matching the Python reference exactly.
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct RobotIdentityChainResult {
259    pub ok: bool,
260    pub reason: Option<String>,
261    pub robot_did: Option<String>,
262    pub issuer_did: Option<String>,
263    pub root_did: Option<String>,
264    pub attributes: Option<Value>,
265    pub hardware_rooted: bool,
266}
267
268impl RobotIdentityChainResult {
269    /// A failure result carrying the reason code and the pinned root that was in
270    /// force when the check failed.
271    fn fail(reason: impl Into<String>, root_did: &str) -> Self {
272        Self {
273            ok: false,
274            reason: Some(reason.into()),
275            robot_did: None,
276            issuer_did: None,
277            root_did: Some(root_did.to_string()),
278            attributes: None,
279            hardware_rooted: false,
280        }
281    }
282}
283
284/// Issue an authority robot identity: a recognized manufacturer binds `robot_did`,
285/// its hardware-rooted key (`hardware_key_multibase`, the robot's Ed25519 key as a
286/// multikey), and identity `attributes` (make, model, serial, owner). The
287/// manufacturer (derived from `issuer_seed`) must be a recognized issuer for the
288/// `issueRobotIdentity` action.
289///
290/// The credential is an `AgentIdentityCredential` so the shared identity-chain
291/// verification applies, with a `kind` of "robot" and the hardware key carried in
292/// the bound identity attributes.
293///
294/// `hardware_root_key_multibase` is the public key of the robot's secure element
295/// as the manufacturer recorded it. Bound as `hardwareRootKey`, it lets a
296/// verifier tell the robot's hardware attestation comes from that exact
297/// hardware; without it the chain verifies but is never hardware-rooted.
298#[allow(clippy::too_many_arguments)]
299pub fn build_robot_identity(
300    issuer_seed: &[u8],
301    robot_did: &str,
302    hardware_key_multibase: &str,
303    attributes: &Value,
304    valid_seconds: i64,
305    valid_from: &str,
306    created: &str,
307    credential_status: Option<Value>,
308    credential_id: &str,
309    hardware_root_key_multibase: Option<&str>,
310) -> Result<Value> {
311    if robot_did.is_empty() {
312        return Err(CoreError::Json("robot_did is required".into()));
313    }
314    if hardware_key_multibase.is_empty() {
315        return Err(CoreError::Json("hardware_key_multibase is required".into()));
316    }
317    let bound = match attributes.as_object() {
318        Some(o) if !o.is_empty() => {
319            let mut m = o.clone();
320            m.insert("kind".into(), json!("robot"));
321            m.insert("hardwareKey".into(), json!(hardware_key_multibase));
322            if let Some(root) = hardware_root_key_multibase {
323                if root.is_empty() {
324                    return Err(CoreError::Json(
325                        "hardware_root_key_multibase must be a multikey string".into(),
326                    ));
327                }
328                m.insert("hardwareRootKey".into(), json!(root));
329            }
330            Value::Object(m)
331        }
332        _ => {
333            return Err(CoreError::Json(
334                "attributes must be a non-empty object".into(),
335            ))
336        }
337    };
338    root_of_trust::build_agent_identity(
339        issuer_seed,
340        robot_did,
341        &bound,
342        valid_seconds,
343        valid_from,
344        created,
345        credential_status,
346        credential_id,
347    )
348}
349
350/// Verify a robot's identity against a single pinned Vouch root, confirming both
351/// provenance and hardware-rooting.
352///
353/// From `trusted_root`, the pinned root DID:
354///
355///   1. The authority chain: the recognized manufacturer must be recognized by
356///      the pinned root for the `issueRobotIdentity` action, and the authority
357///      identity must be signed by that manufacturer (shared identity-chain verify).
358///   2. The vouched key: the authority identity must carry a hardware key.
359///   3. The robot credential: the robot's own `RobotIdentityCredential` must
360///      verify under the key the manufacturer vouched for, name the same robot,
361///      and carry a valid secure-element attestation.
362///   4. The hardware root: when the manufacturer bound a `hardwareRootKey`, the
363///      attestation's hardware key must be exactly that key (else
364///      `hardware_root_mismatch`), and only then is `hardware_rooted` true.
365///
366/// `robot_public_key` is the robot's raw 32-byte Ed25519 public key. `now_iso` is
367/// the current instant used for the temporal window; `clock_skew_seconds` is the
368/// allowed drift. Reason codes on failure match the Python reference exactly.
369#[allow(clippy::too_many_arguments)]
370pub fn verify_robot_identity_chain(
371    authority_identity: &Value,
372    recognized_issuer_credential: &Value,
373    robot_hardware_credential: &Value,
374    trusted_root: &str,
375    robot_public_key: &[u8],
376    root_credential: Option<&Value>,
377    now_iso: &str,
378    clock_skew_seconds: i64,
379) -> RobotIdentityChainResult {
380    let chain = root_of_trust::verify_identity_chain(
381        authority_identity,
382        recognized_issuer_credential,
383        trusted_root,
384        root_credential,
385        None,
386        ACTION_ISSUE_ROBOT_IDENTITY,
387        now_iso,
388        clock_skew_seconds,
389    );
390    if !chain.ok {
391        return RobotIdentityChainResult {
392            ok: false,
393            reason: chain.reason,
394            robot_did: None,
395            issuer_did: None,
396            root_did: Some(trusted_root.to_string()),
397            attributes: None,
398            hardware_rooted: false,
399        };
400    }
401
402    let attributes = match &chain.attributes {
403        Some(v @ Value::Object(_)) => v.clone(),
404        _ => json!({}),
405    };
406    let hardware_key = match attributes.get("hardwareKey").and_then(|v| v.as_str()) {
407        Some(s) if !s.is_empty() => s.to_string(),
408        _ => return RobotIdentityChainResult::fail("identity_no_hardware_key", trusted_root),
409    };
410
411    // The robot's own credential must verify under the supplied key, accepted
412    // for whatever DID the credential names; the next two checks pin that DID
413    // to the manufacturer's subject and the key to the vouched key.
414    let any_did = |_: &str| Some(robot_public_key.to_vec());
415    let hw_subject = match verify_robot_identity(
416        robot_hardware_credential,
417        Keys::Resolver(&any_did),
418        None,
419        now_iso,
420    ) {
421        Ok(Some(s)) => s,
422        _ => return RobotIdentityChainResult::fail("hardware_root_invalid", trusted_root),
423    };
424    if hw_subject.get("id").and_then(|v| v.as_str()) != chain.agent_did.as_deref() {
425        return RobotIdentityChainResult::fail("hardware_subject_mismatch", trusted_root);
426    }
427
428    let robot_key_mb = match multikey::encode_ed25519_public(robot_public_key) {
429        Ok(mb) => mb,
430        Err(_) => return RobotIdentityChainResult::fail("hardware_key_unresolvable", trusted_root),
431    };
432    if robot_key_mb != hardware_key {
433        return RobotIdentityChainResult::fail("hardware_key_mismatch", trusted_root);
434    }
435
436    // Hardware-rooted only when the manufacturer bound the hardware-root key and
437    // the robot's attestation was made by exactly that key.
438    let mut hardware_rooted = false;
439    if let Some(pinned) = attributes.get("hardwareRootKey") {
440        let claimed = hw_subject
441            .get("hardwareRoot")
442            .and_then(|h| h.get("publicKeyMultibase"))
443            .and_then(|v| v.as_str());
444        if pinned.as_str().is_none() || claimed != pinned.as_str() {
445            return RobotIdentityChainResult::fail("hardware_root_mismatch", trusted_root);
446        }
447        hardware_rooted = true;
448    }
449
450    RobotIdentityChainResult {
451        ok: true,
452        reason: None,
453        robot_did: chain.agent_did,
454        issuer_did: chain.issuer_did,
455        root_did: Some(trusted_root.to_string()),
456        attributes: Some(attributes),
457        hardware_rooted,
458    }
459}
460
461// ---------------------------------------------------------------------------
462// Model and config provenance (Phase 5.2)
463// ---------------------------------------------------------------------------
464
465pub const MODEL_PROVENANCE_TYPE: &str = "ModelProvenanceAttestation";
466
467/// Multibase SHA-256 of the JCS-canonical config object. Python, TypeScript, Go,
468/// and Rust all canonicalize identically, so the digest is the same byte string
469/// in every language.
470pub fn config_hash(config: &Value) -> String {
471    let digest = Sha256::digest(jcs::canonicalize(config));
472    mb64(&digest)
473}
474
475/// Parameters for [`build_provenance_attestation`]. The issuer is the signer (the
476/// robot itself or an authority); `robot_did` names the robot the attestation is
477/// about.
478#[derive(Debug, Clone)]
479pub struct BuildProvenance {
480    pub issuer_did: String,
481    pub robot_did: String,
482    pub model_name: String,
483    pub weights_hash: String,
484    pub safety_policy: String,
485    pub config: Option<Value>,
486    pub version: Option<String>,
487    pub supersedes: Option<String>,
488    pub valid_from: String,
489    pub valid_until: Option<String>,
490}
491
492/// Build a signed `ModelProvenanceAttestation` for the software on a robot.
493pub fn build_provenance_attestation(signer_seed: &[u8], params: &BuildProvenance) -> Result<Value> {
494    let mut vla = Map::new();
495    vla.insert("modelName".into(), json!(params.model_name));
496    vla.insert("weightsHash".into(), json!(params.weights_hash));
497    vla.insert("safetyPolicy".into(), json!(params.safety_policy));
498    if let Some(v) = &params.version {
499        vla.insert("version".into(), json!(v));
500    }
501    if let Some(cfg) = &params.config {
502        vla.insert("configHash".into(), json!(config_hash(cfg)));
503    }
504
505    let mut subject = Map::new();
506    subject.insert("id".into(), json!(params.robot_did));
507    subject.insert("vla".into(), Value::Object(vla));
508    if let Some(s) = &params.supersedes {
509        subject.insert("supersedes".into(), json!(s));
510    }
511
512    let mut cred = Map::new();
513    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
514    cred.insert(
515        "type".into(),
516        json!(["VerifiableCredential", MODEL_PROVENANCE_TYPE]),
517    );
518    cred.insert("issuer".into(), json!(params.issuer_did));
519    cred.insert("validFrom".into(), json!(params.valid_from));
520    if let Some(vu) = &params.valid_until {
521        cred.insert("validUntil".into(), json!(vu));
522    }
523    cred.insert("credentialSubject".into(), Value::Object(subject));
524
525    let opts = BuildProofOptions::new(
526        format!("{}#key-1", params.issuer_did),
527        params.valid_from.clone(),
528    );
529    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
530}
531
532/// Verify a `ModelProvenanceAttestation`. When `config` is supplied, also check
533/// the recorded configHash reproduces. Returns the subject on success, `None`
534/// otherwise.
535pub fn verify_provenance_attestation(
536    attestation: &Value,
537    keys: Keys<'_>,
538    config: Option<&Value>,
539    now_iso: &str,
540) -> Result<Option<Value>> {
541    let v = match bound(
542        attestation,
543        keys,
544        MODEL_PROVENANCE_TYPE,
545        now_iso,
546        Window::FromRequired,
547    )? {
548        Some(v) => v,
549        None => return Ok(None),
550    };
551    if let Some(cfg) = config {
552        let want = config_hash(cfg);
553        let got = v
554            .subject
555            .get("vla")
556            .and_then(|v| v.as_object())
557            .and_then(|v| v.get("configHash"))
558            .and_then(|v| v.as_str());
559        if got != Some(want.as_str()) {
560            return Ok(None);
561        }
562    }
563    Ok(Some(v.subject))
564}
565
566/// The reference a superseding attestation uses: multibase SHA-256 of the JCS
567/// form of the whole signed attestation (proof included).
568pub fn provenance_attestation_id(attestation: &Value) -> String {
569    mb64(&Sha256::digest(jcs::canonicalize(attestation)))
570}
571
572/// Verify an ordered OTA history of provenance attestations for `robot_did`:
573/// every attestation verifies and is about `robot_did`; each one after the
574/// first names the previous by [`provenance_attestation_id`] as `supersedes`
575/// and is dated no earlier. Each earlier attestation must still have been valid
576/// when the next was made, and the last at `now_iso`. Returns the latest
577/// subject on success.
578pub fn verify_provenance_chain(
579    attestations: &[Value],
580    keys: Keys<'_>,
581    robot_did: &str,
582    now_iso: &str,
583) -> Result<Option<Value>> {
584    rv::require_now(now_iso)?;
585    if attestations.is_empty() || robot_did.is_empty() {
586        return Ok(None);
587    }
588    let mut prev: Option<&Value> = None;
589    let mut latest = None;
590    for (i, att) in attestations.iter().enumerate() {
591        let at: String = match attestations.get(i + 1) {
592            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
593                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
594                _ => return Ok(None),
595            },
596            None => now_iso.to_string(),
597        };
598        let subject = match verify_provenance_attestation(att, keys, None, &at)? {
599            Some(s) if s.get("id").and_then(|v| v.as_str()) == Some(robot_did) => s,
600            _ => return Ok(None),
601        };
602        if let Some(p) = prev {
603            if subject.get("supersedes").and_then(|v| v.as_str())
604                != Some(provenance_attestation_id(p).as_str())
605            {
606                return Ok(None);
607            }
608            if rv::time_ns(att.get("validFrom")) < rv::time_ns(p.get("validFrom")) {
609                return Ok(None);
610            }
611        }
612        prev = Some(att);
613        latest = Some(subject);
614    }
615    Ok(latest)
616}
617
618// ---------------------------------------------------------------------------
619// Physical capability scope (Phase 5.3)
620// ---------------------------------------------------------------------------
621
622pub const PHYSICAL_SCOPE_TYPE: &str = "PhysicalCapabilityScope";
623
624/// An allowed time-of-day window, "HH:MM" start and end.
625#[derive(Debug, Clone)]
626pub struct ShiftWindow {
627    pub start: String,
628    pub end: String,
629}
630
631/// A proposed actuation to check against a scope. `None` numerics mean "not
632/// specified" (a meaningful zero is still `Some(0.0)`).
633#[derive(Debug, Clone, Default)]
634pub struct PhysicalAction {
635    pub force_n: Option<f64>,
636    pub speed_mps: Option<f64>,
637    pub near_humans: bool,
638    pub zone: Option<String>,
639    pub time_hm: Option<String>,
640}
641
642/// The outcome of [`check_physical_action`].
643#[derive(Debug, Clone)]
644pub struct CheckResult {
645    pub ok: bool,
646    pub reasons: Vec<String>,
647}
648
649/// Parameters for [`build_physical_scope_credential`]. The issuer is the signer
650/// (a fleet authority); `subject_did` is the robot the scope is granted to.
651#[derive(Debug, Clone, Default)]
652pub struct BuildPhysicalScope {
653    pub issuer_did: String,
654    pub subject_did: String,
655    pub max_force_n: Option<f64>,
656    pub max_speed_mps: Option<f64>,
657    pub max_speed_near_humans_mps: Option<f64>,
658    pub allowed_zones: Option<Vec<String>>,
659    pub shift_windows: Option<Vec<ShiftWindow>>,
660    pub valid_from: String,
661    pub valid_until: Option<String>,
662}
663
664/// Build a signed `PhysicalCapabilityScope` credential.
665pub fn build_physical_scope_credential(
666    signer_seed: &[u8],
667    params: &BuildPhysicalScope,
668) -> Result<Value> {
669    let mut scope = Map::new();
670    if let Some(v) = params.max_force_n {
671        scope.insert("maxForceN".into(), json!(v));
672    }
673    if let Some(v) = params.max_speed_mps {
674        scope.insert("maxSpeedMps".into(), json!(v));
675    }
676    if let Some(v) = params.max_speed_near_humans_mps {
677        scope.insert("maxSpeedNearHumansMps".into(), json!(v));
678    }
679    if let Some(zones) = &params.allowed_zones {
680        scope.insert("allowedZones".into(), json!(zones));
681    }
682    if let Some(ws) = &params.shift_windows {
683        let arr: Vec<Value> = ws
684            .iter()
685            .map(|w| json!({"start": w.start, "end": w.end}))
686            .collect();
687        scope.insert("shiftWindows".into(), Value::Array(arr));
688    }
689
690    let mut subject = Map::new();
691    subject.insert("id".into(), json!(params.subject_did));
692    subject.insert("physicalScope".into(), Value::Object(scope));
693
694    let mut cred = Map::new();
695    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
696    cred.insert(
697        "type".into(),
698        json!(["VerifiableCredential", PHYSICAL_SCOPE_TYPE]),
699    );
700    cred.insert("issuer".into(), json!(params.issuer_did));
701    cred.insert("validFrom".into(), json!(params.valid_from));
702    if let Some(vu) = &params.valid_until {
703        cred.insert("validUntil".into(), json!(vu));
704    }
705    cred.insert("credentialSubject".into(), Value::Object(subject));
706
707    let opts = BuildProofOptions::new(
708        format!("{}#key-1", params.issuer_did),
709        params.valid_from.clone(),
710    );
711    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
712}
713
714/// The numeric caps a physical scope may set.
715pub const CAP_KEYS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
716/// Every dimension a physical scope may set.
717pub const SCOPE_KEYS: [&str; 5] = [
718    "maxForceN",
719    "maxSpeedMps",
720    "maxSpeedNearHumansMps",
721    "allowedZones",
722    "shiftWindows",
723];
724
725/// Minutes since midnight for a strict `HH:MM` string (00:00-23:59), else `None`.
726pub fn parse_hm(value: &str) -> Option<u32> {
727    let b = value.as_bytes();
728    if b.len() != 5
729        || b[2] != b':'
730        || !b
731            .iter()
732            .enumerate()
733            .all(|(i, c)| i == 2 || c.is_ascii_digit())
734    {
735        return None;
736    }
737    let h = u32::from(b[0] - b'0') * 10 + u32::from(b[1] - b'0');
738    let m = u32::from(b[3] - b'0') * 10 + u32::from(b[4] - b'0');
739    if h > 23 || m > 59 {
740        return None;
741    }
742    Some(h * 60 + m)
743}
744
745/// A usable physical cap: a finite, non-negative JSON number (never a boolean).
746pub fn valid_cap(v: &Value) -> bool {
747    v.is_number() && v.as_f64().is_some_and(|n| n.is_finite() && n >= 0.0)
748}
749
750/// `(start, end)` minutes of a `{"start", "end"}` window with start <= end.
751pub fn parse_window(w: &Value) -> Option<(u32, u32)> {
752    let o = w.as_object()?;
753    let start = parse_hm(o.get("start")?.as_str()?)?;
754    let end = parse_hm(o.get("end")?.as_str()?)?;
755    (start <= end).then_some((start, end))
756}
757
758/// Every window of a list, or `None` if the list or any window is malformed.
759pub fn parse_windows(v: &Value) -> Option<Vec<(u32, u32)>> {
760    v.as_array()?.iter().map(parse_window).collect()
761}
762
763/// The zone ids of a list of strings, or `None` if malformed.
764pub fn parse_zones(v: &Value) -> Option<Vec<&str>> {
765    v.as_array()?.iter().map(|z| z.as_str()).collect()
766}
767
768/// Reasons the scope itself cannot be read; empty when every set dimension is
769/// well-formed.
770pub fn scope_problems(scope: &Value) -> Vec<String> {
771    let o = match scope.as_object() {
772        Some(o) => o,
773        None => return vec!["scope_malformed: not an object".into()],
774    };
775    let mut problems = Vec::new();
776    for key in CAP_KEYS {
777        if o.get(key).is_some_and(|v| !valid_cap(v)) {
778            problems.push(format!(
779                "scope_malformed: {key} is not a finite non-negative number"
780            ));
781        }
782    }
783    if o.get("allowedZones")
784        .is_some_and(|v| parse_zones(v).is_none())
785    {
786        problems.push("scope_malformed: allowedZones is not a list of strings".into());
787    }
788    if o.get("shiftWindows")
789        .is_some_and(|v| parse_windows(v).is_none())
790    {
791        problems.push("scope_malformed: shiftWindows is not a list of HH:MM windows".into());
792    }
793    problems
794}
795
796/// Verify a `PhysicalCapabilityScope` credential and return its physicalScope:
797/// the proof bound to the issuer, the window at `now_iso` (validFrom
798/// required), a well-formed scope with no unknown dimension (a misspelt cap
799/// would otherwise limit nothing), and (when given) the subject `subject_did`.
800pub fn verify_physical_scope_credential(
801    credential: &Value,
802    keys: Keys<'_>,
803    subject_did: Option<&str>,
804    now_iso: &str,
805) -> Result<Option<Value>> {
806    let v = match bound(
807        credential,
808        keys,
809        PHYSICAL_SCOPE_TYPE,
810        now_iso,
811        Window::FromRequired,
812    )? {
813        Some(v) => v,
814        None => return Ok(None),
815    };
816    if subject_did.is_some_and(|d| v.subject.get("id").and_then(|x| x.as_str()) != Some(d)) {
817        return Ok(None);
818    }
819    let scope = match v.subject.get("physicalScope") {
820        Some(sc @ Value::Object(o)) if o.keys().all(|k| SCOPE_KEYS.contains(&k.as_str())) => sc,
821        _ => return Ok(None),
822    };
823    if !scope_problems(scope).is_empty() {
824        return Ok(None);
825    }
826    Ok(Some(scope.clone()))
827}
828
829/// Check a proposed physical action against a physical scope object, returning
830/// ok plus a reason for each violation. A scope dimension that is set but
831/// malformed, and an action value that is not a finite non-negative number or
832/// not a strict `HH:MM`, are violations. An empty zone or shift-window list
833/// allows nothing. Near humans, the speed cap is the lower of `maxSpeedMps`
834/// and `maxSpeedNearHumansMps`.
835pub fn check_physical_action(scope: &Value, action: &PhysicalAction) -> CheckResult {
836    let mut reasons = scope_problems(scope);
837    if !reasons.is_empty() {
838        return CheckResult { ok: false, reasons };
839    }
840    let o = scope
841        .as_object()
842        .expect("scope_problems checked it is an object");
843    for (name, value) in [("force_n", action.force_n), ("speed_mps", action.speed_mps)] {
844        if let Some(v) = value {
845            if !v.is_finite() || v < 0.0 {
846                reasons.push(format!(
847                    "action_malformed: {name} is not a finite non-negative number"
848                ));
849            }
850        }
851    }
852    if !reasons.is_empty() {
853        return CheckResult { ok: false, reasons };
854    }
855    let cap = |k: &str| o.get(k).and_then(|v| v.as_f64());
856
857    if let (Some(force), Some(c)) = (action.force_n, cap("maxForceN")) {
858        if force > c {
859            reasons.push(format!("force_exceeded: {force}N > {c}N"));
860        }
861    }
862    if let Some(speed) = action.speed_mps {
863        let mut c = cap("maxSpeedMps");
864        if action.near_humans {
865            if let Some(near) = cap("maxSpeedNearHumansMps") {
866                c = Some(c.map_or(near, |g| g.min(near)));
867            }
868        }
869        if let Some(c) = c {
870            if speed > c {
871                let label = if action.near_humans {
872                    "near_humans "
873                } else {
874                    ""
875                };
876                reasons.push(format!("{label}speed_exceeded: {speed} m/s > {c} m/s"));
877            }
878        }
879    }
880    if let (Some(zone), Some(zones)) = (&action.zone, o.get("allowedZones").and_then(parse_zones)) {
881        if !zones.contains(&zone.as_str()) {
882            reasons.push(format!("zone_not_allowed: {zone}"));
883        }
884    }
885    if let (Some(hm), Some(ws)) = (&action.time_hm, o.get("shiftWindows")) {
886        match parse_hm(hm) {
887            None => reasons.push(format!("action_malformed: time_hm {hm:?} is not HH:MM")),
888            Some(t) => {
889                let windows = parse_windows(ws).unwrap_or_default();
890                if !windows.iter().any(|(s, e)| *s <= t && t <= *e) {
891                    reasons.push(format!("outside_shift_window: {hm}"));
892                }
893            }
894        }
895    }
896    CheckResult {
897        ok: reasons.is_empty(),
898        reasons,
899    }
900}
901
902/// Report whether `child` is a valid attenuation of `parent`: never broader on
903/// any physical dimension. Both scopes must be well-formed; for every dimension
904/// the parent sets, the child must set it too and be no broader (a cap no
905/// higher, a NON-EMPTY subset of zones, a NON-EMPTY list of windows each inside
906/// some parent window). Leaving a dimension out, or an empty list, is never an
907/// attenuation of a parent that limits it.
908pub fn attenuates(parent: &Value, child: &Value) -> bool {
909    if !scope_problems(parent).is_empty() || !scope_problems(child).is_empty() {
910        return false;
911    }
912    let (p, c) = match (parent.as_object(), child.as_object()) {
913        (Some(p), Some(c)) => (p, c),
914        _ => return false,
915    };
916    for key in CAP_KEYS {
917        if let Some(pv) = p.get(key).and_then(|v| v.as_f64()) {
918            match c.get(key).and_then(|v| v.as_f64()) {
919                Some(cv) if cv <= pv => {}
920                _ => return false,
921            }
922        }
923    }
924    if let Some(pz) = p.get("allowedZones").and_then(parse_zones) {
925        match c.get("allowedZones").and_then(parse_zones) {
926            Some(cz) if !cz.is_empty() && cz.iter().all(|z| pz.contains(z)) => {}
927            _ => return false,
928        }
929    }
930    if let Some(pw) = p.get("shiftWindows").and_then(parse_windows) {
931        match c.get("shiftWindows").and_then(parse_windows) {
932            Some(cw) if !cw.is_empty() => {
933                for (cs, ce) in cw {
934                    if !pw.iter().any(|(ps, pe)| *ps <= cs && ce <= *pe) {
935                        return false;
936                    }
937                }
938            }
939            _ => return false,
940        }
941    }
942    true
943}
944
945// ---------------------------------------------------------------------------
946// Robot-to-robot trust handshake (Phase 5.4)
947// ---------------------------------------------------------------------------
948
949pub const HELLO: &str = "handshake_hello";
950pub const ACCEPT: &str = "handshake_accept";
951pub const CONFIRM: &str = "handshake_confirm";
952
953/// Decides whether a peer DID is trusted: its did:web or did:webvh name must
954/// be allowed, or `accept_unknown` is set. The name is the domain plus any
955/// path, colon-joined (`did:web:a.example:agents` is `a.example:agents`), so a
956/// bare-domain entry trusts the bare domain only and a path is trusted only
957/// when the policy names it.
958#[derive(Debug, Clone, Default)]
959pub struct TrustPolicy {
960    pub trusted_domains: HashSet<String>,
961    pub accept_unknown: bool,
962}
963
964impl TrustPolicy {
965    pub fn new(domains: impl IntoIterator<Item = String>, accept_unknown: bool) -> Self {
966        Self {
967            trusted_domains: domains.into_iter().collect(),
968            accept_unknown,
969        }
970    }
971
972    pub fn is_trusted(&self, did: &str) -> bool {
973        if self.accept_unknown {
974            return true;
975        }
976        match did_web_domain(did) {
977            Some(d) => self.trusted_domains.contains(&d),
978            None => false,
979        }
980    }
981}
982
983/// The agreed cooperation session after a successful handshake.
984#[derive(Debug, Clone)]
985pub struct BoundedSession {
986    pub session_id: String,
987    pub initiator: String,
988    pub responder: String,
989    pub scope: Vec<String>,
990    pub nonce: String,
991    pub valid_until: Option<String>,
992}
993
994/// The name a did:web or did:webvh DID is trusted under, or None: the domain,
995/// then each path segment after a colon. Each prefix keeps its trailing colon,
996/// so a did:webvh DID never reads as did:web. A did:webvh DID is parsed
997/// strictly ([`crate::did_webvh::parse`]) and gives its host (percent-decoded
998/// and lower-cased) and its percent-decoded path; one that does not parse has
999/// no name. A did:web with an empty segment has no name.
1000fn did_web_domain(did: &str) -> Option<String> {
1001    if crate::did_webvh::is_did_webvh(did) {
1002        return crate::did_webvh::parse(did).ok().map(|parsed| {
1003            std::iter::once(parsed.host)
1004                .chain(parsed.path)
1005                .collect::<Vec<_>>()
1006                .join(":")
1007        });
1008    }
1009    let rest = did.strip_prefix("did:web:")?;
1010    if rest.split(':').any(str::is_empty) {
1011        None
1012    } else {
1013        Some(rest.to_string())
1014    }
1015}
1016
1017/// Parameters for [`build_hello`]. `nonce` and `issued_at` are caller-supplied so
1018/// the core stays deterministic; the wrapper SDKs generate them.
1019#[derive(Debug, Clone, Default)]
1020pub struct BuildHello {
1021    pub from_did: String,
1022    pub proposed_scope: Vec<String>,
1023    pub nonce: String,
1024    pub peer_did: Option<String>,
1025    pub issued_at: String,
1026}
1027
1028/// Open the handshake (initiator A): a proposed scope and a fresh nonce, signed.
1029pub fn build_hello(signer_seed: &[u8], params: &BuildHello) -> Result<Value> {
1030    let mut hello = Map::new();
1031    hello.insert("type".into(), json!(HELLO));
1032    hello.insert("from".into(), json!(params.from_did));
1033    hello.insert(
1034        "to".into(),
1035        match &params.peer_did {
1036            Some(p) => json!(p),
1037            None => Value::Null,
1038        },
1039    );
1040    hello.insert("nonce".into(), json!(params.nonce));
1041    hello.insert("proposedScope".into(), json!(params.proposed_scope));
1042    hello.insert("issuedAt".into(), json!(params.issued_at));
1043    let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), &params.issued_at);
1044    data_integrity::sign(&Value::Object(hello), signer_seed, &opts)
1045}
1046
1047/// The default clock skew for handshake freshness checks (seconds).
1048pub const DEFAULT_HANDSHAKE_SKEW_SECONDS: i64 = 30;
1049/// The oldest HELLO a responder answers (seconds).
1050pub const DEFAULT_MAX_HELLO_AGE_SECONDS: i64 = 300;
1051/// The longest session an ACCEPT may grant (validUntil - issuedAt).
1052pub const DEFAULT_MAX_SESSION_SECONDS: i64 = 3600;
1053
1054/// The message is `expected_type` and its proof is bound to the DID in `from`
1055/// (assertionMethod, verification method of that DID, key resolved from it).
1056fn handshake_message_ok(obj: &Value, keys: Keys<'_>, expected_type: &str) -> bool {
1057    if obj.get("type").and_then(|v| v.as_str()) != Some(expected_type) {
1058        return false;
1059    }
1060    if rv::input_too_large(obj, rv::MAX_CREDENTIAL_BYTES).is_some() {
1061        return false;
1062    }
1063    let sender = match obj.get("from").and_then(|v| v.as_str()) {
1064        Some(s) if s.starts_with("did:") => s,
1065        _ => return false,
1066    };
1067    if rv::proof_unbound_reason(obj.get("proof").unwrap_or(&Value::Null), sender).is_some() {
1068        return false;
1069    }
1070    // The handshake binds each message to the DID in `from`; whether that
1071    // party is trusted is the policy's decision (or the caller's own HELLO or
1072    // ACCEPT pins it), so `from` is the pinned issuer here.
1073    let key = match rv::resolve_issuer_key(sender, rv::pin_if_keyless(keys, Some(sender))) {
1074        Ok(k) => k,
1075        Err(_) => return false,
1076    };
1077    matches!(data_integrity::verify_proof(obj, &key), Ok(true))
1078}
1079
1080fn scope_list(v: Option<&Value>) -> Option<Vec<String>> {
1081    v?.as_array()?
1082        .iter()
1083        .map(|x| x.as_str().map(String::from))
1084        .collect()
1085}
1086
1087fn issued_recently(v: Option<&Value>, now_ns: i128, skew: i64, max_age: i64) -> bool {
1088    let issued = match rv::time_ns(v) {
1089        Some(t) => t,
1090        None => return false,
1091    };
1092    let second: i128 = 1_000_000_000;
1093    now_ns - i128::from(max_age.saturating_add(skew)) * second <= issued
1094        && issued <= now_ns + i128::from(skew) * second
1095}
1096
1097impl BoundedSession {
1098    /// True while `now_iso` is at or before the session's validUntil (required).
1099    pub fn is_current(&self, now_iso: &str) -> bool {
1100        match (
1101            self.valid_until
1102                .as_deref()
1103                .and_then(|u| crate::time::parse_protocol_time_ns(u).ok()),
1104            crate::time::parse_protocol_time_ns(now_iso).ok(),
1105        ) {
1106            (Some(u), Some(n)) => n <= u,
1107            _ => false,
1108        }
1109    }
1110}
1111
1112/// Parameters for [`build_accept`]. `issued_at` is the responder's clock (it
1113/// also judges the HELLO's age); `valid_until` bounds the session.
1114#[derive(Debug, Clone, Default)]
1115pub struct BuildAccept {
1116    pub from_did: String,
1117    pub offered_scope: Vec<String>,
1118    pub session_id: String,
1119    pub valid_until: String,
1120    pub created: String,
1121}
1122
1123/// Verify A's HELLO, check A's domain, intersect the scope, and sign an
1124/// acceptance (responder B). The HELLO's proof must be bound to its `from` DID
1125/// (`hello_keys` is a `{did: key}` source, or the bare key of a did:key
1126/// initiator); it must be addressed to this responder (`to` unset or this
1127/// responder's DID) and its `issuedAt` within [`DEFAULT_MAX_HELLO_AGE_SECONDS`]
1128/// (plus [`DEFAULT_HANDSHAKE_SKEW_SECONDS`]) of `params.created`. The trust
1129/// policy is applied to the verified `from`. The ACCEPT carries `issuedAt`.
1130pub fn build_accept(
1131    signer_seed: &[u8],
1132    hello: &Value,
1133    hello_keys: Keys<'_>,
1134    policy: &TrustPolicy,
1135    params: &BuildAccept,
1136) -> Result<Value> {
1137    build_accept_with(
1138        signer_seed,
1139        hello,
1140        hello_keys,
1141        policy,
1142        params,
1143        HandshakeLimits::default(),
1144    )
1145}
1146
1147/// The time limits of the handshake: the clock skew allowed either way, the
1148/// oldest HELLO (for [`build_accept_with`]) or ACCEPT (for
1149/// [`verify_accept_with`]) accepted, and the longest session an ACCEPT may
1150/// grant.
1151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1152pub struct HandshakeLimits {
1153    pub clock_skew_seconds: i64,
1154    pub max_age_seconds: i64,
1155    pub max_session_seconds: i64,
1156}
1157
1158impl Default for HandshakeLimits {
1159    fn default() -> Self {
1160        Self {
1161            clock_skew_seconds: DEFAULT_HANDSHAKE_SKEW_SECONDS,
1162            max_age_seconds: DEFAULT_MAX_HELLO_AGE_SECONDS,
1163            max_session_seconds: DEFAULT_MAX_SESSION_SECONDS,
1164        }
1165    }
1166}
1167
1168impl HandshakeLimits {
1169    fn check(&self) -> Result<()> {
1170        if !(0..=120).contains(&self.clock_skew_seconds) {
1171            return Err(CoreError::Json(
1172                "clock skew must be between 0 and 120 seconds".into(),
1173            ));
1174        }
1175        if self.max_age_seconds < 0 || self.max_session_seconds < 1 {
1176            return Err(CoreError::Json(
1177                "handshake age and session limits must be positive".into(),
1178            ));
1179        }
1180        Ok(())
1181    }
1182}
1183
1184/// [`build_accept`] with the caller's [`HandshakeLimits`].
1185pub fn build_accept_with(
1186    signer_seed: &[u8],
1187    hello: &Value,
1188    hello_keys: Keys<'_>,
1189    policy: &TrustPolicy,
1190    params: &BuildAccept,
1191    limits: HandshakeLimits,
1192) -> Result<Value> {
1193    limits.check()?;
1194    let now = rv::require_now(&params.created)?;
1195    if !handshake_message_ok(hello, hello_keys, HELLO) {
1196        return Err(CoreError::Json(
1197            "HELLO is not signed by the DID it is from".into(),
1198        ));
1199    }
1200    match hello.get("to") {
1201        None | Some(Value::Null) => {}
1202        Some(Value::String(t)) if *t == params.from_did => {}
1203        _ => return Err(CoreError::Json("HELLO is addressed to another node".into())),
1204    }
1205    if !issued_recently(
1206        hello.get("issuedAt"),
1207        now,
1208        limits.clock_skew_seconds,
1209        limits.max_age_seconds,
1210    ) {
1211        return Err(CoreError::Json(
1212            "HELLO is stale, from the future, or has no valid issuedAt".into(),
1213        ));
1214    }
1215    let proposed = scope_list(hello.get("proposedScope"));
1216    let nonce = hello
1217        .get("nonce")
1218        .and_then(|v| v.as_str())
1219        .filter(|n| !n.is_empty());
1220    let (proposed, nonce) = match (proposed, nonce) {
1221        (Some(p), Some(n)) => (p, n),
1222        _ => return Err(CoreError::Json("HELLO is malformed".into())),
1223    };
1224    let initiator = hello.get("from").and_then(|v| v.as_str()).unwrap_or("");
1225    if !policy.is_trusted(initiator) {
1226        return Err(CoreError::Json(format!(
1227            "peer {initiator} is not in this trust domain's policy"
1228        )));
1229    }
1230    if rv::time_ns(Some(&json!(params.valid_until))).is_none_or(|u| u <= now) {
1231        return Err(CoreError::Json(
1232            "valid_until must be a protocol time after created".into(),
1233        ));
1234    }
1235
1236    let offered: HashSet<&str> = params.offered_scope.iter().map(|s| s.as_str()).collect();
1237    let mut bounded: Vec<String> = proposed
1238        .into_iter()
1239        .filter(|s| offered.contains(s.as_str()))
1240        .collect::<HashSet<_>>()
1241        .into_iter()
1242        .collect();
1243    bounded.sort();
1244
1245    let mut accept = Map::new();
1246    accept.insert("type".into(), json!(ACCEPT));
1247    accept.insert("from".into(), json!(params.from_did));
1248    accept.insert("to".into(), json!(initiator));
1249    accept.insert("sessionId".into(), json!(params.session_id));
1250    accept.insert("nonce".into(), json!(nonce));
1251    accept.insert("boundedScope".into(), json!(bounded));
1252    accept.insert("issuedAt".into(), json!(params.created));
1253    accept.insert("validUntil".into(), json!(params.valid_until));
1254    let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), &params.created);
1255    data_integrity::sign(&Value::Object(accept), signer_seed, &opts)
1256}
1257
1258/// Verify B's ACCEPT against the HELLO that A sent (initiator A). The ACCEPT's
1259/// proof must be bound to its `from` DID; it must be addressed to A (`to` ==
1260/// the HELLO's `from`), come from the node the HELLO was addressed to (a HELLO
1261/// addressed to nobody needs a `policy` that trusts the responder), echo the
1262/// HELLO's nonce (and `expected_nonce` when given), carry a bounded scope that
1263/// is a subset of what A proposed, and not have expired at `now_iso`.
1264pub fn verify_accept(
1265    accept: &Value,
1266    accept_keys: Keys<'_>,
1267    hello: &Value,
1268    expected_nonce: Option<&str>,
1269    policy: Option<&TrustPolicy>,
1270    now_iso: &str,
1271) -> Result<Option<BoundedSession>> {
1272    verify_accept_with(
1273        accept,
1274        accept_keys,
1275        hello,
1276        expected_nonce,
1277        policy,
1278        HandshakeLimits::default(),
1279        now_iso,
1280    )
1281}
1282
1283/// [`verify_accept`] with the caller's [`HandshakeLimits`].
1284pub fn verify_accept_with(
1285    accept: &Value,
1286    accept_keys: Keys<'_>,
1287    hello: &Value,
1288    expected_nonce: Option<&str>,
1289    policy: Option<&TrustPolicy>,
1290    limits: HandshakeLimits,
1291    now_iso: &str,
1292) -> Result<Option<BoundedSession>> {
1293    limits.check()?;
1294    let now = rv::require_now(now_iso)?;
1295    if !hello.is_object() || !handshake_message_ok(accept, accept_keys, ACCEPT) {
1296        return Ok(None);
1297    }
1298    let responder = accept
1299        .get("from")
1300        .and_then(|v| v.as_str())
1301        .unwrap_or("")
1302        .to_string();
1303    if accept.get("to") != hello.get("from") {
1304        return Ok(None);
1305    }
1306    match hello.get("to") {
1307        Some(Value::String(t)) if *t != responder => return Ok(None),
1308        Some(Value::String(_)) => {}
1309        _ if policy.is_none() => return Ok(None),
1310        _ => {}
1311    }
1312    if let Some(p) = policy {
1313        if !p.is_trusted(&responder) {
1314            return Ok(None);
1315        }
1316    }
1317    let nonce = match accept.get("nonce").and_then(|v| v.as_str()) {
1318        Some(n) if Some(n) == hello.get("nonce").and_then(|v| v.as_str()) => n.to_string(),
1319        _ => return Ok(None),
1320    };
1321    if expected_nonce.is_some_and(|e| e != nonce) {
1322        return Ok(None);
1323    }
1324    let (bounded, proposed) = match (
1325        scope_list(accept.get("boundedScope")),
1326        scope_list(hello.get("proposedScope")),
1327    ) {
1328        (Some(b), Some(p)) if b.iter().all(|x| p.contains(x)) => (b, p),
1329        _ => return Ok(None),
1330    };
1331    let _ = proposed;
1332    let sid = match non_empty_str(accept, "sessionId") {
1333        Some(s) => s.to_string(),
1334        None => return Ok(None),
1335    };
1336    let session = BoundedSession {
1337        session_id: sid,
1338        initiator: accept
1339            .get("to")
1340            .and_then(|v| v.as_str())
1341            .unwrap_or("")
1342            .to_string(),
1343        responder,
1344        scope: bounded,
1345        nonce,
1346        valid_until: accept
1347            .get("validUntil")
1348            .and_then(|v| v.as_str())
1349            .map(String::from),
1350    };
1351    if !session.is_current(now_iso) {
1352        return Ok(None);
1353    }
1354    // issuedAt is required: no older than the HELLO age limit, not ahead of
1355    // the clock beyond the skew, and the session it grants is bounded.
1356    if !issued_recently(
1357        accept.get("issuedAt"),
1358        now,
1359        limits.clock_skew_seconds,
1360        limits.max_age_seconds,
1361    ) {
1362        return Ok(None);
1363    }
1364    match (
1365        rv::time_ns(accept.get("issuedAt")),
1366        rv::time_ns(accept.get("validUntil")),
1367    ) {
1368        (Some(i), Some(u))
1369            if u > i && u - i <= i128::from(limits.max_session_seconds) * 1_000_000_000 => {}
1370        _ => return Ok(None),
1371    }
1372    Ok(Some(session))
1373}
1374
1375/// Sign A's confirmation of the bounded session to B. Refuses an expired
1376/// session (checked at `created`).
1377pub fn build_confirm(
1378    signer_seed: &[u8],
1379    from_did: &str,
1380    session: &BoundedSession,
1381    created: &str,
1382) -> Result<Value> {
1383    rv::require_now(created)?;
1384    if !session.is_current(created) {
1385        return Err(CoreError::Json("the session has expired".into()));
1386    }
1387    let mut confirm = Map::new();
1388    confirm.insert("type".into(), json!(CONFIRM));
1389    confirm.insert("from".into(), json!(from_did));
1390    confirm.insert("to".into(), json!(session.responder));
1391    confirm.insert("sessionId".into(), json!(session.session_id));
1392    confirm.insert("nonce".into(), json!(session.nonce));
1393    confirm.insert("acceptedScope".into(), json!(session.scope));
1394    let opts = BuildProofOptions::new(format!("{from_did}#key-1"), created);
1395    data_integrity::sign(&Value::Object(confirm), signer_seed, &opts)
1396}
1397
1398/// Verify A's CONFIRM closes the session B accepted (responder B). `accept` is
1399/// the ACCEPT B sent. The CONFIRM's proof must be bound to its `from` DID,
1400/// which must be the initiator (the ACCEPT's `to`); it must be addressed to
1401/// B, name the same session and nonce, accept a scope within the bounded
1402/// scope, and arrive while the session is still valid at `now_iso`.
1403pub fn verify_confirm(
1404    confirm: &Value,
1405    confirm_keys: Keys<'_>,
1406    accept: &Value,
1407    now_iso: &str,
1408) -> Result<bool> {
1409    let now = rv::require_now(now_iso)?;
1410    if !accept.is_object() || !handshake_message_ok(confirm, confirm_keys, CONFIRM) {
1411        return Ok(false);
1412    }
1413    if confirm.get("from") != accept.get("to") || confirm.get("to") != accept.get("from") {
1414        return Ok(false);
1415    }
1416    if confirm.get("sessionId") != accept.get("sessionId")
1417        || confirm.get("nonce") != accept.get("nonce")
1418    {
1419        return Ok(false);
1420    }
1421    match (
1422        scope_list(confirm.get("acceptedScope")),
1423        scope_list(accept.get("boundedScope")),
1424    ) {
1425        (Some(a), Some(b)) if a.iter().all(|x| b.contains(x)) => {}
1426        _ => return Ok(false),
1427    }
1428    Ok(rv::time_ns(accept.get("validUntil")).is_some_and(|u| now <= u))
1429}
1430
1431// ---------------------------------------------------------------------------
1432// Black box and kill switch (Phase 5.5)
1433// ---------------------------------------------------------------------------
1434
1435/// Version 1.1 entries bind their header (every field but the ciphertext and
1436/// the hash) into AES-GCM as associated data; 1.0 entries do not.
1437pub const BLACKBOX_VERSION: &str = "1.1";
1438/// The pre-1.1 entry version, still opened (without associated data).
1439pub const BLACKBOX_LEGACY_VERSION: &str = "1.0";
1440/// A signed black-box head: entry count plus last hash.
1441pub const BLACKBOX_HEAD_TYPE: &str = "BlackBoxHeadCredential";
1442/// Size cap for a log handed to a verifier (before canonicalization).
1443pub const MAX_LOG_BYTES: usize = 64 * 1024 * 1024;
1444pub const KILLSWITCH_TYPE: &str = "KillSwitchCredential";
1445pub const EMERGENCY_STOP: &str = "emergency_stop";
1446
1447/// The prevHash of the first entry: multibase of 32 zero bytes.
1448pub fn genesis_prev_hash() -> String {
1449    mb64(&[0u8; 32])
1450}
1451
1452/// The entry header bound into AES-GCM: JCS of every field but the ciphertext
1453/// and the entry hash.
1454fn entry_aad(entry: &Map<String, Value>) -> Vec<u8> {
1455    let mut header = entry.clone();
1456    header.remove("ciphertext");
1457    header.remove("entryHash");
1458    jcs::canonicalize(&Value::Object(header))
1459}
1460
1461fn entry_hash(body: &Map<String, Value>) -> Result<String> {
1462    let mut clean = body.clone();
1463    clean.remove("entryHash");
1464    let canonical = jcs::canonicalize(&Value::Object(clean));
1465    Ok(mb64(&Sha256::digest(canonical)))
1466}
1467
1468/// Build one black-box entry statelessly: encrypt `payload` under `key`, link it
1469/// to `prev_hash` at `seq`, and return the entry with its `entryHash`. The
1470/// stateful [`BlackBoxLog`] and the FFI layer both build on this. The encrypted
1471/// blob is nonce(12) || ciphertext || tag(16).
1472pub fn blackbox_append_entry(
1473    key: &[u8],
1474    seq: u64,
1475    event: &str,
1476    payload: &Value,
1477    timestamp: &str,
1478    prev_hash: &str,
1479) -> Result<Value> {
1480    blackbox_append_entry_with_nonce(key, seq, event, payload, timestamp, prev_hash, None)
1481}
1482
1483/// [`blackbox_append_entry`] with the host's own 12-byte AES-GCM nonce (a
1484/// host with its own random source or a secure element). A nonce must never
1485/// be used twice under one key; without one the core draws a random nonce.
1486pub fn blackbox_append_entry_with_nonce(
1487    key: &[u8],
1488    seq: u64,
1489    event: &str,
1490    payload: &Value,
1491    timestamp: &str,
1492    prev_hash: &str,
1493    host_nonce: Option<&[u8]>,
1494) -> Result<Value> {
1495    if key.len() != 32 {
1496        return Err(CoreError::Crypto(
1497            "black box key must be 32 bytes (AES-256)".into(),
1498        ));
1499    }
1500    let mut nonce = [0u8; 12];
1501    match host_nonce {
1502        Some(n) if n.len() == 12 => nonce.copy_from_slice(n),
1503        Some(_) => return Err(CoreError::Crypto("black box nonce must be 12 bytes".into())),
1504        None => {
1505            getrandom::getrandom(&mut nonce).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?
1506        }
1507    }
1508    let plaintext = jcs::canonicalize(payload);
1509    let mut body = Map::new();
1510    body.insert("version".into(), json!(BLACKBOX_VERSION));
1511    body.insert("seq".into(), json!(seq));
1512    body.insert("timestamp".into(), json!(timestamp));
1513    body.insert("event".into(), json!(event));
1514    body.insert("prevHash".into(), json!(prev_hash));
1515    let aad = entry_aad(&body);
1516    let cipher =
1517        Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
1518    let ct = cipher
1519        .encrypt(
1520            Nonce::from_slice(&nonce),
1521            Payload {
1522                msg: plaintext.as_ref(),
1523                aad: &aad,
1524            },
1525        )
1526        .map_err(|e| CoreError::Crypto(format!("encrypt: {e}")))?;
1527    let mut blob = Vec::with_capacity(nonce.len() + ct.len());
1528    blob.extend_from_slice(&nonce);
1529    blob.extend_from_slice(&ct);
1530    body.insert("ciphertext".into(), json!(mb64(&blob)));
1531    let h = entry_hash(&body)?;
1532    body.insert("entryHash".into(), json!(h));
1533    Ok(Value::Object(body))
1534}
1535
1536/// An append-only, AES-256-GCM-encrypted, JCS hash-linked event log. The key is
1537/// 32 bytes. The encrypted blob is nonce(12) || ciphertext || tag(16), matching
1538/// Python, TypeScript, and Go.
1539pub struct BlackBoxLog {
1540    key: Vec<u8>,
1541    genesis: String,
1542    entries: Vec<Value>,
1543    head: String,
1544}
1545
1546impl BlackBoxLog {
1547    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
1548    pub fn new(key: &[u8], genesis_prev_hash_override: Option<&str>) -> Result<Self> {
1549        if key.len() != 32 {
1550            return Err(CoreError::Crypto(
1551                "black box key must be 32 bytes (AES-256)".into(),
1552            ));
1553        }
1554        let genesis = genesis_prev_hash_override
1555            .map(String::from)
1556            .unwrap_or_else(genesis_prev_hash);
1557        Ok(Self {
1558            key: key.to_vec(),
1559            head: genesis.clone(),
1560            genesis,
1561            entries: Vec::new(),
1562        })
1563    }
1564
1565    /// Encrypt `payload`, link it to the chain head, and return the new entry.
1566    pub fn append(&mut self, event: &str, payload: &Value, timestamp: &str) -> Result<Value> {
1567        let entry = blackbox_append_entry(
1568            &self.key,
1569            self.entries.len() as u64,
1570            event,
1571            payload,
1572            timestamp,
1573            &self.head,
1574        )?;
1575        self.head = entry
1576            .get("entryHash")
1577            .and_then(|v| v.as_str())
1578            .unwrap_or("")
1579            .to_string();
1580        self.entries.push(entry.clone());
1581        Ok(entry)
1582    }
1583
1584    pub fn head(&self) -> &str {
1585        &self.head
1586    }
1587
1588    pub fn genesis(&self) -> &str {
1589        &self.genesis
1590    }
1591
1592    pub fn entries(&self) -> &[Value] {
1593        &self.entries
1594    }
1595
1596    /// The number of entries, the count a signed head carries.
1597    pub fn count(&self) -> usize {
1598        self.entries.len()
1599    }
1600
1601    pub fn open(&self, entry: &Value) -> Result<Value> {
1602        open_entry(entry, &self.key)
1603    }
1604}
1605
1606/// Decrypt a black-box entry payload with the log key.
1607pub fn open_entry(entry: &Value, key: &[u8]) -> Result<Value> {
1608    let obj = entry
1609        .as_object()
1610        .ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
1611    let ct_mb = obj
1612        .get("ciphertext")
1613        .and_then(|v| v.as_str())
1614        .ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
1615    // 1.1 entries open with their header as associated data, so a changed
1616    // label, time, sequence number or link fails to decrypt. 1.0 entries were
1617    // written before the header was bound and open without it.
1618    let aad = match obj.get("version").and_then(|v| v.as_str()) {
1619        Some(BLACKBOX_VERSION) => entry_aad(obj),
1620        Some(BLACKBOX_LEGACY_VERSION) => Vec::new(),
1621        other => {
1622            return Err(CoreError::Json(format!(
1623                "unsupported black-box entry version {other:?}"
1624            )))
1625        }
1626    };
1627    let blob = unmb64(ct_mb)?;
1628    if blob.len() < 12 + 16 {
1629        return Err(CoreError::Crypto("ciphertext too short".into()));
1630    }
1631    let cipher =
1632        Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
1633    let (nonce, rest) = blob.split_at(12);
1634    let pt = cipher
1635        .decrypt(
1636            Nonce::from_slice(nonce),
1637            Payload {
1638                msg: rest,
1639                aad: &aad,
1640            },
1641        )
1642        .map_err(|_| CoreError::Crypto("decryption failed".into()))?;
1643    serde_json::from_slice(&pt).map_err(|e| CoreError::Json(format!("payload decode: {e}")))
1644}
1645
1646/// The outcome of [`verify_blackbox_chain`].
1647#[derive(Debug, Clone)]
1648pub struct ChainResult {
1649    pub ok: bool,
1650    pub reason: Option<String>,
1651}
1652
1653/// Verify the hash chain over the (still-encrypted) entries. Tamper-evident
1654/// without the key. A `None` genesis uses [`genesis_prev_hash`].
1655pub fn verify_blackbox_chain(
1656    entries: &[Value],
1657    genesis_prev_hash_override: Option<&str>,
1658) -> ChainResult {
1659    verify_blackbox_chain_capped(entries, genesis_prev_hash_override, MAX_LOG_BYTES)
1660}
1661
1662/// [`verify_blackbox_chain`] with the host's size limit for the log.
1663pub fn verify_blackbox_chain_capped(
1664    entries: &[Value],
1665    genesis_prev_hash_override: Option<&str>,
1666    max_bytes: usize,
1667) -> ChainResult {
1668    let mut progress = ChainProgress::start(genesis_prev_hash_override);
1669    verify_chain_segment(&mut progress, entries, max_bytes);
1670    progress.result()
1671}
1672
1673/// Where a hash-chain check stands after the first entries of a log: the
1674/// number the next entry must carry, the hash it must link to, and the first
1675/// failure. A long log is checked one segment at a time by passing this from
1676/// one [`verify_chain_segment`] call to the next, so memory stays bounded by
1677/// one segment however long the log is. The verdict is the one
1678/// [`verify_blackbox_chain`] gives for the whole log.
1679#[derive(Debug, Clone, PartialEq, Eq)]
1680pub struct ChainProgress {
1681    /// The prevHash of entry 0.
1682    pub genesis: String,
1683    /// The number of entries checked so far (the next entry's seq).
1684    pub next_seq: u64,
1685    /// The entryHash of the last entry checked, or the genesis.
1686    pub last_hash: String,
1687    /// The first failure; once set, later segments are not read.
1688    pub failure: Option<String>,
1689}
1690
1691impl ChainProgress {
1692    /// The start of a log. A `None` genesis uses [`genesis_prev_hash`].
1693    pub fn start(genesis_prev_hash_override: Option<&str>) -> Self {
1694        let genesis = genesis_prev_hash_override
1695            .map(String::from)
1696            .unwrap_or_else(genesis_prev_hash);
1697        Self {
1698            last_hash: genesis.clone(),
1699            genesis,
1700            next_seq: 0,
1701            failure: None,
1702        }
1703    }
1704
1705    /// The verdict over every entry checked so far.
1706    pub fn result(&self) -> ChainResult {
1707        ChainResult {
1708            ok: self.failure.is_none(),
1709            reason: self.failure.clone(),
1710        }
1711    }
1712}
1713
1714/// The reason a segment of log entries nests too deeply or is larger than
1715/// `max_bytes`, measured as [`rv::input_too_large`] measures the same entries
1716/// in one list, without copying them.
1717fn entries_too_large(entries: &[Value], max_bytes: usize) -> Option<String> {
1718    use crate::attenuation::json_nesting_exceeds;
1719    if entries
1720        .iter()
1721        .any(|e| json_nesting_exceeds(e, rv::MAX_NESTING - 1))
1722    {
1723        return Some(format!("input nests more than {} levels", rv::MAX_NESTING));
1724    }
1725    let mut total = 2 + entries.len();
1726    for e in entries {
1727        if total > max_bytes {
1728            break;
1729        }
1730        total += rv::approx_size(e, max_bytes - total);
1731    }
1732    if total > max_bytes {
1733        return Some(format!("input larger than {max_bytes} bytes"));
1734    }
1735    None
1736}
1737
1738/// Check the next `entries` of a log (one segment) and move `progress` past
1739/// them. Every hash-linked log (black box, safety ledger, perception log)
1740/// verifies through here, whole or in segments.
1741pub fn verify_chain_segment(progress: &mut ChainProgress, entries: &[Value], max_bytes: usize) {
1742    if progress.failure.is_some() {
1743        return;
1744    }
1745    if let Some(big) = entries_too_large(entries, max_bytes) {
1746        progress.failure = Some(big);
1747        return;
1748    }
1749    for entry in entries {
1750        let i = progress.next_seq;
1751        let obj = match entry.as_object() {
1752            Some(o) => o,
1753            None => {
1754                progress.failure = Some(format!("entry {i} is not an object"));
1755                return;
1756            }
1757        };
1758        if entry.get("seq").and_then(|v| v.as_u64()) != Some(i) {
1759            progress.failure = Some(format!("entry {i} seq mismatch"));
1760            return;
1761        }
1762        if entry.get("prevHash").and_then(|v| v.as_str()).unwrap_or("") != progress.last_hash {
1763            progress.failure = Some(format!("entry {i} prevHash does not link"));
1764            return;
1765        }
1766        let want = match entry_hash(obj) {
1767            Ok(w) => w,
1768            Err(_) => {
1769                progress.failure = Some(format!("entry {i} hash error"));
1770                return;
1771            }
1772        };
1773        let eh = entry
1774            .get("entryHash")
1775            .and_then(|v| v.as_str())
1776            .unwrap_or("");
1777        if eh != want {
1778            progress.failure = Some(format!("entry {i} entryHash mismatch (tampered)"));
1779            return;
1780        }
1781        // A resumed state can carry any number; one past u64::MAX is no seq.
1782        let Some(next) = progress.next_seq.checked_add(1) else {
1783            progress.failure = Some(format!("entry {i} seq mismatch"));
1784            return;
1785        };
1786        progress.last_hash = want;
1787        progress.next_seq = next;
1788    }
1789}
1790
1791/// The end of a segmented check against a signed head: the same verdict
1792/// [`verify_chain_against_head`] gives for the whole log.
1793pub fn finish_chain_against_head(
1794    progress: &ChainProgress,
1795    head: Option<&Value>,
1796    count: Option<&Value>,
1797) -> ChainResult {
1798    if progress.failure.is_some() {
1799        return progress.result();
1800    }
1801    let fail = |r: String| ChainResult {
1802        ok: false,
1803        reason: Some(r),
1804    };
1805    let n = match count.and_then(|c| rv::strict_int(Some(c))) {
1806        Some(n) if n >= 0 => n,
1807        _ => return fail("anchored count is not a non-negative integer".into()),
1808    };
1809    if i128::from(progress.next_seq) != i128::from(n) {
1810        return fail(format!(
1811            "log has {} entries, the signed head says {n}",
1812            progress.next_seq
1813        ));
1814    }
1815    if head.and_then(|h| h.as_str()) != Some(progress.last_hash.as_str()) {
1816        return fail("log does not end at the signed head".into());
1817    }
1818    ChainResult {
1819        ok: true,
1820        reason: None,
1821    }
1822}
1823
1824/// Parameters for [`build_killswitch_credential`].
1825#[derive(Debug, Clone, Default)]
1826pub struct BuildKillswitch {
1827    pub issuer_did: String,
1828    pub target: String,
1829    pub reason: String,
1830    pub command: Option<String>,
1831    pub scope: Option<Vec<String>>,
1832    pub valid_from: String,
1833    pub valid_until: Option<String>,
1834}
1835
1836/// Build a signed `KillSwitchCredential` proving who issued an emergency stop.
1837pub fn build_killswitch_credential(
1838    authority_seed: &[u8],
1839    params: &BuildKillswitch,
1840) -> Result<Value> {
1841    let command = params
1842        .command
1843        .clone()
1844        .unwrap_or_else(|| EMERGENCY_STOP.to_string());
1845    let mut subject = Map::new();
1846    subject.insert("id".into(), json!(params.target));
1847    subject.insert("command".into(), json!(command));
1848    subject.insert("reason".into(), json!(params.reason));
1849    subject.insert("issuedBy".into(), json!(params.issuer_did));
1850    if let Some(scope) = &params.scope {
1851        subject.insert("scope".into(), json!(scope));
1852    }
1853
1854    let mut cred = Map::new();
1855    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1856    cred.insert(
1857        "type".into(),
1858        json!(["VerifiableCredential", KILLSWITCH_TYPE]),
1859    );
1860    cred.insert("issuer".into(), json!(params.issuer_did));
1861    cred.insert("validFrom".into(), json!(params.valid_from));
1862    if let Some(vu) = &params.valid_until {
1863        cred.insert("validUntil".into(), json!(vu));
1864    }
1865    cred.insert("credentialSubject".into(), Value::Object(subject));
1866
1867    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
1868    data_integrity::sign(&Value::Object(cred), authority_seed, &opts)
1869}
1870
1871/// Verify a `KillSwitchCredential`. When `trusted_authorities` is supplied, the
1872/// issuer DID MUST be in it. Returns the subject on success.
1873pub fn verify_killswitch_credential(
1874    credential: &Value,
1875    keys: Keys<'_>,
1876    trusted_authorities: Option<&HashSet<String>>,
1877    now_iso: &str,
1878) -> Result<Option<Value>> {
1879    let now = rv::require_now(now_iso)?;
1880    let opts = VerifyOptions {
1881        trusted_issuers: trusted_authorities,
1882        ..VerifyOptions::window(Window::FromRequired)
1883    };
1884    let v = match rv::verify_robotics_credential(credential, keys, Some(KILLSWITCH_TYPE), now, opts)
1885    {
1886        Ok(v) => v,
1887        Err(_) => return Ok(None),
1888    };
1889    // issuedBy, when present, must be the bound issuer.
1890    if let Some(by) = v.subject.get("issuedBy") {
1891        if by.as_str() != Some(v.issuer.as_str()) {
1892            return Ok(None);
1893        }
1894    }
1895    Ok(Some(v.subject))
1896}
1897
1898/// Verify the hash links AND that the log ends at a known head: `head` and
1899/// `count` come from something signed (a head credential, a safety-record
1900/// summary, a perception attestation). A log cut short, extended or rebuilt
1901/// does not end at that head with that many entries.
1902pub fn verify_chain_against_head(
1903    entries: &[Value],
1904    head: Option<&Value>,
1905    count: Option<&Value>,
1906    genesis_prev_hash_override: Option<&str>,
1907) -> ChainResult {
1908    verify_chain_against_head_capped(
1909        entries,
1910        head,
1911        count,
1912        genesis_prev_hash_override,
1913        MAX_LOG_BYTES,
1914    )
1915}
1916
1917/// [`verify_chain_against_head`] with the host's size limit for the log.
1918pub fn verify_chain_against_head_capped(
1919    entries: &[Value],
1920    head: Option<&Value>,
1921    count: Option<&Value>,
1922    genesis_prev_hash_override: Option<&str>,
1923    max_bytes: usize,
1924) -> ChainResult {
1925    let mut progress = ChainProgress::start(genesis_prev_hash_override);
1926    verify_chain_segment(&mut progress, entries, max_bytes);
1927    finish_chain_against_head(&progress, head, count)
1928}
1929
1930/// Sign the head of a black-box log (entry count plus last hash). The robot is
1931/// the issuer and the subject.
1932pub fn build_blackbox_head(
1933    robot_seed: &[u8],
1934    robot_did: &str,
1935    head: &str,
1936    entry_count: u64,
1937    valid_from: &str,
1938    valid_until: Option<&str>,
1939) -> Result<Value> {
1940    let mut cred = Map::new();
1941    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1942    cred.insert(
1943        "type".into(),
1944        json!(["VerifiableCredential", BLACKBOX_HEAD_TYPE]),
1945    );
1946    cred.insert("issuer".into(), json!(robot_did));
1947    cred.insert("validFrom".into(), json!(valid_from));
1948    if let Some(vu) = valid_until {
1949        cred.insert("validUntil".into(), json!(vu));
1950    }
1951    cred.insert(
1952        "credentialSubject".into(),
1953        json!({"id": robot_did, "logHead": head, "entryCount": entry_count}),
1954    );
1955    let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), valid_from);
1956    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
1957}
1958
1959/// Verify a log against the robot's signed head: the head credential must
1960/// verify bound to the robot as issuer and subject, and the log must link and
1961/// end at the signed head with exactly the signed number of entries.
1962pub fn verify_blackbox_head(
1963    credential: &Value,
1964    robot_keys: Keys<'_>,
1965    entries: &[Value],
1966    genesis_prev_hash_override: Option<&str>,
1967    now_iso: &str,
1968) -> Result<ChainResult> {
1969    let mut progress = ChainProgress::start(genesis_prev_hash_override);
1970    verify_chain_segment(&mut progress, entries, MAX_LOG_BYTES);
1971    finish_chain_against_head_credential(credential, robot_keys, &progress, now_iso)
1972}
1973
1974/// The end of a segmented check against the robot's signed head credential:
1975/// the same verdict [`verify_blackbox_head`] gives for the whole log.
1976pub fn finish_chain_against_head_credential(
1977    credential: &Value,
1978    robot_keys: Keys<'_>,
1979    progress: &ChainProgress,
1980    now_iso: &str,
1981) -> Result<ChainResult> {
1982    let now = rv::require_now(now_iso)?;
1983    let v = match rv::verify_robotics_credential(
1984        credential,
1985        robot_keys,
1986        Some(BLACKBOX_HEAD_TYPE),
1987        now,
1988        VerifyOptions::window(Window::FromRequired),
1989    ) {
1990        Ok(v) => v,
1991        Err(r) => {
1992            return Ok(ChainResult {
1993                ok: false,
1994                reason: Some(r),
1995            })
1996        }
1997    };
1998    if !issuer_is_subject(&v) {
1999        return Ok(ChainResult {
2000            ok: false,
2001            reason: Some("head is not issued by the robot it describes".into()),
2002        });
2003    }
2004    Ok(finish_chain_against_head(
2005        progress,
2006        v.subject.get("logHead"),
2007        v.subject.get("entryCount"),
2008    ))
2009}
2010
2011// ---------------------------------------------------------------------------
2012// Halos safety-evidence recorder (NVIDIA Halos integration)
2013// ---------------------------------------------------------------------------
2014//
2015// Byte-exact port of the Python reference `vouch/robotics/halos.py`.
2016//
2017// Halos certifies that a robot's stack is functionally safe and secure by design.
2018// It does not, on its own, produce a verifiable record of what a specific robot
2019// did or bind that record to the robot's identity. This is the evidence layer
2020// under a Halos-certified stack: the robot seals its black-box chain head and
2021// entry count into a signed `HalosSafetyEvidenceCredential` that binds them to its
2022// identity, to the Halos stack elements it ran on, and to a time window. A
2023// verifier that holds the credential and the entries confirms, without the
2024// black-box key, that the record is unaltered, was not truncated or extended since
2025// it was sealed, and is attributable to that robot. This composes the existing
2026// black-box and credential primitives and adds no new cryptography.
2027
2028pub const HALOS_SAFETY_EVIDENCE_TYPE: &str = "HalosSafetyEvidenceCredential";
2029
2030/// Format Unix epoch seconds as "YYYY-MM-DDTHH:MM:SSZ" for a whole-second UTC
2031/// instant. Howard Hinnant's civil-from-days algorithm, matching the rest of the
2032/// core so a `valid_seconds` lifetime renders identically across languages.
2033fn halos_epoch_to_iso(epoch: i64) -> String {
2034    let days = epoch.div_euclid(86400);
2035    let secs = epoch.rem_euclid(86400);
2036    let z = days + 719468;
2037    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
2038    let doe = z - era * 146097;
2039    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2040    let y = yoe + era * 400;
2041    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2042    let mp = (5 * doy + 2) / 153;
2043    let d = doy - (153 * mp + 2) / 5 + 1;
2044    let m = if mp < 10 { mp + 3 } else { mp - 9 };
2045    let year = if m <= 2 { y + 1 } else { y };
2046    let hh = secs / 3600;
2047    let mm = (secs % 3600) / 60;
2048    let ss = secs % 60;
2049    format!("{year:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
2050}
2051
2052/// Parameters for [`build_safety_evidence`]. The robot DID is derived from
2053/// `signer_seed` (a did:key), mirroring the Python signer. `blackbox_head` and
2054/// `entry_count` seal the robot's black-box chain; `halos_stack` names the
2055/// certified configuration; `window` covers the recorded events. Timestamps are
2056/// caller-supplied ISO-8601 strings.
2057#[derive(Debug, Clone)]
2058pub struct BuildSafetyEvidence {
2059    pub halos_stack: Value,
2060    pub window_from: String,
2061    pub window_to: String,
2062    pub blackbox_head: String,
2063    pub entry_count: u64,
2064    pub robot_identity: Option<String>,
2065    pub valid_seconds: Option<i64>,
2066    pub valid_from: String,
2067    pub created: String,
2068    /// The robot's DID, when it is not the did:key of the signing key (a
2069    /// did:web robot); without it the issuer is that did:key.
2070    pub robot_did: Option<String>,
2071}
2072
2073/// Seal a robot's Halos safety-event record into a signed
2074/// `HalosSafetyEvidenceCredential`. The robot signs a credential binding the
2075/// black-box chain head and entry count to its identity, to the Halos stack
2076/// elements it ran on, and to the time window.
2077pub fn build_safety_evidence(signer_seed: &[u8], params: &BuildSafetyEvidence) -> Result<Value> {
2078    match params.halos_stack.as_object() {
2079        Some(o) if !o.is_empty() => {}
2080        _ => return Err(CoreError::Json("halos_stack is required".into())),
2081    }
2082    if params.window_from.is_empty() || params.window_to.is_empty() {
2083        return Err(CoreError::Json(
2084            "window with 'from' and 'to' is required".into(),
2085        ));
2086    }
2087
2088    let robot_did = match params.robot_did.as_deref().filter(|d| !d.is_empty()) {
2089        Some(d) if d.starts_with("did:") => d.to_string(),
2090        Some(_) => return Err(CoreError::Json("robot_did must be a DID".into())),
2091        None => {
2092            let kp = keys::Ed25519KeyPair::from_seed_slice(signer_seed)?;
2093            keys::ed25519_to_did_key(&kp.public_key())?
2094        }
2095    };
2096
2097    let mut subject = Map::new();
2098    subject.insert("id".into(), json!(robot_did));
2099    subject.insert("blackboxHead".into(), json!(params.blackbox_head));
2100    subject.insert("entryCount".into(), json!(params.entry_count));
2101    subject.insert("halosStack".into(), params.halos_stack.clone());
2102    subject.insert(
2103        "window".into(),
2104        json!({ "from": params.window_from, "to": params.window_to }),
2105    );
2106    if let Some(robot_identity) = &params.robot_identity {
2107        subject.insert("robotIdentity".into(), json!(robot_identity));
2108    }
2109
2110    let mut cred = Map::new();
2111    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2112    cred.insert(
2113        "type".into(),
2114        json!(["VerifiableCredential", HALOS_SAFETY_EVIDENCE_TYPE]),
2115    );
2116    cred.insert("issuer".into(), json!(robot_did));
2117    cred.insert("validFrom".into(), json!(params.valid_from));
2118    if let Some(valid_seconds) = params.valid_seconds {
2119        let from = crate::time::iso_to_epoch_seconds(&params.valid_from)?;
2120        cred.insert(
2121            "validUntil".into(),
2122            json!(halos_epoch_to_iso(from + valid_seconds)),
2123        );
2124    }
2125    cred.insert("credentialSubject".into(), Value::Object(subject));
2126
2127    let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), &params.created);
2128    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2129}
2130
2131/// Verify a `HalosSafetyEvidenceCredential`: the robot's proof and that the issuer
2132/// is the robot (`credentialSubject.id`). When `entries` is supplied, also checks
2133/// that the black-box chain is intact, that its length matches the sealed entry
2134/// count, and that its head matches the sealed head, so a truncated, extended,
2135/// reordered, or tampered record is rejected. Returns `(ok, credentialSubject)`.
2136pub fn verify_safety_evidence(
2137    credential: &Value,
2138    robot_keys: Keys<'_>,
2139    entries: Option<&[Value]>,
2140    now_iso: &str,
2141) -> Result<(bool, Option<Value>)> {
2142    let v = match bound(
2143        credential,
2144        robot_keys,
2145        HALOS_SAFETY_EVIDENCE_TYPE,
2146        now_iso,
2147        Window::FromRequired,
2148    )? {
2149        Some(v) if issuer_is_subject(&v) => v,
2150        _ => return Ok((false, None)),
2151    };
2152    let subject = v.subject;
2153    let count = match rv::strict_int(subject.get("entryCount")) {
2154        Some(n) if n >= 0 => n,
2155        _ => return Ok((false, None)),
2156    };
2157
2158    if let Some(entries) = entries {
2159        if !verify_blackbox_chain(entries, None).ok {
2160            return Ok((false, None));
2161        }
2162        if count != entries.len() as i64 {
2163            return Ok((false, None));
2164        }
2165        let head = match entries.last() {
2166            Some(last) => last
2167                .get("entryHash")
2168                .and_then(|v| v.as_str())
2169                .unwrap_or("")
2170                .to_string(),
2171            None => genesis_prev_hash(),
2172        };
2173        if Some(head.as_str()) != subject.get("blackboxHead").and_then(|v| v.as_str()) {
2174            return Ok((false, None));
2175        }
2176    }
2177
2178    Ok((true, Some(subject)))
2179}
2180
2181// ---------------------------------------------------------------------------
2182// Scannable robot passport (Phase 5.6)
2183// ---------------------------------------------------------------------------
2184
2185pub const ROBOT_PASSPORT_TYPE: &str = "RobotPassport";
2186pub const PASSPORT_URI_SCHEME: &str = "vouch-passport:";
2187pub const STATUS_ACTIVE: &str = "active";
2188pub const STATUS_SUSPENDED: &str = "suspended";
2189pub const STATUS_DECOMMISSIONED: &str = "decommissioned";
2190
2191/// Parameters for [`build_passport`]. The issuer is the signer (the robot or an
2192/// authority); `robot_did` is the robot the passport describes.
2193#[derive(Debug, Clone, Default)]
2194pub struct BuildPassport {
2195    pub issuer_did: String,
2196    pub robot_did: String,
2197    pub make: String,
2198    pub model: String,
2199    pub owner: String,
2200    pub authorized_actions: Vec<String>,
2201    pub certification: Option<String>,
2202    pub status: Option<String>,
2203    pub valid_from: String,
2204    pub valid_until: Option<String>,
2205}
2206
2207/// Build a signed `RobotPassport` credential.
2208pub fn build_passport(signer_seed: &[u8], params: &BuildPassport) -> Result<Value> {
2209    let status = params
2210        .status
2211        .clone()
2212        .unwrap_or_else(|| STATUS_ACTIVE.to_string());
2213    let mut subject = Map::new();
2214    subject.insert("id".into(), json!(params.robot_did));
2215    subject.insert("make".into(), json!(params.make));
2216    subject.insert("model".into(), json!(params.model));
2217    subject.insert("owner".into(), json!(params.owner));
2218    subject.insert("authorizedActions".into(), json!(params.authorized_actions));
2219    subject.insert("status".into(), json!(status));
2220    if let Some(c) = &params.certification {
2221        subject.insert("certification".into(), json!(c));
2222    }
2223
2224    let mut cred = Map::new();
2225    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2226    cred.insert(
2227        "type".into(),
2228        json!(["VerifiableCredential", ROBOT_PASSPORT_TYPE]),
2229    );
2230    cred.insert("issuer".into(), json!(params.issuer_did));
2231    cred.insert("validFrom".into(), json!(params.valid_from));
2232    if let Some(vu) = &params.valid_until {
2233        cred.insert("validUntil".into(), json!(vu));
2234    }
2235    cred.insert("credentialSubject".into(), Value::Object(subject));
2236
2237    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
2238    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2239}
2240
2241/// Encode a passport into a compact `vouch-passport:` URI for a QR or NFC tag.
2242pub fn encode_passport(passport: &Value) -> String {
2243    format!(
2244        "{}{}",
2245        PASSPORT_URI_SCHEME,
2246        mb64(&jcs::canonicalize(passport))
2247    )
2248}
2249
2250/// Decode a `vouch-passport:` URI back into the passport credential.
2251pub fn decode_passport(uri: &str) -> Result<Value> {
2252    let body = uri
2253        .strip_prefix(PASSPORT_URI_SCHEME)
2254        .ok_or_else(|| CoreError::Json(format!("not a {PASSPORT_URI_SCHEME} URI")))?;
2255    if body.len() > 2 * rv::MAX_CREDENTIAL_BYTES {
2256        return Err(CoreError::Json("passport URI too large".into()));
2257    }
2258    let raw = unmb64(body)?;
2259    let decoded: Value = serde_json::from_slice(&raw)
2260        .map_err(|e| CoreError::Json(format!("passport decode: {e}")))?;
2261    if !decoded.is_object() {
2262        return Err(CoreError::Json("passport payload is not an object".into()));
2263    }
2264    Ok(decoded)
2265}
2266
2267/// Verify a passport: the proof bound to the issuer (`keys` is a `{did: key}`
2268/// source, or the bare key of a did:key issuer), the validity window at
2269/// `now_iso` (validFrom required, strict times), `authorizedActions` a list of
2270/// strings, and (when given) the issuer in `trusted_issuers`. A suspended or
2271/// decommissioned status still verifies; the caller reads it from the subject.
2272pub fn verify_passport(
2273    passport: &Value,
2274    keys: Keys<'_>,
2275    trusted_issuers: Option<&HashSet<String>>,
2276    now_iso: &str,
2277) -> Result<Option<Value>> {
2278    let now = rv::require_now(now_iso)?;
2279    let opts = VerifyOptions {
2280        trusted_issuers,
2281        ..VerifyOptions::window(Window::FromRequired)
2282    };
2283    let v = match rv::verify_robotics_credential(
2284        passport,
2285        keys,
2286        Some(ROBOT_PASSPORT_TYPE),
2287        now,
2288        opts,
2289    ) {
2290        Ok(v) => v,
2291        Err(_) => return Ok(None),
2292    };
2293    match v.subject.get("authorizedActions") {
2294        None => {}
2295        Some(Value::Array(a)) if a.iter().all(|x| x.is_string()) => {}
2296        _ => return Ok(None),
2297    }
2298    Ok(Some(v.subject))
2299}
2300
2301pub fn verify_passport_uri(
2302    uri: &str,
2303    keys: Keys<'_>,
2304    trusted_issuers: Option<&HashSet<String>>,
2305    now_iso: &str,
2306) -> Result<Option<Value>> {
2307    rv::require_now(now_iso)?;
2308    match decode_passport(uri) {
2309        Ok(p) => verify_passport(&p, keys, trusted_issuers, now_iso),
2310        Err(_) => Ok(None),
2311    }
2312}
2313
2314/// Verify a passport (a credential object or a `vouch-passport:` URI) as
2315/// [`verify_passport`] does and return the human-facing summary the Python
2316/// reference returns: robot, make, model, owner, authorizedActions,
2317/// certification, status, and the verified `issuer`.
2318pub fn verify_passport_summary(
2319    passport: &Value,
2320    keys: Keys<'_>,
2321    trusted_issuers: Option<&HashSet<String>>,
2322    now_iso: &str,
2323) -> Result<Option<Value>> {
2324    let cred = match passport {
2325        Value::String(uri) => match decode_passport(uri) {
2326            Ok(p) => p,
2327            Err(_) => return Ok(None),
2328        },
2329        other => other.clone(),
2330    };
2331    let subject = match verify_passport(&cred, keys, trusted_issuers, now_iso)? {
2332        Some(s) => s,
2333        None => return Ok(None),
2334    };
2335    let issuer = rv::issuer_id(cred.get("issuer")).unwrap_or("").to_string();
2336    let g = |k: &str| subject.get(k).cloned().unwrap_or(Value::Null);
2337    Ok(Some(json!({
2338        "robot": g("id"),
2339        "make": g("make"),
2340        "model": g("model"),
2341        "owner": g("owner"),
2342        "authorizedActions": subject.get("authorizedActions").cloned().unwrap_or(json!([])),
2343        "certification": g("certification"),
2344        "status": g("status"),
2345        "issuer": issuer,
2346    })))
2347}
2348
2349// ---------------------------------------------------------------------------
2350// Liveness heartbeat with safety-envelope conformance (Phase 5.7)
2351// ---------------------------------------------------------------------------
2352
2353pub const ROBOT_HEARTBEAT_TYPE: &str = "RobotHeartbeatCredential";
2354
2355/// Default number of missed intervals tolerated before trust is considered stale.
2356pub const DEFAULT_GRACE_INTERVALS: i64 = 2;
2357
2358/// One observed motion sample. `None` numerics mean "not specified" (a meaningful
2359/// zero is still `Some(0.0)`), matching [`PhysicalAction`].
2360#[derive(Debug, Clone, Default)]
2361pub struct MotionSample {
2362    pub force_n: Option<f64>,
2363    pub speed_mps: Option<f64>,
2364    pub near_humans: bool,
2365    pub zone: Option<String>,
2366    pub time_hm: Option<String>,
2367}
2368
2369/// Collector for per-interval motion telemetry. It accumulates aggregates of what
2370/// the robot physically did over a heartbeat interval and, when given a physical
2371/// scope, counts how many samples fell outside the declared envelope. The
2372/// physical analogue of the agent behavioral digest.
2373///
2374/// With `scope` set to `None` the digest still reports observed maxima but cannot
2375/// judge conformance, so it reports `withinEnvelope` true with a zero breach
2376/// count, mirroring the Python `MotionCollector`.
2377#[derive(Debug, Clone, Default)]
2378pub struct MotionCollector {
2379    scope: Option<Value>,
2380    samples: u64,
2381    max_force: f64,
2382    max_speed: f64,
2383    max_speed_near: f64,
2384    zone_breaches: u64,
2385    breaches: u64,
2386}
2387
2388impl MotionCollector {
2389    /// A collector that judges samples against `scope` (the
2390    /// `credentialSubject.physicalScope` object). Pass `None` to only aggregate.
2391    pub fn new(scope: Option<Value>) -> Self {
2392        Self {
2393            scope,
2394            ..Default::default()
2395        }
2396    }
2397
2398    /// Record a single observed motion sample, updating the running aggregates and
2399    /// (when a scope is set) the breach counts.
2400    pub fn record(&mut self, sample: &MotionSample) -> Result<()> {
2401        if let Some(f) = sample.force_n {
2402            if !f.is_finite() || f < 0.0 {
2403                return Err(CoreError::Json(format!(
2404                    "force_n must be a finite non-negative number, got {f}"
2405                )));
2406            }
2407        }
2408        if let Some(s) = sample.speed_mps {
2409            if !s.is_finite() || s < 0.0 {
2410                return Err(CoreError::Json(format!(
2411                    "speed_mps must be a finite non-negative number, got {s}"
2412                )));
2413            }
2414        }
2415
2416        self.samples += 1;
2417        if let Some(f) = sample.force_n {
2418            self.max_force = self.max_force.max(f);
2419        }
2420        if let Some(s) = sample.speed_mps {
2421            self.max_speed = self.max_speed.max(s);
2422            if sample.near_humans {
2423                self.max_speed_near = self.max_speed_near.max(s);
2424            }
2425        }
2426
2427        if let Some(scope) = &self.scope {
2428            let action = PhysicalAction {
2429                force_n: sample.force_n,
2430                speed_mps: sample.speed_mps,
2431                near_humans: sample.near_humans,
2432                zone: sample.zone.clone(),
2433                time_hm: sample.time_hm.clone(),
2434            };
2435            let result = check_physical_action(scope, &action);
2436            if !result.ok {
2437                self.breaches += 1;
2438                if result
2439                    .reasons
2440                    .iter()
2441                    .any(|r| r.starts_with("zone_not_allowed"))
2442                {
2443                    self.zone_breaches += 1;
2444                }
2445            }
2446        }
2447        Ok(())
2448    }
2449
2450    /// Return the `motionDigest` object for embedding in a heartbeat credential.
2451    pub fn digest(&self) -> Value {
2452        json!({
2453            "samples": self.samples,
2454            "maxForceN": self.max_force,
2455            "maxSpeedMps": self.max_speed,
2456            "maxSpeedNearHumansMps": self.max_speed_near,
2457            "zoneBreaches": self.zone_breaches,
2458            "breachCount": self.breaches,
2459            "withinEnvelope": self.breaches == 0,
2460        })
2461    }
2462
2463    /// Clear all state. Call after submitting a heartbeat to start fresh.
2464    pub fn reset(&mut self) {
2465        self.samples = 0;
2466        self.max_force = 0.0;
2467        self.max_speed = 0.0;
2468        self.max_speed_near = 0.0;
2469        self.zone_breaches = 0;
2470        self.breaches = 0;
2471    }
2472}
2473
2474fn digest_non_negative_int(digest: &Map<String, Value>, name: &str) -> Result<()> {
2475    match digest.get(name) {
2476        Some(v) if v.is_u64() => Ok(()),
2477        Some(Value::Number(n)) if n.as_i64().map(|i| i >= 0).unwrap_or(false) => Ok(()),
2478        Some(_) => Err(CoreError::Json(format!(
2479            "motionDigest.{name} must be a non-negative integer"
2480        ))),
2481        None => Err(CoreError::Json(format!("motionDigest.{name} is required"))),
2482    }
2483}
2484
2485/// Structural validation of a `motionDigest` object. Does not judge whether the
2486/// values are acceptable; that is policy, expressed through [`is_live`].
2487pub fn validate_motion_digest(digest: &Value) -> Result<()> {
2488    let obj = digest
2489        .as_object()
2490        .ok_or_else(|| CoreError::Json("motionDigest must be an object".into()))?;
2491
2492    for name in ["samples", "zoneBreaches", "breachCount"] {
2493        digest_non_negative_int(obj, name)?;
2494    }
2495    for name in ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"] {
2496        match obj.get(name) {
2497            Some(Value::Bool(_)) | None => {
2498                return Err(CoreError::Json(format!("motionDigest.{name} is required")))
2499            }
2500            Some(v) => {
2501                let n = rv::finite_number(Some(v)).ok_or_else(|| {
2502                    CoreError::Json(format!("motionDigest.{name} must be a finite number"))
2503                })?;
2504                if n < 0.0 {
2505                    return Err(CoreError::Json(format!(
2506                        "motionDigest.{name} must be non-negative"
2507                    )));
2508                }
2509            }
2510        }
2511    }
2512    let within = match obj.get("withinEnvelope") {
2513        Some(Value::Bool(b)) => *b,
2514        Some(_) => {
2515            return Err(CoreError::Json(
2516                "motionDigest.withinEnvelope must be a boolean".into(),
2517            ))
2518        }
2519        None => {
2520            return Err(CoreError::Json(
2521                "motionDigest.withinEnvelope is required".into(),
2522            ))
2523        }
2524    };
2525    let n = |k: &str| obj.get(k).and_then(|v| v.as_u64()).unwrap_or(0);
2526    if within != (n("breachCount") == 0) {
2527        return Err(CoreError::Json(
2528            "motionDigest.withinEnvelope disagrees with breachCount".into(),
2529        ));
2530    }
2531    if n("zoneBreaches") > n("breachCount") {
2532        return Err(CoreError::Json(
2533            "motionDigest.zoneBreaches exceeds breachCount".into(),
2534        ));
2535    }
2536    Ok(())
2537}
2538
2539/// The longest heartbeat cadence a verifier accepts from the heartbeat itself.
2540pub const MAX_INTERVAL_SECONDS: i64 = 3600;
2541
2542/// Parameters for [`build_robot_heartbeat`]. The robot self-issues the credential
2543/// with its own Ed25519 seed; `motion_digest` is produced by a [`MotionCollector`]
2544/// over the interval and `interval_seconds` is the declared heartbeat cadence.
2545#[derive(Debug, Clone)]
2546pub struct BuildRobotHeartbeat {
2547    pub robot_did: String,
2548    pub session_id: String,
2549    pub interval_index: i64,
2550    pub interval_seconds: i64,
2551    pub motion_digest: Value,
2552    pub valid_from: String,
2553}
2554
2555/// Build a signed `RobotHeartbeatCredential`.
2556pub fn build_robot_heartbeat(robot_seed: &[u8], params: &BuildRobotHeartbeat) -> Result<Value> {
2557    if params.interval_index < 0 {
2558        return Err(CoreError::Json(
2559            "interval_index must be non-negative".into(),
2560        ));
2561    }
2562    if params.interval_seconds <= 0 {
2563        return Err(CoreError::Json("interval_seconds must be positive".into()));
2564    }
2565    validate_motion_digest(&params.motion_digest)?;
2566
2567    let mut subject = Map::new();
2568    subject.insert("id".into(), json!(params.robot_did));
2569    subject.insert("sessionId".into(), json!(params.session_id));
2570    subject.insert("intervalIndex".into(), json!(params.interval_index));
2571    subject.insert("intervalSeconds".into(), json!(params.interval_seconds));
2572    subject.insert("motionDigest".into(), params.motion_digest.clone());
2573
2574    let mut cred = Map::new();
2575    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2576    cred.insert(
2577        "type".into(),
2578        json!(["VerifiableCredential", ROBOT_HEARTBEAT_TYPE]),
2579    );
2580    cred.insert("issuer".into(), json!(params.robot_did));
2581    cred.insert("validFrom".into(), json!(params.valid_from));
2582    cred.insert("credentialSubject".into(), Value::Object(subject));
2583
2584    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
2585    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
2586}
2587
2588/// Verify a `RobotHeartbeatCredential`: the credential proof bound to the robot
2589/// as issuer (which must also be `credentialSubject.id`), a validFrom no later
2590/// than `now_iso`, and the structural validity of the embedded motion digest. Returns the subject on
2591/// success. Whether the robot is currently trusted is a separate, time-dependent
2592/// question answered by [`is_live`].
2593pub fn verify_robot_heartbeat(
2594    credential: &Value,
2595    robot_keys: Keys<'_>,
2596    now_iso: &str,
2597) -> Result<Option<Value>> {
2598    let v = match bound(
2599        credential,
2600        robot_keys,
2601        ROBOT_HEARTBEAT_TYPE,
2602        now_iso,
2603        Window::FromRequired,
2604    )? {
2605        Some(v) if issuer_is_subject(&v) => v,
2606        _ => return Ok(None),
2607    };
2608    let digest = v
2609        .subject
2610        .get("motionDigest")
2611        .cloned()
2612        .unwrap_or(Value::Null);
2613    if validate_motion_digest(&digest).is_err() {
2614        return Ok(None);
2615    }
2616    Ok(Some(v.subject))
2617}
2618
2619/// Decide whether a robot is currently trusted, given its most recent heartbeat
2620/// (verify it with [`verify_robot_heartbeat`] first). Live only when: the
2621/// heartbeat was issued within `grace_intervals` cadence periods of `now_iso`
2622/// (the cadence is the verifier's `interval_seconds` when given, else the
2623/// heartbeat's declared interval capped at [`MAX_INTERVAL_SECONDS`]); the
2624/// motion digest covers at least one sample; and the digest is well-formed and
2625/// reports withinEnvelope true. Malformed input returns `false`.
2626pub fn is_live(
2627    credential: &Value,
2628    now_iso: &str,
2629    interval_seconds: Option<i64>,
2630    grace_intervals: i64,
2631) -> Result<bool> {
2632    is_live_capped(
2633        credential,
2634        now_iso,
2635        interval_seconds,
2636        grace_intervals,
2637        MAX_INTERVAL_SECONDS,
2638    )
2639}
2640
2641/// [`is_live`] with the caller's cap on a declared cadence instead of
2642/// [`MAX_INTERVAL_SECONDS`].
2643pub fn is_live_capped(
2644    credential: &Value,
2645    now_iso: &str,
2646    interval_seconds: Option<i64>,
2647    grace_intervals: i64,
2648    max_interval_seconds: i64,
2649) -> Result<bool> {
2650    if max_interval_seconds < 1 {
2651        return Err(CoreError::Json(
2652            "max_interval_seconds must be at least 1".into(),
2653        ));
2654    }
2655    if grace_intervals < 1 {
2656        return Err(CoreError::Json("grace_intervals must be at least 1".into()));
2657    }
2658    let subject = match credential
2659        .get("credentialSubject")
2660        .and_then(|s| s.as_object())
2661    {
2662        Some(s) => s,
2663        None => return Ok(false),
2664    };
2665    let digest = match subject.get("motionDigest") {
2666        Some(d) if validate_motion_digest(d).is_ok() => d,
2667        _ => return Ok(false),
2668    };
2669    if digest.get("samples").and_then(|v| v.as_u64()).unwrap_or(0) == 0
2670        || digest.get("withinEnvelope") != Some(&Value::Bool(true))
2671    {
2672        return Ok(false);
2673    }
2674    let cadence = match interval_seconds {
2675        Some(c) => c,
2676        None => match rv::strict_int(subject.get("intervalSeconds")) {
2677            Some(d) if d > 0 => d.min(max_interval_seconds),
2678            _ => return Ok(false),
2679        },
2680    };
2681    if cadence <= 0 {
2682        return Ok(false);
2683    }
2684    let issued = match rv::time_ns(credential.get("validFrom")) {
2685        Some(t) => t,
2686        None => return Ok(false),
2687    };
2688    let moment = match crate::time::parse_protocol_time_ns(now_iso) {
2689        Ok(t) => t,
2690        Err(_) => return Ok(false),
2691    };
2692    let cadence_ns = i128::from(cadence) * 1_000_000_000;
2693    // A heartbeat from the future (clock skew beyond one cadence) is not trusted.
2694    if moment + cadence_ns < issued {
2695        return Ok(false);
2696    }
2697    Ok(moment <= issued + cadence_ns * i128::from(grace_intervals))
2698}
2699
2700// ---------------------------------------------------------------------------
2701// Per-credential revocation (Phase 5.8)
2702// ---------------------------------------------------------------------------
2703
2704pub use crate::status_list::{BITSTRING_STATUS_LIST_ENTRY_TYPE, STATUS_PURPOSE_REVOCATION};
2705
2706/// Build a BitstringStatusList `credentialStatus` entry referencing a bit index in
2707/// a published status list credential. Mirrors the agent-side
2708/// `status_list.build_status_list_entry`. `entry_id`, when `None`, defaults to
2709/// `{status_list_credential}#{status_list_index}`.
2710pub fn build_status_list_entry(
2711    status_list_credential: &str,
2712    status_list_index: i64,
2713    status_purpose: &str,
2714    entry_id: Option<&str>,
2715) -> Result<Value> {
2716    if !matches!(status_purpose, "revocation" | "suspension" | "message") {
2717        return Err(CoreError::Json(format!(
2718            "status_purpose must be one of revocation, suspension, message, got {status_purpose:?}"
2719        )));
2720    }
2721    if status_list_index < 0 {
2722        return Err(CoreError::Json(
2723            "status_list_index must be non-negative".into(),
2724        ));
2725    }
2726    if status_list_credential.is_empty() {
2727        return Err(CoreError::Json(
2728            "status_list_credential URL is required".into(),
2729        ));
2730    }
2731    let id = entry_id
2732        .map(String::from)
2733        .unwrap_or_else(|| format!("{status_list_credential}#{status_list_index}"));
2734    Ok(json!({
2735        "id": id,
2736        "type": BITSTRING_STATUS_LIST_ENTRY_TYPE,
2737        "statusPurpose": status_purpose,
2738        "statusListIndex": status_list_index.to_string(),
2739        "statusListCredential": status_list_credential,
2740    }))
2741}
2742
2743/// Parameters for [`attach_credential_status`].
2744#[derive(Debug, Clone)]
2745pub struct AttachCredentialStatus {
2746    pub status_list_credential: String,
2747    pub status_list_index: i64,
2748    pub status_purpose: String,
2749    pub entry_id: Option<String>,
2750    /// `validFrom`-style timestamp used as the proof `created` when re-signing.
2751    pub created: String,
2752}
2753
2754/// Add a BitstringStatusList `credentialStatus` entry to a robot credential and
2755/// re-sign it under `signer_seed`, so the proof covers the status binding. If the
2756/// credential already carries a `credentialStatus`, the new entry is appended (the
2757/// field becomes a list), matching the Verifiable Credentials data model. Any
2758/// pre-existing proof is replaced.
2759pub fn attach_credential_status(
2760    credential: &Value,
2761    signer_seed: &[u8],
2762    params: &AttachCredentialStatus,
2763) -> Result<Value> {
2764    let entry = build_status_list_entry(
2765        &params.status_list_credential,
2766        params.status_list_index,
2767        &params.status_purpose,
2768        params.entry_id.as_deref(),
2769    )?;
2770
2771    let mut obj = credential
2772        .as_object()
2773        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
2774        .clone();
2775
2776    match obj.get("credentialStatus").cloned() {
2777        None => {
2778            obj.insert("credentialStatus".into(), entry);
2779        }
2780        Some(Value::Array(mut existing)) => {
2781            existing.push(entry);
2782            obj.insert("credentialStatus".into(), Value::Array(existing));
2783        }
2784        Some(existing) => {
2785            obj.insert("credentialStatus".into(), json!([existing, entry]));
2786        }
2787    }
2788
2789    // Re-sign: the proof must cover the credentialStatus we just added.
2790    obj.remove("proof");
2791    let issuer = obj.get("issuer").and_then(|v| v.as_str()).unwrap_or("");
2792    let opts = BuildProofOptions::new(format!("{issuer}#key-1"), &params.created);
2793    data_integrity::sign(&Value::Object(obj), signer_seed, &opts)
2794}
2795
2796fn status_entries(credential: &Value) -> Result<Vec<Value>> {
2797    match credential.get("credentialStatus") {
2798        None => Ok(Vec::new()),
2799        Some(Value::Array(a)) => Ok(a.iter().filter(|e| e.is_object()).cloned().collect()),
2800        Some(v) if v.is_object() => Ok(vec![v.clone()]),
2801        Some(_) => Err(CoreError::Json(
2802            "credentialStatus must be an object or a list of objects".into(),
2803        )),
2804    }
2805}
2806
2807/// Return `true` if the robot credential's status bit for `status_purpose` is
2808/// set in the supplied status list. Returns `false` only when the credential
2809/// carries no status entry for that purpose, or every entry for that purpose
2810/// that references this list has its bit clear (every matching entry is
2811/// checked). Errors when the credential has an entry for this purpose but none
2812/// references the supplied list (the list cannot answer), or when the list's
2813/// issuer is not the credential's issuer. The caller verifies the list's proof
2814/// first.
2815pub fn check_credential_status(
2816    credential: &Value,
2817    status_list_credential: &Value,
2818    status_purpose: &str,
2819) -> Result<bool> {
2820    check_status_inner(credential, status_list_credential, status_purpose, None)
2821}
2822
2823/// [`check_credential_status`], and the status list's own signature must
2824/// verify: issued by the issuer it names, under that issuer's key from `keys`
2825/// (see [`crate::robotics_dtn::verify_status_list_signature`]), checked at
2826/// `now_iso` with 30 s of skew. A list whose signature fails is an error.
2827pub fn check_credential_status_signed(
2828    credential: &Value,
2829    status_list_credential: &Value,
2830    status_purpose: &str,
2831    keys: Keys<'_>,
2832    now_iso: &str,
2833) -> Result<bool> {
2834    check_status_inner(
2835        credential,
2836        status_list_credential,
2837        status_purpose,
2838        Some((keys, now_iso)),
2839    )
2840}
2841
2842fn check_status_inner(
2843    credential: &Value,
2844    status_list_credential: &Value,
2845    status_purpose: &str,
2846    signed_by: Option<(Keys<'_>, &str)>,
2847) -> Result<bool> {
2848    let entries: Vec<Value> = status_entries(credential)?
2849        .into_iter()
2850        .filter(|e| e.get("statusPurpose").and_then(|v| v.as_str()) == Some(status_purpose))
2851        .collect();
2852    if entries.is_empty() {
2853        return Ok(false);
2854    }
2855    let referenced_id = status_list_credential.get("id");
2856    let matching: Vec<&Value> = entries
2857        .iter()
2858        .filter(|e| e.get("statusListCredential") == referenced_id)
2859        .collect();
2860    if matching.is_empty() {
2861        return Err(CoreError::Json(
2862            "the credential has a status entry for this purpose, but none references this list"
2863                .into(),
2864        ));
2865    }
2866    if rv::issuer_id(status_list_credential.get("issuer"))
2867        != rv::issuer_id(credential.get("issuer"))
2868    {
2869        return Err(CoreError::Json(
2870            "the status list is not from the credential's issuer".into(),
2871        ));
2872    }
2873    if let Some((keys, now_iso)) = signed_by {
2874        if !crate::robotics_dtn::verify_status_list_signature(
2875            status_list_credential,
2876            keys,
2877            now_iso,
2878            30,
2879        )? {
2880            return Err(CoreError::Json(
2881                "the status list signature does not verify".into(),
2882            ));
2883        }
2884    }
2885    for entry in matching {
2886        if crate::status_list::verify_status(entry, status_list_credential)? {
2887            return Ok(true);
2888        }
2889    }
2890    Ok(false)
2891}
2892
2893// ---------------------------------------------------------------------------
2894// Accountable safety record (Phase 5.9)
2895// ---------------------------------------------------------------------------
2896
2897pub const SAFETY_RECORD_TYPE: &str = "RobotSafetyRecordCredential";
2898pub const SAFETY_LOG_VERSION: &str = "1.0";
2899
2900/// Standard safety event types: the interoperable set a verifier and an insurer
2901/// can rely on. Implementers MAY use additional types.
2902pub const EVENT_TYPES: [&str; 6] = [
2903    "incident",
2904    "near_miss",
2905    "manual_override",
2906    "kill_switch",
2907    "envelope_breach",
2908    "maintenance",
2909];
2910
2911/// Severity bands, ordered from least to most serious.
2912pub const SEVERITIES: [&str; 5] = ["info", "low", "medium", "high", "critical"];
2913
2914/// Append-only, plaintext, hash-linked safety event ledger. Reuses the black-box
2915/// chain semantics ([`entry_hash`], [`genesis_prev_hash`]) so the two logs verify
2916/// the same way, but entries are plaintext: a safety record is meant to be read
2917/// and trusted by third parties.
2918pub struct SafetyEventLog {
2919    genesis: String,
2920    entries: Vec<Value>,
2921    head: String,
2922    seq_base: u64,
2923}
2924
2925impl SafetyEventLog {
2926    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
2927    pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
2928        let genesis = genesis_prev_hash_override
2929            .map(String::from)
2930            .unwrap_or_else(genesis_prev_hash);
2931        Self {
2932            head: genesis.clone(),
2933            genesis,
2934            entries: Vec::new(),
2935            seq_base: 0,
2936        }
2937    }
2938
2939    /// Continue a log whose head is `prev_hash` and whose next entry is
2940    /// number `next_seq` (a host that keeps the log itself appends one entry
2941    /// at a time this way).
2942    pub fn resume(prev_hash: &str, next_seq: u64) -> Self {
2943        let mut log = Self::new(Some(prev_hash));
2944        log.seq_base = next_seq;
2945        log
2946    }
2947
2948    /// Append one safety event, link it to the chain head, and return the entry.
2949    pub fn append(
2950        &mut self,
2951        event_type: &str,
2952        severity: &str,
2953        details: Option<&Value>,
2954        actor: Option<&str>,
2955        timestamp: &str,
2956    ) -> Result<Value> {
2957        if !EVENT_TYPES.contains(&event_type) {
2958            return Err(CoreError::Json(format!(
2959                "event_type must be one of {EVENT_TYPES:?}, got {event_type:?}"
2960            )));
2961        }
2962        if !SEVERITIES.contains(&severity) {
2963            return Err(CoreError::Json(format!(
2964                "severity must be one of {SEVERITIES:?}, got {severity:?}"
2965            )));
2966        }
2967
2968        let mut body = Map::new();
2969        body.insert("version".into(), json!(SAFETY_LOG_VERSION));
2970        body.insert(
2971            "seq".into(),
2972            json!(self.seq_base + self.entries.len() as u64),
2973        );
2974        body.insert("timestamp".into(), json!(timestamp));
2975        body.insert("eventType".into(), json!(event_type));
2976        body.insert("severity".into(), json!(severity));
2977        body.insert("prevHash".into(), json!(self.head));
2978        if let Some(d) = details {
2979            body.insert("details".into(), d.clone());
2980        }
2981        if let Some(a) = actor {
2982            body.insert("actor".into(), json!(a));
2983        }
2984        let h = entry_hash(&body)?;
2985        body.insert("entryHash".into(), json!(h));
2986        self.head = h;
2987        let entry = Value::Object(body);
2988        self.entries.push(entry.clone());
2989        Ok(entry)
2990    }
2991
2992    pub fn head(&self) -> &str {
2993        &self.head
2994    }
2995
2996    pub fn genesis(&self) -> &str {
2997        &self.genesis
2998    }
2999
3000    pub fn entries(&self) -> &[Value] {
3001        &self.entries
3002    }
3003
3004    /// Produce a summary object for embedding in a safety-record credential.
3005    pub fn summarize(&self) -> Value {
3006        summarize_entries(&self.entries, Some(&self.head))
3007    }
3008}
3009
3010/// Verify the hash chain over the ledger entries. Tamper-evident. Shares the
3011/// black-box chain verifier so the two logs verify identically.
3012pub fn verify_safety_log(
3013    entries: &[Value],
3014    genesis_prev_hash_override: Option<&str>,
3015) -> ChainResult {
3016    verify_blackbox_chain(entries, genesis_prev_hash_override)
3017}
3018
3019/// Summarize ledger entries into counts by event type (sorted) and by severity
3020/// (info..critical), the total event count, and (when supplied) the ledger head
3021/// hash that anchors the summary to a specific chain state.
3022pub fn summarize_entries(entries: &[Value], head: Option<&str>) -> Value {
3023    let mut sorted_types: Vec<&str> = EVENT_TYPES.to_vec();
3024    sorted_types.sort_unstable();
3025
3026    let mut event_counts = Map::new();
3027    for t in &sorted_types {
3028        event_counts.insert((*t).to_string(), json!(0));
3029    }
3030    let mut severity_counts = Map::new();
3031    for s in SEVERITIES {
3032        severity_counts.insert(s.to_string(), json!(0));
3033    }
3034
3035    for e in entries {
3036        if let Some(et) = e.get("eventType").and_then(|v| v.as_str()) {
3037            if let Some(c) = event_counts.get_mut(et).and_then(|v| v.as_u64()) {
3038                event_counts.insert(et.to_string(), json!(c + 1));
3039            }
3040        }
3041        if let Some(sv) = e.get("severity").and_then(|v| v.as_str()) {
3042            if let Some(c) = severity_counts.get_mut(sv).and_then(|v| v.as_u64()) {
3043                severity_counts.insert(sv.to_string(), json!(c + 1));
3044            }
3045        }
3046    }
3047
3048    let mut summary = Map::new();
3049    summary.insert("eventCounts".into(), Value::Object(event_counts));
3050    summary.insert("severityCounts".into(), Value::Object(severity_counts));
3051    summary.insert("totalEvents".into(), json!(entries.len() as u64));
3052    if let Some(h) = head {
3053        summary.insert("logHead".into(), json!(h));
3054    }
3055    Value::Object(summary)
3056}
3057
3058/// Structural validation of a safety summary.
3059pub fn validate_safety_summary(summary: &Value) -> Result<()> {
3060    let obj = summary
3061        .as_object()
3062        .ok_or_else(|| CoreError::Json("summary must be an object".into()))?;
3063    for name in ["eventCounts", "severityCounts"] {
3064        let block = obj
3065            .get(name)
3066            .and_then(|v| v.as_object())
3067            .ok_or_else(|| CoreError::Json(format!("summary.{name} must be an object")))?;
3068        for (k, v) in block {
3069            let ok = v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false);
3070            if v.is_boolean() || !ok {
3071                return Err(CoreError::Json(format!(
3072                    "summary.{name}[{k:?}] must be a non-negative integer"
3073                )));
3074            }
3075        }
3076    }
3077    let total_ok = obj
3078        .get("totalEvents")
3079        .map(|v| (v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false)) && !v.is_boolean())
3080        .unwrap_or(false);
3081    if !total_ok {
3082        return Err(CoreError::Json(
3083            "summary.totalEvents must be a non-negative integer".into(),
3084        ));
3085    }
3086    Ok(())
3087}
3088
3089/// Parameters for [`build_safety_record`]. The issuer (an owner, an auditor, or
3090/// the robot itself) attests `summary`, produced by [`SafetyEventLog::summarize`]
3091/// or [`summarize_entries`].
3092#[derive(Debug, Clone)]
3093pub struct BuildSafetyRecord {
3094    pub issuer_did: String,
3095    pub robot_did: String,
3096    pub summary: Value,
3097    pub period_start: Option<String>,
3098    pub period_end: Option<String>,
3099    pub valid_from: String,
3100    pub valid_until: Option<String>,
3101}
3102
3103/// Build a signed `RobotSafetyRecordCredential` summarizing a robot's safety
3104/// ledger.
3105pub fn build_safety_record(signer_seed: &[u8], params: &BuildSafetyRecord) -> Result<Value> {
3106    validate_safety_summary(&params.summary)?;
3107
3108    let mut subject = Map::new();
3109    subject.insert("id".into(), json!(params.robot_did));
3110    if let Some(s) = params.summary.as_object() {
3111        for (k, v) in s {
3112            subject.insert(k.clone(), v.clone());
3113        }
3114    }
3115    if params.period_start.is_some() || params.period_end.is_some() {
3116        let mut period = Map::new();
3117        if let Some(start) = &params.period_start {
3118            period.insert("start".into(), json!(start));
3119        }
3120        if let Some(end) = &params.period_end {
3121            period.insert("end".into(), json!(end));
3122        }
3123        subject.insert("period".into(), Value::Object(period));
3124    }
3125
3126    let mut cred = Map::new();
3127    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3128    cred.insert(
3129        "type".into(),
3130        json!(["VerifiableCredential", SAFETY_RECORD_TYPE]),
3131    );
3132    cred.insert("issuer".into(), json!(params.issuer_did));
3133    cred.insert("validFrom".into(), json!(params.valid_from));
3134    if let Some(vu) = &params.valid_until {
3135        cred.insert("validUntil".into(), json!(vu));
3136    }
3137    cred.insert("credentialSubject".into(), Value::Object(subject));
3138
3139    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
3140    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
3141}
3142
3143/// Options for [`verify_safety_record`].
3144#[derive(Default, Clone, Copy)]
3145pub struct SafetyRecordCheck<'a> {
3146    /// The ledger entries: they must link, end at the summary's `logHead` with
3147    /// exactly `totalEvents` entries, and reproduce the summary's counts.
3148    pub entries: Option<&'a [Value]>,
3149    /// The record must be about this robot.
3150    pub robot_did: Option<&'a str>,
3151    /// The issuer must be in this set.
3152    pub trusted_issuers: Option<&'a HashSet<String>>,
3153}
3154
3155/// Verify a `RobotSafetyRecordCredential`: the issuer's proof bound to the
3156/// issuer, the validity window at `now_iso` (validFrom required), and the
3157/// structure of the embedded summary, plus the [`SafetyRecordCheck`] options.
3158/// Returns the credentialSubject on success.
3159pub fn verify_safety_record(
3160    credential: &Value,
3161    keys: Keys<'_>,
3162    check: SafetyRecordCheck<'_>,
3163    now_iso: &str,
3164) -> Result<Option<Value>> {
3165    let now = rv::require_now(now_iso)?;
3166    let opts = VerifyOptions {
3167        trusted_issuers: check.trusted_issuers,
3168        ..VerifyOptions::window(Window::FromRequired)
3169    };
3170    let v =
3171        match rv::verify_robotics_credential(credential, keys, Some(SAFETY_RECORD_TYPE), now, opts)
3172        {
3173            Ok(v) => v,
3174            Err(_) => return Ok(None),
3175        };
3176    let subject = v.subject;
3177    if validate_safety_summary(&subject).is_err() {
3178        return Ok(None);
3179    }
3180    if let Some(robot) = check.robot_did {
3181        if subject.get("id").and_then(|x| x.as_str()) != Some(robot) {
3182            return Ok(None);
3183        }
3184    }
3185    if let Some(entries) = check.entries {
3186        if !verify_chain_against_head(
3187            entries,
3188            subject.get("logHead"),
3189            subject.get("totalEvents"),
3190            None,
3191        )
3192        .ok
3193        {
3194            return Ok(None);
3195        }
3196        let recount = summarize_entries(entries, None);
3197        if recount.get("eventCounts") != subject.get("eventCounts")
3198            || recount.get("severityCounts") != subject.get("severityCounts")
3199        {
3200            return Ok(None);
3201        }
3202    }
3203    Ok(Some(subject))
3204}
3205
3206// ---------------------------------------------------------------------------
3207// Perception provenance (Phase 5.10)
3208// ---------------------------------------------------------------------------
3209
3210pub const PERCEPTION_TYPE: &str = "PerceptionProvenanceCredential";
3211pub const PERCEPTION_LOG_VERSION: &str = "1.0";
3212
3213/// Standard sensor modalities: the interoperable set a verifier can rely on.
3214/// Implementers MAY use additional values.
3215pub const MODALITIES: [&str; 6] = ["camera", "lidar", "radar", "depth", "audio", "thermal"];
3216
3217/// Multibase (base64url) SHA-256 of a raw sensor frame. Only the hash travels in
3218/// the log and the attestation; the frame stays wherever the deployment keeps it.
3219pub fn hash_frame(frame: &[u8]) -> String {
3220    mb64(&Sha256::digest(frame))
3221}
3222
3223/// Append-only, plaintext, hash-linked log of sensor-frame provenance records.
3224/// Reuses the black-box chain semantics ([`entry_hash`], [`genesis_prev_hash`]),
3225/// so a perception log verifies the same way as the safety ledger. Each entry
3226/// binds a sequence number, a timestamp, the sensor id, the modality, the frame
3227/// hash, and the hash of the previous entry; the frames are not stored.
3228pub struct PerceptionLog {
3229    genesis: String,
3230    entries: Vec<Value>,
3231    head: String,
3232    seq_base: u64,
3233}
3234
3235impl PerceptionLog {
3236    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
3237    pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
3238        let genesis = genesis_prev_hash_override
3239            .map(String::from)
3240            .unwrap_or_else(genesis_prev_hash);
3241        Self {
3242            head: genesis.clone(),
3243            genesis,
3244            entries: Vec::new(),
3245            seq_base: 0,
3246        }
3247    }
3248
3249    /// Continue a log whose head is `prev_hash` and whose next entry is
3250    /// number `next_seq`.
3251    pub fn resume(prev_hash: &str, next_seq: u64) -> Self {
3252        let mut log = Self::new(Some(prev_hash));
3253        log.seq_base = next_seq;
3254        log
3255    }
3256
3257    /// Append one frame-provenance record, link it to the chain head, and return
3258    /// the entry. Provide either the raw `frame` (it is hashed) or a precomputed
3259    /// `frame_hash`, not both.
3260    pub fn record(
3261        &mut self,
3262        sensor_id: &str,
3263        modality: &str,
3264        frame: Option<&[u8]>,
3265        frame_hash: Option<&str>,
3266        timestamp: &str,
3267    ) -> Result<Value> {
3268        if !MODALITIES.contains(&modality) {
3269            return Err(CoreError::Json(format!(
3270                "modality must be one of {MODALITIES:?}, got {modality:?}"
3271            )));
3272        }
3273        if sensor_id.is_empty() {
3274            return Err(CoreError::Json("sensor_id is required".into()));
3275        }
3276        if frame.is_some() && frame_hash.is_some() {
3277            return Err(CoreError::Json(
3278                "provide either frame or frame_hash, not both".into(),
3279            ));
3280        }
3281        let resolved = match (frame, frame_hash) {
3282            (Some(f), None) => hash_frame(f),
3283            (None, Some(h)) if !h.is_empty() => h.to_string(),
3284            _ => return Err(CoreError::Json("frame or frame_hash is required".into())),
3285        };
3286
3287        let mut body = Map::new();
3288        body.insert("version".into(), json!(PERCEPTION_LOG_VERSION));
3289        body.insert(
3290            "seq".into(),
3291            json!(self.seq_base + self.entries.len() as u64),
3292        );
3293        body.insert("timestamp".into(), json!(timestamp));
3294        body.insert("sensorId".into(), json!(sensor_id));
3295        body.insert("modality".into(), json!(modality));
3296        body.insert("frameHash".into(), json!(resolved));
3297        body.insert("prevHash".into(), json!(self.head));
3298        let h = entry_hash(&body)?;
3299        body.insert("entryHash".into(), json!(h));
3300        self.head = h;
3301        let entry = Value::Object(body);
3302        self.entries.push(entry.clone());
3303        Ok(entry)
3304    }
3305
3306    pub fn head(&self) -> &str {
3307        &self.head
3308    }
3309
3310    pub fn genesis(&self) -> &str {
3311        &self.genesis
3312    }
3313
3314    pub fn entries(&self) -> &[Value] {
3315        &self.entries
3316    }
3317
3318    /// The number of records, the count a perception attestation anchors.
3319    pub fn count(&self) -> usize {
3320        self.entries.len()
3321    }
3322}
3323
3324/// Verify the hash chain over the perception log entries. Tamper-evident. Shares
3325/// the black-box chain verifier so every hash-linked log verifies identically.
3326pub fn verify_perception_log(
3327    entries: &[Value],
3328    genesis_prev_hash_override: Option<&str>,
3329) -> ChainResult {
3330    verify_blackbox_chain(entries, genesis_prev_hash_override)
3331}
3332
3333/// Parameters for [`build_perception_attestation`]. The robot self-issues the
3334/// credential with its own Ed25519 seed. `captured_at`, when `None`, defaults to
3335/// `valid_from`. When `log_head` is supplied, the attestation also anchors the
3336/// segment of frames up to that chain head.
3337#[derive(Debug, Clone)]
3338pub struct BuildPerception {
3339    pub robot_did: String,
3340    pub sensor_id: String,
3341    pub modality: String,
3342    pub frame_hash: String,
3343    pub captured_at: Option<String>,
3344    pub log_head: Option<String>,
3345    /// The number of log entries up to `log_head`, so a verifier can tell a
3346    /// segment was not cut short.
3347    pub log_count: Option<u64>,
3348    pub valid_from: String,
3349    pub valid_until: Option<String>,
3350}
3351
3352/// Build a signed `PerceptionProvenanceCredential` attesting that a robot's sensor
3353/// captured a specific frame. Software frame-hash signing: the robot signs the
3354/// provenance of the captured frame with its own key.
3355pub fn build_perception_attestation(robot_seed: &[u8], params: &BuildPerception) -> Result<Value> {
3356    if !MODALITIES.contains(&params.modality.as_str()) {
3357        return Err(CoreError::Json(format!(
3358            "modality must be one of {MODALITIES:?}, got {:?}",
3359            params.modality
3360        )));
3361    }
3362    if params.frame_hash.is_empty() {
3363        return Err(CoreError::Json("frame_hash is required".into()));
3364    }
3365
3366    let captured = params
3367        .captured_at
3368        .clone()
3369        .unwrap_or_else(|| params.valid_from.clone());
3370
3371    let mut subject = Map::new();
3372    subject.insert("id".into(), json!(params.robot_did));
3373    subject.insert("sensorId".into(), json!(params.sensor_id));
3374    subject.insert("modality".into(), json!(params.modality));
3375    subject.insert("frameHash".into(), json!(params.frame_hash));
3376    subject.insert("capturedAt".into(), json!(captured));
3377    if let Some(head) = &params.log_head {
3378        subject.insert("logHead".into(), json!(head));
3379    }
3380    if let Some(n) = params.log_count {
3381        subject.insert("logCount".into(), json!(n));
3382    }
3383
3384    let mut cred = Map::new();
3385    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3386    cred.insert(
3387        "type".into(),
3388        json!(["VerifiableCredential", PERCEPTION_TYPE]),
3389    );
3390    cred.insert("issuer".into(), json!(params.robot_did));
3391    cred.insert("validFrom".into(), json!(params.valid_from));
3392    if let Some(vu) = &params.valid_until {
3393        cred.insert("validUntil".into(), json!(vu));
3394    }
3395    cred.insert("credentialSubject".into(), Value::Object(subject));
3396
3397    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
3398    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
3399}
3400
3401/// Verify a `PerceptionProvenanceCredential`: the robot's proof and, when the raw
3402/// `frame` is supplied, that its hash reproduces the attested `frameHash`. Returns
3403/// the credentialSubject on success, `None` if invalid.
3404pub fn verify_perception_attestation(
3405    credential: &Value,
3406    keys: Keys<'_>,
3407    frame: Option<&[u8]>,
3408    now_iso: &str,
3409) -> Result<Option<Value>> {
3410    let v = match bound(
3411        credential,
3412        keys,
3413        PERCEPTION_TYPE,
3414        now_iso,
3415        Window::FromRequired,
3416    )? {
3417        Some(v) if issuer_is_subject(&v) => v,
3418        _ => return Ok(None),
3419    };
3420    let frame_hash = v.subject.get("frameHash").and_then(|v| v.as_str());
3421    let modality = v.subject.get("modality").and_then(|v| v.as_str());
3422    match (frame_hash, modality) {
3423        (Some(fh), Some(m)) if !fh.is_empty() && MODALITIES.contains(&m) => {}
3424        _ => return Ok(None),
3425    }
3426    if let Some(f) = frame {
3427        if hash_frame(f) != frame_hash.unwrap_or("") {
3428            return Ok(None);
3429        }
3430    }
3431    Ok(Some(v.subject))
3432}
3433
3434/// Verify a perception log against the robot's signed head: the attestation
3435/// must verify and carry `logHead` and `logCount`, and the log must link and
3436/// end at that head with exactly that many entries.
3437pub fn verify_perception_segment(
3438    entries: &[Value],
3439    attestation: &Value,
3440    keys: Keys<'_>,
3441    genesis_prev_hash_override: Option<&str>,
3442    now_iso: &str,
3443) -> Result<ChainResult> {
3444    let subject = match verify_perception_attestation(attestation, keys, None, now_iso)? {
3445        Some(s) => s,
3446        None => {
3447            return Ok(ChainResult {
3448                ok: false,
3449                reason: Some("attestation does not verify".into()),
3450            })
3451        }
3452    };
3453    if subject.get("logHead").is_none() || subject.get("logCount").is_none() {
3454        return Ok(ChainResult {
3455            ok: false,
3456            reason: Some("attestation does not anchor a log head and count".into()),
3457        });
3458    }
3459    Ok(verify_chain_against_head(
3460        entries,
3461        subject.get("logHead"),
3462        subject.get("logCount"),
3463        genesis_prev_hash_override,
3464    ))
3465}
3466
3467// ---------------------------------------------------------------------------
3468// Delegation lease (Phase 5.11)
3469// ---------------------------------------------------------------------------
3470
3471pub const DELEGATION_LEASE_TYPE: &str = "DelegationLeaseCredential";
3472
3473/// Parameters for [`build_delegation_lease`]. The issuer is the signer (an
3474/// authority or the holder of a parent lease); `robot_did` is the subject the
3475/// lease is granted to. `scope` is a physicalScope object (the same shape as a
3476/// `PhysicalCapabilityScope` credentialSubject.physicalScope). Leases are
3477/// short-lived by design, so the window is bounded by `valid_from`/`valid_until`.
3478/// Set `parent_lease_id` when sub-granting from another lease.
3479#[derive(Debug, Clone)]
3480pub struct BuildDelegationLease {
3481    pub issuer_did: String,
3482    pub robot_did: String,
3483    pub lease_id: String,
3484    pub scope: Value,
3485    pub parent_lease_id: Option<String>,
3486    pub valid_from: String,
3487    pub valid_until: String,
3488}
3489
3490/// Build a signed `DelegationLeaseCredential` granting `robot_did` a bounded
3491/// physical scope for a fixed window. The window is verifiable entirely offline.
3492pub fn build_delegation_lease(signer_seed: &[u8], params: &BuildDelegationLease) -> Result<Value> {
3493    if params.lease_id.is_empty() {
3494        return Err(CoreError::Json("lease_id is required".into()));
3495    }
3496    if !params.scope.is_object() {
3497        return Err(CoreError::Json(
3498            "scope must be a physicalScope object".into(),
3499        ));
3500    }
3501
3502    let mut subject = Map::new();
3503    subject.insert("id".into(), json!(params.robot_did));
3504    subject.insert("leaseId".into(), json!(params.lease_id));
3505    subject.insert("physicalScope".into(), params.scope.clone());
3506    if let Some(parent) = &params.parent_lease_id {
3507        subject.insert("parentLeaseId".into(), json!(parent));
3508    }
3509
3510    let mut cred = Map::new();
3511    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3512    cred.insert(
3513        "type".into(),
3514        json!(["VerifiableCredential", DELEGATION_LEASE_TYPE]),
3515    );
3516    cred.insert("issuer".into(), json!(params.issuer_did));
3517    cred.insert("validFrom".into(), json!(params.valid_from));
3518    cred.insert("validUntil".into(), json!(params.valid_until));
3519    cred.insert("credentialSubject".into(), Value::Object(subject));
3520
3521    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
3522    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
3523}
3524
3525/// Verify a `DelegationLeaseCredential` offline: the issuer's proof bound to the
3526/// issuer (`keys` is a `{did: key}` source, or the bare key of a did:key
3527/// issuer), validFrom and validUntil both present with `now_iso` inside, the
3528/// lease is for `expected_robot` (required), it carries a `leaseId` and a
3529/// well-formed scope, the issuer is in `trusted_issuers` when given, and (when
3530/// `parent_scope` is supplied) the scope attenuates the parent. Returns the
3531/// credentialSubject on success, `None` if invalid.
3532pub fn verify_delegation_lease(
3533    credential: &Value,
3534    keys: Keys<'_>,
3535    expected_robot: &str,
3536    parent_scope: Option<&Value>,
3537    trusted_issuers: Option<&HashSet<String>>,
3538    now_iso: &str,
3539) -> Result<Option<Value>> {
3540    if expected_robot.is_empty() {
3541        return Err(CoreError::Json("expected_robot is required".into()));
3542    }
3543    let now = rv::require_now(now_iso)?;
3544    let opts = VerifyOptions {
3545        trusted_issuers,
3546        ..VerifyOptions::window(Window::Required)
3547    };
3548    let v = match rv::verify_robotics_credential(
3549        credential,
3550        keys,
3551        Some(DELEGATION_LEASE_TYPE),
3552        now,
3553        opts,
3554    ) {
3555        Ok(v) => v,
3556        Err(_) => return Ok(None),
3557    };
3558    if v.subject.get("id").and_then(|x| x.as_str()) != Some(expected_robot)
3559        || non_empty_str(&v.subject, "leaseId").is_none()
3560    {
3561        return Ok(None);
3562    }
3563    let scope = match v.subject.get("physicalScope") {
3564        Some(sc) if sc.is_object() && scope_problems(sc).is_empty() => sc,
3565        _ => return Ok(None),
3566    };
3567    if parent_scope.is_some_and(|p| !attenuates(p, scope)) {
3568        return Ok(None);
3569    }
3570    Ok(Some(v.subject))
3571}
3572
3573/// Verify a chain of leases from a trusted root down to `expected_robot`
3574/// (`leases` runs root to leaf). The root is issued by one of `root_issuers`
3575/// and has no `parentLeaseId`; each later lease names the previous `leaseId`
3576/// as its `parentLeaseId`, is issued by the party the previous lease was
3577/// granted to, has a window inside the previous window, and attenuates the
3578/// previous scope. Every lease is current at `now_iso`; the leaf is for
3579/// `expected_robot`. Returns the leaf subject on success.
3580pub fn verify_lease_chain(
3581    leases: &[Value],
3582    keys: Keys<'_>,
3583    expected_robot: &str,
3584    root_issuers: &HashSet<String>,
3585    now_iso: &str,
3586) -> Result<Option<Value>> {
3587    rv::require_now(now_iso)?;
3588    if leases.is_empty() || root_issuers.is_empty() {
3589        return Ok(None);
3590    }
3591    let mut prev: Option<(&Value, Value)> = None;
3592    for (i, lease) in leases.iter().enumerate() {
3593        let holder = lease
3594            .get("credentialSubject")
3595            .and_then(|s| s.get("id"))
3596            .and_then(|v| v.as_str())
3597            .unwrap_or("");
3598        let target = if i + 1 == leases.len() {
3599            expected_robot
3600        } else {
3601            holder
3602        };
3603        if target.is_empty() {
3604            return Ok(None);
3605        }
3606        let parent_scope = prev.as_ref().and_then(|(_, ps)| ps.get("physicalScope"));
3607        // The root must be one of `root_issuers`; each child must be issued by
3608        // the holder the verified parent names. Both are named sets, so did:key
3609        // parties verify under their own keys with no key source.
3610        let holder_set: HashSet<String> = prev
3611            .as_ref()
3612            .and_then(|(_, ps)| ps.get("id"))
3613            .and_then(|v| v.as_str())
3614            .filter(|h| !h.is_empty())
3615            .map(|h| [h.to_string()].into_iter().collect())
3616            .unwrap_or_default();
3617        let subject = match verify_delegation_lease(
3618            lease,
3619            keys,
3620            target,
3621            parent_scope,
3622            Some(if prev.is_none() {
3623                root_issuers
3624            } else {
3625                &holder_set
3626            }),
3627            now_iso,
3628        )? {
3629            Some(s) => s,
3630            None => return Ok(None),
3631        };
3632        match &prev {
3633            Some((p_lease, p_sub)) => {
3634                if subject.get("parentLeaseId") != p_sub.get("leaseId") {
3635                    return Ok(None);
3636                }
3637                if rv::issuer_id(lease.get("issuer")) != p_sub.get("id").and_then(|v| v.as_str()) {
3638                    return Ok(None);
3639                }
3640                let t = |c: &Value, k: &str| rv::time_ns(c.get(k));
3641                if t(lease, "validFrom") < t(p_lease, "validFrom")
3642                    || t(lease, "validUntil") > t(p_lease, "validUntil")
3643                {
3644                    return Ok(None);
3645                }
3646            }
3647            None => {
3648                if subject.get("parentLeaseId").is_some() {
3649                    return Ok(None);
3650                }
3651            }
3652        }
3653        prev = Some((lease, subject));
3654    }
3655    Ok(prev.map(|(_, s)| s))
3656}
3657
3658/// Decide whether a verified lease permits a proposed physical action. The full
3659/// lease `credential` is required and is verified again here (`keys` and
3660/// `trusted_issuers` as in [`verify_delegation_lease`], with `subject.id` as the
3661/// expected robot), so its window is read from signed data: a copy with a
3662/// re-dated `validUntil` no longer verifies. Its subject must equal `subject`,
3663/// its window must contain `now_iso`, and the action must fit the scope.
3664pub fn lease_permits(
3665    subject: &Value,
3666    action: &PhysicalAction,
3667    credential: Option<&Value>,
3668    keys: Keys<'_>,
3669    trusted_issuers: Option<&HashSet<String>>,
3670    now_iso: &str,
3671) -> Result<bool> {
3672    let now = rv::require_now(now_iso)?;
3673    let cred = match credential {
3674        Some(c) if c.is_object() && subject.is_object() => c,
3675        _ => return Ok(false),
3676    };
3677    let robot = match subject.get("id").and_then(|v| v.as_str()) {
3678        Some(r) if !r.is_empty() => r,
3679        _ => return Ok(false),
3680    };
3681    match verify_delegation_lease(cred, keys, robot, None, trusted_issuers, now_iso)? {
3682        Some(v) if &v == subject => {}
3683        _ => return Ok(false),
3684    }
3685    if rv::window_reason(cred, Window::Required, now, 0).is_some() {
3686        return Ok(false);
3687    }
3688    match subject.get("physicalScope") {
3689        Some(scope) if scope.is_object() => Ok(check_physical_action(scope, action).ok),
3690        _ => Ok(false),
3691    }
3692}
3693
3694// ---------------------------------------------------------------------------
3695// Physical quorum (Phase 5.12)
3696// ---------------------------------------------------------------------------
3697
3698pub const ACTION_APPROVAL_TYPE: &str = "PhysicalActionApprovalCredential";
3699pub const APPROVE: &str = "approve";
3700pub const REJECT: &str = "reject";
3701/// How long an approval lasts when its builder gives no end.
3702pub const DEFAULT_APPROVAL_SECONDS: i64 = 300;
3703/// The longest approval lifetime a verifier accepts.
3704pub const MAX_APPROVAL_SECONDS: i64 = 900;
3705
3706/// Parameters for [`build_action_approval`]. The approver is the signer; the
3707/// approval is over a specific physical action `action_id` that `robot_did`
3708/// would perform. `decision` is "approve" or "reject".
3709#[derive(Debug, Clone)]
3710pub struct BuildActionApproval {
3711    pub approver_did: String,
3712    pub action_id: String,
3713    pub robot_did: String,
3714    pub decision: String,
3715    pub valid_from: String,
3716    pub valid_until: Option<String>,
3717}
3718
3719/// Build a signed `PhysicalActionApprovalCredential` by one approver for a
3720/// specific physical action.
3721pub fn build_action_approval(approver_seed: &[u8], params: &BuildActionApproval) -> Result<Value> {
3722    if params.decision != APPROVE && params.decision != REJECT {
3723        return Err(CoreError::Json(format!(
3724            "decision must be {APPROVE:?} or {REJECT:?}, got {:?}",
3725            params.decision
3726        )));
3727    }
3728    if params.action_id.is_empty() {
3729        return Err(CoreError::Json("action_id is required".into()));
3730    }
3731
3732    let mut subject = Map::new();
3733    subject.insert("id".into(), json!(params.approver_did));
3734    subject.insert("actionId".into(), json!(params.action_id));
3735    subject.insert("robotDid".into(), json!(params.robot_did));
3736    subject.insert("decision".into(), json!(params.decision));
3737
3738    let mut cred = Map::new();
3739    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3740    cred.insert(
3741        "type".into(),
3742        json!(["VerifiableCredential", ACTION_APPROVAL_TYPE]),
3743    );
3744    cred.insert("issuer".into(), json!(params.approver_did));
3745    cred.insert("validFrom".into(), json!(params.valid_from));
3746    // An approval is short-lived: without an explicit end it lasts
3747    // DEFAULT_APPROVAL_SECONDS, and a verifier refuses one without validUntil.
3748    let valid_until = match &params.valid_until {
3749        Some(vu) => vu.clone(),
3750        None => crate::time::epoch_seconds_to_iso(
3751            crate::time::iso_to_epoch_seconds(&params.valid_from)? + DEFAULT_APPROVAL_SECONDS,
3752        ),
3753    };
3754    cred.insert("validUntil".into(), json!(valid_until));
3755    cred.insert("credentialSubject".into(), Value::Object(subject));
3756
3757    let opts = BuildProofOptions::new(format!("{}#key-1", params.approver_did), &params.valid_from);
3758    data_integrity::sign(&Value::Object(cred), approver_seed, &opts)
3759}
3760
3761/// One approver's public key, looked up by issuer DID, for
3762/// [`verify_action_authorization`].
3763#[derive(Debug, Clone)]
3764pub struct ApproverKey {
3765    pub did: String,
3766    pub public_key: Vec<u8>,
3767}
3768
3769/// Verify that a high-consequence physical action is authorized by a quorum.
3770///
3771/// Each approval must carry a proof bound to its issuer and verified with the
3772/// issuer's key from `approver_keys`, name the issuer as its subject, match
3773/// `action_id` and `robot_did`, and carry both validFrom and validUntil with
3774/// `now_iso` inside and a lifetime of at most [`MAX_APPROVAL_SECONDS`]. When
3775/// `approver_set` is supplied, the approver must be in it. Each approver's
3776/// latest decision counts (at the same instant a rejection wins); any latest
3777/// rejection vetoes the action. Otherwise it is authorized when at least
3778/// `threshold` approvers with DISTINCT signing keys approve: two DIDs mapped to
3779/// the same key count once. Returns `(authorized, sorted approving DIDs)`.
3780pub fn verify_action_authorization(
3781    approvals: &[Value],
3782    action_id: &str,
3783    robot_did: &str,
3784    approver_keys: &[ApproverKey],
3785    threshold: i64,
3786    approver_set: Option<&HashSet<String>>,
3787    now_iso: &str,
3788) -> Result<(bool, Vec<String>)> {
3789    verify_action_authorization_with(
3790        approvals,
3791        action_id,
3792        robot_did,
3793        approver_keys,
3794        threshold,
3795        approver_set,
3796        MAX_APPROVAL_SECONDS,
3797        now_iso,
3798    )
3799}
3800
3801/// [`verify_action_authorization`] with the caller's longest approval
3802/// lifetime instead of [`MAX_APPROVAL_SECONDS`].
3803#[allow(clippy::too_many_arguments)]
3804pub fn verify_action_authorization_with(
3805    approvals: &[Value],
3806    action_id: &str,
3807    robot_did: &str,
3808    approver_keys: &[ApproverKey],
3809    threshold: i64,
3810    approver_set: Option<&HashSet<String>>,
3811    max_approval_seconds: i64,
3812    now_iso: &str,
3813) -> Result<(bool, Vec<String>)> {
3814    if max_approval_seconds < 1 {
3815        return Err(CoreError::Json(
3816            "max_approval_seconds must be at least 1".into(),
3817        ));
3818    }
3819    if threshold < 1 {
3820        return Err(CoreError::Json("threshold must be at least 1".into()));
3821    }
3822    let now = rv::require_now(now_iso)?;
3823    let map: std::collections::BTreeMap<String, Vec<u8>> =
3824        Keys::map_of(approver_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
3825    let keys = Keys::Map(&map);
3826
3827    // The approver set is a named member set: with no key on file, its
3828    // did:key members verify under their own keys. A freshly minted did:key
3829    // is never an approver by itself.
3830    let opts = VerifyOptions {
3831        trusted_issuers: approver_set,
3832        ..VerifyOptions::window(Window::Required)
3833    };
3834    let mut latest: std::collections::BTreeMap<String, (i128, bool)> =
3835        std::collections::BTreeMap::new();
3836    for approval in approvals {
3837        let mut early = false;
3838        let v = match rv::verify_robotics_credential(
3839            approval,
3840            keys,
3841            Some(ACTION_APPROVAL_TYPE),
3842            now,
3843            opts,
3844        ) {
3845            Ok(v) if issuer_is_subject(&v) => v,
3846            Err(why) if why == "credential window: not_yet_valid" => {
3847                // A rejection dated slightly ahead of the verifier's clock
3848                // still vetoes: re-check everything else at its own start. An
3849                // early approval never counts.
3850                let at = match rv::time_ns(approval.get("validFrom")) {
3851                    Some(t) => t,
3852                    None => continue,
3853                };
3854                match rv::verify_robotics_credential(
3855                    approval,
3856                    keys,
3857                    Some(ACTION_APPROVAL_TYPE),
3858                    at,
3859                    opts,
3860                ) {
3861                    Ok(v) if issuer_is_subject(&v) => {
3862                        early = true;
3863                        v
3864                    }
3865                    _ => continue,
3866                }
3867            }
3868            _ => continue,
3869        };
3870        if v.subject.get("actionId").and_then(|x| x.as_str()) != Some(action_id)
3871            || v.subject.get("robotDid").and_then(|x| x.as_str()) != Some(robot_did)
3872        {
3873            continue;
3874        }
3875        let reject = match v.subject.get("decision").and_then(|x| x.as_str()) {
3876            Some(APPROVE) => false,
3877            Some(REJECT) => true,
3878            _ => continue,
3879        };
3880        if early && !reject {
3881            continue;
3882        }
3883        if let Some(set) = approver_set {
3884            if !set.contains(&v.issuer) {
3885                continue;
3886            }
3887        }
3888        let (start, end) = match (
3889            rv::time_ns(approval.get("validFrom")),
3890            rv::time_ns(approval.get("validUntil")),
3891        ) {
3892            (Some(a), Some(b)) => (a, b),
3893            _ => continue,
3894        };
3895        if end - start > i128::from(max_approval_seconds) * 1_000_000_000 {
3896            continue;
3897        }
3898        let newer = match latest.get(&v.issuer) {
3899            None => true,
3900            Some((t, _)) => start > *t || (start == *t && reject),
3901        };
3902        if newer {
3903            latest.insert(v.issuer, (start, reject));
3904        }
3905    }
3906
3907    if latest.values().any(|(_, reject)| *reject) {
3908        return Ok((false, Vec::new()));
3909    }
3910    let mut approvers: Vec<String> = Vec::new();
3911    let mut seen: HashSet<Vec<u8>> = HashSet::new();
3912    for issuer in latest.keys() {
3913        let raw = match map.get(issuer) {
3914            Some(k) => k.clone(),
3915            None => match crate::keys::did_key_to_ed25519(issuer) {
3916                Ok(k) if issuer.starts_with("did:key:") => k,
3917                _ => continue,
3918            },
3919        };
3920        if seen.insert(raw) {
3921            approvers.push(issuer.clone());
3922        }
3923    }
3924    approvers.sort();
3925    Ok((approvers.len() as i64 >= threshold, approvers))
3926}
3927
3928// ---------------------------------------------------------------------------
3929// Robot lifecycle: ownership transfer, key rotation, decommission (Phase 5.13)
3930// ---------------------------------------------------------------------------
3931
3932pub const OWNERSHIP_TRANSFER_TYPE: &str = "RobotOwnershipTransferCredential";
3933pub const KEY_ROTATION_TYPE: &str = "RobotKeyRotationCredential";
3934pub const DECOMMISSION_TYPE: &str = "RobotDecommissionCredential";
3935
3936/// Parameters for [`build_ownership_transfer`]. The signer is the current owner;
3937/// `from_owner` defaults to `issuer_did` (the current owner's DID). Setting
3938/// `prev_transfer_id` links this transfer to the previous one, forming a chain:
3939/// it must be the previous transfer's `id`. `credential_id` is this transfer's
3940/// own `id` (the caller supplies it; use a fresh `urn:uuid:`).
3941#[derive(Debug, Clone)]
3942pub struct BuildOwnershipTransfer {
3943    pub issuer_did: String,
3944    pub robot_did: String,
3945    pub to_owner: String,
3946    pub from_owner: Option<String>,
3947    pub prev_transfer_id: Option<String>,
3948    pub credential_id: String,
3949    pub valid_from: String,
3950}
3951
3952/// Build a signed transfer of `robot_did` from the current owner to `to_owner`.
3953/// The signer is the current owner; `from_owner` defaults to `issuer_did`.
3954pub fn build_ownership_transfer(
3955    current_owner_seed: &[u8],
3956    params: &BuildOwnershipTransfer,
3957) -> Result<Value> {
3958    if params.robot_did.is_empty() || params.to_owner.is_empty() {
3959        return Err(CoreError::Json(
3960            "robot_did and to_owner are required".into(),
3961        ));
3962    }
3963    if params.credential_id.is_empty() {
3964        return Err(CoreError::Json("credential_id is required".into()));
3965    }
3966    let seller = params
3967        .from_owner
3968        .clone()
3969        .unwrap_or_else(|| params.issuer_did.clone());
3970
3971    let mut subject = Map::new();
3972    subject.insert("id".into(), json!(params.robot_did));
3973    subject.insert("fromOwner".into(), json!(seller));
3974    subject.insert("toOwner".into(), json!(params.to_owner));
3975    if let Some(prev) = &params.prev_transfer_id {
3976        subject.insert("prevTransferId".into(), json!(prev));
3977    }
3978
3979    let mut cred = Map::new();
3980    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3981    cred.insert("id".into(), json!(params.credential_id));
3982    cred.insert(
3983        "type".into(),
3984        json!(["VerifiableCredential", OWNERSHIP_TRANSFER_TYPE]),
3985    );
3986    cred.insert("issuer".into(), json!(params.issuer_did));
3987    cred.insert("validFrom".into(), json!(params.valid_from));
3988    cred.insert("credentialSubject".into(), Value::Object(subject));
3989
3990    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
3991    data_integrity::sign(&Value::Object(cred), current_owner_seed, &opts)
3992}
3993
3994fn non_empty_str<'v>(v: &'v Value, key: &str) -> Option<&'v str> {
3995    v.get(key)
3996        .and_then(|x| x.as_str())
3997        .filter(|s| !s.is_empty())
3998}
3999
4000/// Verify a transfer: the current owner's proof bound to the issuer, the
4001/// issuer is the `fromOwner` (only the current owner can transfer the robot),
4002/// `toOwner` and the robot `id` are non-empty strings, validFrom no later than
4003/// `now_iso`, and (when given) the transfer is for `robot_did`. `owner_keys` is
4004/// a `{owner_did: key}` source (or the bare key of a did:key owner).
4005pub fn verify_ownership_transfer(
4006    credential: &Value,
4007    owner_keys: Keys<'_>,
4008    robot_did: Option<&str>,
4009    now_iso: &str,
4010) -> Result<Option<Value>> {
4011    let v = match bound(
4012        credential,
4013        owner_keys,
4014        OWNERSHIP_TRANSFER_TYPE,
4015        now_iso,
4016        Window::FromRequired,
4017    )? {
4018        Some(v) => v,
4019        None => return Ok(None),
4020    };
4021    let ok = non_empty_str(&v.subject, "toOwner").is_some()
4022        && non_empty_str(&v.subject, "fromOwner") == Some(v.issuer.as_str())
4023        && non_empty_str(&v.subject, "id").is_some()
4024        && robot_did.is_none_or(|r| v.subject.get("id").and_then(|x| x.as_str()) == Some(r));
4025    Ok(if ok { Some(v.subject) } else { None })
4026}
4027
4028/// One owner's public key, looked up by owner DID, for [`verify_custody_chain`].
4029#[derive(Debug, Clone)]
4030pub struct OwnerKey {
4031    pub did: String,
4032    pub public_key: Vec<u8>,
4033}
4034
4035/// Verify an ordered list of transfer credentials forms a valid chain of custody
4036/// for `robot_did`: every link verifies under the owner who signed it (keys
4037/// from `public_keys`), names the previous link's `id` as its
4038/// `prevTransferId`, is dated no earlier than the previous link, each
4039/// `toOwner` is the next link's `fromOwner`, and the first `fromOwner` is
4040/// `origin_owner`. Returns `(ok, current_owner)`.
4041///
4042/// `origin_owner` is required: with no known first owner, anyone could sign a
4043/// first transfer of any robot from themselves. Without it the chain is
4044/// refused. Each link's signer is pinned (the origin, then each `toOwner`), so
4045/// a did:key owner verifies under its own key even with no entry in
4046/// `public_keys`.
4047pub fn verify_custody_chain(
4048    transfers: &[Value],
4049    public_keys: &[OwnerKey],
4050    robot_did: &str,
4051    origin_owner: Option<&str>,
4052    now_iso: &str,
4053) -> Result<(bool, Option<String>)> {
4054    rv::require_now(now_iso)?;
4055    if robot_did.is_empty() || origin_owner.is_none_or(str::is_empty) {
4056        return Ok((false, None));
4057    }
4058    let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
4059    let mut expected_from: Option<String> = origin_owner.map(String::from);
4060    let mut current_owner: Option<String> = origin_owner.map(String::from);
4061    let mut prev_id: Option<String> = None;
4062    let mut prev_time: Option<i128> = None;
4063    for (i, transfer) in transfers.iter().enumerate() {
4064        let keys = rv::pin_if_keyless(Keys::Map(&map), expected_from.as_deref());
4065        let subject = match verify_ownership_transfer(transfer, keys, Some(robot_did), now_iso)? {
4066            Some(s) => s,
4067            None => return Ok((false, None)),
4068        };
4069        if let Some(expected) = &expected_from {
4070            if subject.get("fromOwner").and_then(|v| v.as_str()) != Some(expected.as_str()) {
4071                return Ok((false, None));
4072            }
4073        }
4074        let this_time = match rv::time_ns(transfer.get("validFrom")) {
4075            Some(t) if prev_time.is_none_or(|p| t >= p) => t,
4076            _ => return Ok((false, None)),
4077        };
4078        if i > 0 {
4079            match &prev_id {
4080                Some(p) if subject.get("prevTransferId").and_then(|v| v.as_str()) == Some(p) => {}
4081                _ => return Ok((false, None)),
4082            }
4083        }
4084        prev_id = non_empty_str(transfer, "id").map(String::from);
4085        prev_time = Some(this_time);
4086        current_owner = subject
4087            .get("toOwner")
4088            .and_then(|v| v.as_str())
4089            .map(String::from);
4090        expected_from = current_owner.clone();
4091    }
4092    Ok((true, current_owner))
4093}
4094
4095/// Parameters for [`build_key_rotation`]. The credential is signed by the old key
4096/// (the `signer_seed`) and issued under `robot_did`; the old key's public multibase
4097/// is recorded as `previousKey` and `new_key_multibase` as the authorized successor.
4098#[derive(Debug, Clone)]
4099pub struct BuildKeyRotation {
4100    pub robot_did: String,
4101    pub new_key_multibase: String,
4102    pub reason: Option<String>,
4103    pub valid_from: String,
4104}
4105
4106/// Build a key-rotation credential in which the robot's current (old) key
4107/// authorizes a new key. Signed by the old key, so anyone trusting the old key
4108/// can trust the new one. `old_key_seed` is the seed of the current key.
4109pub fn build_key_rotation(old_key_seed: &[u8], params: &BuildKeyRotation) -> Result<Value> {
4110    if params.new_key_multibase.is_empty() {
4111        return Err(CoreError::Json("new_key_multibase is required".into()));
4112    }
4113    let old_kp = keys::Ed25519KeyPair::from_seed_slice(old_key_seed)?;
4114
4115    let mut subject = Map::new();
4116    subject.insert("id".into(), json!(params.robot_did));
4117    subject.insert("previousKey".into(), json!(old_kp.public_multikey()));
4118    subject.insert("newKey".into(), json!(params.new_key_multibase));
4119    if let Some(reason) = &params.reason {
4120        subject.insert("reason".into(), json!(reason));
4121    }
4122
4123    let mut cred = Map::new();
4124    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4125    cred.insert(
4126        "type".into(),
4127        json!(["VerifiableCredential", KEY_ROTATION_TYPE]),
4128    );
4129    cred.insert("issuer".into(), json!(params.robot_did));
4130    cred.insert("validFrom".into(), json!(params.valid_from));
4131    cred.insert("credentialSubject".into(), Value::Object(subject));
4132
4133    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
4134    data_integrity::sign(&Value::Object(cred), old_key_seed, &opts)
4135}
4136
4137/// The raw Ed25519 key of a `z...` multikey, or `None`.
4138fn multikey_raw(v: Option<&Value>) -> Option<Vec<u8>> {
4139    let s = v.and_then(|x| x.as_str()).filter(|s| s.starts_with('z'))?;
4140    match multikey::decode(s) {
4141        Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => Some(d.raw_key),
4142        _ => None,
4143    }
4144}
4145
4146/// Verify a key rotation: the robot's OLD key signed it, binding the new key.
4147///
4148/// The rotation is a self-attestation: the issuer must be the robot
4149/// (`credentialSubject.id`), `previousKey` must decode to exactly the key the
4150/// caller trusts as the robot's current key (`old_keys`: a bare key, or a
4151/// `{robot_did: key}` source), the proof is checked under that key, and
4152/// `newKey` must decode and differ. When given, the rotation must be for
4153/// `robot_did`. Returns the credentialSubject (with `newKey` the successor).
4154pub fn verify_key_rotation(
4155    credential: &Value,
4156    old_keys: Keys<'_>,
4157    robot_did: Option<&str>,
4158    now_iso: &str,
4159) -> Result<Option<Value>> {
4160    let now = rv::require_now(now_iso)?;
4161    let issuer = match rv::issuer_id(credential.get("issuer")) {
4162        Some(i) => i.to_string(),
4163        None => return Ok(None),
4164    };
4165    let trusted: Option<Vec<u8>> = match old_keys {
4166        Keys::Embedded | Keys::Pinned(_) => None,
4167        Keys::Bare(k) => Some(k.to_vec()),
4168        Keys::One(did, k) => (did == issuer).then(|| k.to_vec()),
4169        Keys::Map(m) => m.get(&issuer).cloned(),
4170        Keys::Resolver(f) => f(&issuer),
4171    };
4172    let trusted = match trusted {
4173        Some(t) if t.len() == 32 => t,
4174        _ => return Ok(None),
4175    };
4176    let previous = credential
4177        .get("credentialSubject")
4178        .and_then(|s| s.get("previousKey"));
4179    if multikey_raw(previous) != Some(trusted.clone()) {
4180        return Ok(None);
4181    }
4182    let v = match rv::verify_robotics_credential(
4183        credential,
4184        Keys::One(&issuer, &trusted),
4185        Some(KEY_ROTATION_TYPE),
4186        now,
4187        VerifyOptions::window(Window::FromRequired),
4188    ) {
4189        Ok(v) if issuer_is_subject(&v) => v,
4190        _ => return Ok(None),
4191    };
4192    if robot_did.is_some_and(|r| r != v.issuer) {
4193        return Ok(None);
4194    }
4195    match multikey_raw(v.subject.get("newKey")) {
4196        Some(n) if n != trusted => Ok(Some(v.subject)),
4197        _ => Ok(None),
4198    }
4199}
4200
4201/// Verify an ordered list of key rotations forms one linear key history from
4202/// `origin_key_multibase`. Each rotation must be signed by the key it rotates
4203/// from, decoded from the multibase itself; every rotation is for the same
4204/// robot (`robot_did` when given, else the first rotation's robot) and dated no
4205/// earlier than the one before; a key that appears twice (a fork or a cycle)
4206/// is refused. Returns `(ok, current_key)`.
4207pub fn verify_key_history(
4208    rotations: &[Value],
4209    origin_key_multibase: &str,
4210    robot_did: Option<&str>,
4211    now_iso: &str,
4212) -> Result<(bool, Option<String>)> {
4213    rv::require_now(now_iso)?;
4214    let origin = match multikey_raw(Some(&json!(origin_key_multibase))) {
4215        Some(o) => o,
4216        None => return Ok((false, None)),
4217    };
4218    let mut current_key = origin_key_multibase.to_string();
4219    let mut current_raw = origin.clone();
4220    let mut seen: HashSet<Vec<u8>> = HashSet::from([origin]);
4221    let mut pinned: Option<String> = robot_did.map(String::from);
4222    let mut prev_time: Option<i128> = None;
4223    for rotation in rotations {
4224        let subject = match verify_key_rotation(
4225            rotation,
4226            Keys::Bare(&current_raw),
4227            pinned.as_deref(),
4228            now_iso,
4229        )? {
4230            Some(s) => s,
4231            None => return Ok((false, None)),
4232        };
4233        if pinned.is_none() {
4234            pinned = subject.get("id").and_then(|v| v.as_str()).map(String::from);
4235        }
4236        match rv::time_ns(rotation.get("validFrom")) {
4237            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
4238            _ => return Ok((false, None)),
4239        }
4240        let new_raw = match multikey_raw(subject.get("newKey")) {
4241            Some(n) if !seen.contains(&n) => n,
4242            _ => return Ok((false, None)),
4243        };
4244        seen.insert(new_raw.clone());
4245        current_raw = new_raw;
4246        current_key = subject
4247            .get("newKey")
4248            .and_then(|v| v.as_str())
4249            .unwrap_or("")
4250            .to_string();
4251    }
4252    Ok((true, Some(current_key)))
4253}
4254
4255/// Parameters for [`build_decommission`]. The signer is the owner or an authority;
4256/// `final_disposition` records the outcome (for example recycled, destroyed, or
4257/// transferred to parts). When `valid_until` is set it bounds the credential.
4258#[derive(Debug, Clone)]
4259pub struct BuildDecommission {
4260    pub issuer_did: String,
4261    pub robot_did: String,
4262    pub reason: String,
4263    pub final_disposition: Option<String>,
4264    pub valid_from: String,
4265    pub valid_until: Option<String>,
4266}
4267
4268/// Build a signed decommission credential retiring `robot_did`. After
4269/// decommissioning, a verifier should refuse to trust the robot. `decommissionedBy`
4270/// is the issuer DID.
4271pub fn build_decommission(signer_seed: &[u8], params: &BuildDecommission) -> Result<Value> {
4272    if params.reason.is_empty() {
4273        return Err(CoreError::Json("reason is required".into()));
4274    }
4275    let mut subject = Map::new();
4276    subject.insert("id".into(), json!(params.robot_did));
4277    subject.insert("reason".into(), json!(params.reason));
4278    subject.insert("decommissionedBy".into(), json!(params.issuer_did));
4279    if let Some(disposition) = &params.final_disposition {
4280        subject.insert("finalDisposition".into(), json!(disposition));
4281    }
4282
4283    let mut cred = Map::new();
4284    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4285    cred.insert(
4286        "type".into(),
4287        json!(["VerifiableCredential", DECOMMISSION_TYPE]),
4288    );
4289    cred.insert("issuer".into(), json!(params.issuer_did));
4290    cred.insert("validFrom".into(), json!(params.valid_from));
4291    if let Some(vu) = &params.valid_until {
4292        cred.insert("validUntil".into(), json!(vu));
4293    }
4294    cred.insert("credentialSubject".into(), Value::Object(subject));
4295
4296    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
4297    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
4298}
4299
4300/// Verify a decommission credential: the proof bound to the issuer, the
4301/// window at `now_iso` (validFrom required), `decommissionedBy` (when present)
4302/// equal to the issuer, the issuer in `trusted_authorities` when supplied, and
4303/// (when given) the credential is about `robot_did`.
4304pub fn verify_decommission(
4305    credential: &Value,
4306    keys: Keys<'_>,
4307    trusted_authorities: Option<&HashSet<String>>,
4308    robot_did: Option<&str>,
4309    now_iso: &str,
4310) -> Result<Option<Value>> {
4311    let now = rv::require_now(now_iso)?;
4312    let opts = VerifyOptions {
4313        trusted_issuers: trusted_authorities,
4314        ..VerifyOptions::window(Window::FromRequired)
4315    };
4316    let v = match rv::verify_robotics_credential(
4317        credential,
4318        keys,
4319        Some(DECOMMISSION_TYPE),
4320        now,
4321        opts,
4322    ) {
4323        Ok(v) => v,
4324        Err(_) => return Ok(None),
4325    };
4326    if let Some(by) = v.subject.get("decommissionedBy") {
4327        if by.as_str() != Some(v.issuer.as_str()) {
4328            return Ok(None);
4329        }
4330    }
4331    if robot_did.is_some_and(|r| v.subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
4332        return Ok(None);
4333    }
4334    Ok(Some(v.subject))
4335}
4336
4337// ---------------------------------------------------------------------------
4338// Regulatory conformance profiles (Phase 5.14)
4339// ---------------------------------------------------------------------------
4340//
4341// A conformance profile is a machine-checkable mapping from Vouch robotics
4342// credentials to the clauses of a public safety or AI regulation. Given the
4343// credentials a robot presents, the checker reports which clauses are satisfied
4344// and cites each one, and an issuer can sign a point-in-time conformance
4345// attestation an auditor or notified body can consume. The profiles are plain
4346// data so every language reproduces them identically.
4347//
4348// This is the open layer: declarative profiles, a deterministic checker, and a
4349// signed point-in-time attestation over the full report. It is a reference
4350// crosswalk to make conformance verifiable in the open, not legal advice.
4351
4352pub const CONFORMANCE_ATTESTATION_TYPE: &str = "RobotConformanceAttestation";
4353
4354/// How well-sourced a requirement's clause citation is. A profile can be a
4355/// useful crosswalk while its citations are only as good as the sources that
4356/// were available, and a reader is entitled to know which. Every report and
4357/// every signed attestation carries these, so a conformance result never
4358/// implies more authority over the regulation than it has.
4359///
4360/// The clause text was read from the official published source.
4361pub const CITATION_VERIFIED_PRIMARY: &str = "verified-primary";
4362/// The mapping is believed sound, but the clause number comes from secondary
4363/// sources rather than the standard or official journal itself. The default,
4364/// because it is the honest default.
4365pub const CITATION_UNVERIFIED_SECONDARY: &str = "unverified-secondary";
4366/// Not a clause reference at all, only a description of the topic. An assessor
4367/// cannot look it up.
4368pub const CITATION_DESCRIPTIVE: &str = "descriptive";
4369
4370/// Every citation provenance value, in report order.
4371pub const CITATION_STATUSES: &[&str] = &[
4372    CITATION_VERIFIED_PRIMARY,
4373    CITATION_UNVERIFIED_SECONDARY,
4374    CITATION_DESCRIPTIVE,
4375];
4376
4377// Citation notes shared by several requirements. Macros rather than consts so
4378// they can be `concat!`-ed into the longer per-requirement notes, byte-for-byte
4379// identical with the Python, TypeScript and Go profiles.
4380macro_rules! iso_paywall_note {
4381    () => {
4382        "Clause number taken from secondary sources; the standard is paywalled \
4383         and the text has not been read."
4384    };
4385}
4386
4387macro_rules! iso_10218_note {
4388    () => {
4389        concat!(
4390            iso_paywall_note!(),
4391            " ISO 10218-1/-2:2011 were superseded by the 2025 editions (in \
4392             force 1 April 2025); this mapping still cites the 2011 clause \
4393             numbering and has not been migrated."
4394        )
4395    };
4396}
4397
4398macro_rules! oj_note {
4399    () => {
4400        "Article number taken from a third-party reproduction of the Official \
4401         Journal text, not from EUR-Lex itself."
4402    };
4403}
4404
4405macro_rules! ul_note {
4406    () => {
4407        "UL 3300 (now ANSI/CAN/UL 3300:2024) is paywalled and no clause \
4408         numbering was available; this names the topic only and cannot be \
4409         looked up."
4410    };
4411}
4412
4413/// One requirement in a profile: a clause of a regulation mapped to the
4414/// credential type and field paths that satisfy it.
4415struct ProfileRequirement {
4416    id: &'static str,
4417    clause: &'static str,
4418    title: &'static str,
4419    credential: &'static str,
4420    fields: &'static [&'static str],
4421    /// Subject paths that must hold boolean `true`, for requirements where mere
4422    /// presence is not evidence: a heartbeat reporting an envelope breach is not
4423    /// evidence of having stayed inside the envelope. This is the boolean subset
4424    /// of the `expect` map the Python, TypeScript and Go profiles carry; the
4425    /// built-in profiles use only boolean expectations.
4426    expect_true: &'static [&'static str],
4427    /// Provenance of the `clause` reference above, one of [`CITATION_STATUSES`].
4428    citation: &'static str,
4429    /// Anything a reader should know about the citation, such as a known
4430    /// conflict between sources.
4431    citation_note: Option<&'static str>,
4432}
4433
4434/// A built-in conformance profile: a regime, a version, and its requirements.
4435struct ConformanceProfile {
4436    regime: &'static str,
4437    version: &'static str,
4438    requirements: &'static [ProfileRequirement],
4439}
4440
4441const ISO_10218_REQUIREMENTS: &[ProfileRequirement] = &[
4442    ProfileRequirement {
4443        id: "iso10218-identification",
4444        clause: "ISO 10218-1:2011, 5.2",
4445        title: "Robot identification bound to its hardware",
4446        credential: "RobotIdentityCredential",
4447        fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
4448        expect_true: &[],
4449        citation: CITATION_UNVERIFIED_SECONDARY,
4450        citation_note: Some(iso_10218_note!()),
4451    },
4452    ProfileRequirement {
4453        id: "iso10218-software-integrity",
4454        clause: "ISO 10218-1:2011, 5.3",
4455        title: "Control software and configuration integrity",
4456        credential: "ModelProvenanceAttestation",
4457        fields: &["vla.weightsHash"],
4458        expect_true: &[],
4459        citation: CITATION_UNVERIFIED_SECONDARY,
4460        citation_note: Some(iso_10218_note!()),
4461    },
4462    ProfileRequirement {
4463        id: "iso10218-limits",
4464        clause: "ISO 10218-1:2011, 5.6",
4465        title: "Limiting of speed, force, and workspace",
4466        credential: "PhysicalCapabilityScope",
4467        fields: &[
4468            "physicalScope.maxForceN",
4469            "physicalScope.maxSpeedMps",
4470            "physicalScope.allowedZones",
4471        ],
4472        expect_true: &[],
4473        citation: CITATION_UNVERIFIED_SECONDARY,
4474        citation_note: Some(iso_10218_note!()),
4475    },
4476    ProfileRequirement {
4477        id: "iso10218-records",
4478        clause: "ISO 10218-2:2011, 5.2",
4479        title: "Records of safety-relevant events",
4480        credential: "RobotSafetyRecordCredential",
4481        fields: &["totalEvents", "logHead"],
4482        expect_true: &[],
4483        citation: CITATION_UNVERIFIED_SECONDARY,
4484        citation_note: Some(iso_10218_note!()),
4485    },
4486];
4487
4488const ISO_TS_15066_REQUIREMENTS: &[ProfileRequirement] = &[
4489    ProfileRequirement {
4490        id: "iso15066-power-force-limiting",
4491        clause: "ISO/TS 15066:2016, 5.5.4",
4492        title: "Power and force limiting near humans",
4493        credential: "PhysicalCapabilityScope",
4494        fields: &[
4495            "physicalScope.maxSpeedNearHumansMps",
4496            "physicalScope.maxForceN",
4497        ],
4498        expect_true: &[],
4499        citation: CITATION_UNVERIFIED_SECONDARY,
4500        citation_note: Some(concat!(
4501            iso_paywall_note!(),
4502            " Secondary sources disagree on whether power and force limiting \
4503             is 5.5.4 or 5.5.2; confirm against the published table of \
4504             contents before relying on the number."
4505        )),
4506    },
4507    ProfileRequirement {
4508        id: "iso15066-collaborative-workspace",
4509        clause: "ISO/TS 15066:2016, 5.5.2",
4510        title: "Defined collaborative workspace",
4511        credential: "PhysicalCapabilityScope",
4512        fields: &["physicalScope.allowedZones"],
4513        expect_true: &[],
4514        citation: CITATION_UNVERIFIED_SECONDARY,
4515        citation_note: Some(concat!(
4516            iso_paywall_note!(),
4517            " Shares the unresolved 5.5.2/5.5.4 numbering conflict with \
4518             iso15066-power-force-limiting."
4519        )),
4520    },
4521    ProfileRequirement {
4522        id: "iso15066-monitoring",
4523        clause: "ISO/TS 15066:2016, 5.2",
4524        title: "Continuous monitoring of the collaborative operation",
4525        credential: "RobotHeartbeatCredential",
4526        fields: &["motionDigest"],
4527        expect_true: &["motionDigest.withinEnvelope"],
4528        citation: CITATION_UNVERIFIED_SECONDARY,
4529        citation_note: Some(iso_paywall_note!()),
4530    },
4531];
4532
4533const EU_MACHINERY_REQUIREMENTS: &[ProfileRequirement] = &[
4534    ProfileRequirement {
4535        id: "eu-mr-identification",
4536        clause: "Reg (EU) 2023/1230, Annex III 1.7.4",
4537        title: "Machinery identification and traceability",
4538        credential: "RobotIdentityCredential",
4539        fields: &["make", "model", "serial"],
4540        expect_true: &[],
4541        citation: CITATION_UNVERIFIED_SECONDARY,
4542        citation_note: Some(oj_note!()),
4543    },
4544    ProfileRequirement {
4545        id: "eu-mr-software-integrity",
4546        clause: "Reg (EU) 2023/1230, Annex III 1.1.9",
4547        title: "Protection against corruption of safety software",
4548        credential: "ModelProvenanceAttestation",
4549        fields: &["vla.weightsHash", "vla.safetyPolicy"],
4550        expect_true: &[],
4551        citation: CITATION_UNVERIFIED_SECONDARY,
4552        citation_note: Some(concat!(
4553            oj_note!(),
4554            " The Annex III subclause for protection against corruption has \
4555             not been confirmed and may need to be re-pointed."
4556        )),
4557    },
4558    ProfileRequirement {
4559        id: "eu-mr-safe-limits",
4560        clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
4561        title: "Safety and reliability of control systems and limits",
4562        credential: "PhysicalCapabilityScope",
4563        fields: &["physicalScope.maxForceN"],
4564        expect_true: &[],
4565        citation: CITATION_UNVERIFIED_SECONDARY,
4566        citation_note: Some(oj_note!()),
4567    },
4568    ProfileRequirement {
4569        id: "eu-mr-records",
4570        clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
4571        title: "Recording of safety-relevant data",
4572        credential: "RobotSafetyRecordCredential",
4573        fields: &["totalEvents", "logHead"],
4574        expect_true: &[],
4575        citation: CITATION_UNVERIFIED_SECONDARY,
4576        citation_note: Some(oj_note!()),
4577    },
4578];
4579
4580const EU_AI_ACT_REQUIREMENTS: &[ProfileRequirement] = &[
4581    ProfileRequirement {
4582        id: "eu-aia-record-keeping",
4583        clause: "Reg (EU) 2024/1689, Art. 12",
4584        title: "Automatic recording of events (logging)",
4585        credential: "RobotSafetyRecordCredential",
4586        fields: &["logHead"],
4587        expect_true: &[],
4588        citation: CITATION_UNVERIFIED_SECONDARY,
4589        citation_note: Some(oj_note!()),
4590    },
4591    ProfileRequirement {
4592        id: "eu-aia-transparency",
4593        clause: "Reg (EU) 2024/1689, Art. 13",
4594        title: "Model and configuration transparency",
4595        credential: "ModelProvenanceAttestation",
4596        fields: &["vla.modelName", "vla.configHash"],
4597        expect_true: &[],
4598        citation: CITATION_UNVERIFIED_SECONDARY,
4599        citation_note: Some(oj_note!()),
4600    },
4601    ProfileRequirement {
4602        id: "eu-aia-human-oversight",
4603        clause: "Reg (EU) 2024/1689, Art. 14",
4604        title: "Human oversight through enforced operating limits",
4605        credential: "PhysicalCapabilityScope",
4606        fields: &["physicalScope.maxSpeedNearHumansMps"],
4607        expect_true: &[],
4608        citation: CITATION_UNVERIFIED_SECONDARY,
4609        citation_note: Some(concat!(
4610            oj_note!(),
4611            " Art. 14 also requires a means for the overseer to intervene or \
4612             stop the system, which an operating-limit scope alone does not \
4613             evidence."
4614        )),
4615    },
4616    ProfileRequirement {
4617        id: "eu-aia-accuracy-robustness",
4618        clause: "Reg (EU) 2024/1689, Art. 15",
4619        title: "Accuracy and robustness traceable to a known build",
4620        credential: "ModelProvenanceAttestation",
4621        fields: &["vla.weightsHash"],
4622        expect_true: &[],
4623        citation: CITATION_UNVERIFIED_SECONDARY,
4624        citation_note: Some(oj_note!()),
4625    },
4626];
4627
4628const UL_3300_REQUIREMENTS: &[ProfileRequirement] = &[
4629    ProfileRequirement {
4630        id: "ul3300-identity",
4631        clause: "UL 3300, identification",
4632        title: "Robot identity bound to its hardware",
4633        credential: "RobotIdentityCredential",
4634        fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
4635        expect_true: &[],
4636        citation: CITATION_DESCRIPTIVE,
4637        citation_note: Some(ul_note!()),
4638    },
4639    ProfileRequirement {
4640        id: "ul3300-operating-limits",
4641        clause: "UL 3300, operating limits",
4642        title: "Enforced speed and zone limits",
4643        credential: "PhysicalCapabilityScope",
4644        fields: &["physicalScope.maxSpeedMps", "physicalScope.allowedZones"],
4645        expect_true: &[],
4646        citation: CITATION_DESCRIPTIVE,
4647        citation_note: Some(ul_note!()),
4648    },
4649    ProfileRequirement {
4650        id: "ul3300-perception-integrity",
4651        clause: "UL 3300, sensing integrity",
4652        title: "Integrity of perception used for safe operation",
4653        credential: "PerceptionProvenanceCredential",
4654        fields: &["frameHash"],
4655        expect_true: &[],
4656        citation: CITATION_DESCRIPTIVE,
4657        citation_note: Some(ul_note!()),
4658    },
4659    ProfileRequirement {
4660        id: "ul3300-records",
4661        clause: "UL 3300, incident records",
4662        title: "Records of safety-relevant incidents",
4663        credential: "RobotSafetyRecordCredential",
4664        fields: &["totalEvents", "logHead"],
4665        expect_true: &[],
4666        citation: CITATION_DESCRIPTIVE,
4667        citation_note: Some(ul_note!()),
4668    },
4669];
4670
4671/// Return a built-in profile by id, or `None` if it is unknown. The five profiles
4672/// cover ISO 10218-1/-2 (industrial), ISO/TS 15066 (collaborative), the EU
4673/// Machinery Regulation 2023/1230, the EU AI Act high-risk requirements, and
4674/// UL 3300 (service and mobile robots).
4675fn conformance_profile(profile_id: &str) -> Option<ConformanceProfile> {
4676    match profile_id {
4677        "iso-10218" => Some(ConformanceProfile {
4678            regime: "ISO 10218-1/-2 industrial robots",
4679            version: "2011 (superseded by the 2025 editions; mapping not yet migrated)",
4680            requirements: ISO_10218_REQUIREMENTS,
4681        }),
4682        "iso-ts-15066" => Some(ConformanceProfile {
4683            regime: "ISO/TS 15066 collaborative robots",
4684            version: "2016",
4685            requirements: ISO_TS_15066_REQUIREMENTS,
4686        }),
4687        "eu-machinery-2023-1230" => Some(ConformanceProfile {
4688            regime: "EU Machinery Regulation 2023/1230",
4689            version: "2023",
4690            requirements: EU_MACHINERY_REQUIREMENTS,
4691        }),
4692        "eu-ai-act-high-risk" => Some(ConformanceProfile {
4693            regime: "EU AI Act high-risk systems",
4694            version: "2024",
4695            requirements: EU_AI_ACT_REQUIREMENTS,
4696        }),
4697        "ul-3300" => Some(ConformanceProfile {
4698            regime: "UL 3300 service, communication, and mobile robots",
4699            version: "2022 (see ANSI/CAN/UL 3300:2024)",
4700            requirements: UL_3300_REQUIREMENTS,
4701        }),
4702        _ => None,
4703    }
4704}
4705
4706/// A built-in conformance profile as JSON (`{regime, version, requirements:
4707/// [{id, clause, title, credential, fields, expect, citation,
4708/// citationNote?}]}`), or `null` for an unknown id.
4709pub fn conformance_profile_json(profile_id: &str) -> Value {
4710    let Some(p) = conformance_profile(profile_id) else {
4711        return Value::Null;
4712    };
4713    let requirements: Vec<Value> = p
4714        .requirements
4715        .iter()
4716        .map(|r| {
4717            let expect: Map<String, Value> = r
4718                .expect_true
4719                .iter()
4720                .map(|f| (f.to_string(), Value::Bool(true)))
4721                .collect();
4722            let mut m = Map::new();
4723            m.insert("id".into(), json!(r.id));
4724            m.insert("clause".into(), json!(r.clause));
4725            m.insert("title".into(), json!(r.title));
4726            m.insert("credential".into(), json!(r.credential));
4727            m.insert("fields".into(), json!(r.fields));
4728            m.insert("expect".into(), Value::Object(expect));
4729            m.insert("citation".into(), json!(r.citation));
4730            if let Some(n) = r.citation_note {
4731                m.insert("citationNote".into(), json!(n));
4732            }
4733            Value::Object(m)
4734        })
4735        .collect();
4736    json!({"regime": p.regime, "version": p.version, "requirements": requirements})
4737}
4738
4739/// The type array of a credential, accepting a JSON string or an array of strings.
4740fn credential_types(credential: &Value) -> Vec<&str> {
4741    match credential.get("type") {
4742        Some(Value::String(s)) => vec![s.as_str()],
4743        Some(Value::Array(items)) => items.iter().filter_map(|v| v.as_str()).collect(),
4744        _ => Vec::new(),
4745    }
4746}
4747
4748/// Follow a dot-separated path from the credentialSubject, returning the value at
4749/// the leaf or `None` if any segment is missing or not an object.
4750fn path_value<'a>(subject: &'a Value, path: &str) -> Option<&'a Value> {
4751    let mut node = subject;
4752    for part in path.split('.') {
4753        match node {
4754            Value::Object(map) => match map.get(part) {
4755                Some(v) => node = v,
4756                None => return None,
4757            },
4758            _ => return None,
4759        }
4760    }
4761    Some(node)
4762}
4763
4764/// True when a value is present and non-empty: not null, and not an empty array
4765/// or empty object. Any other value (including `false`, `0`, or `""`) counts.
4766fn value_present(value: &Value) -> bool {
4767    match value {
4768        Value::Null => false,
4769        Value::Array(a) => !a.is_empty(),
4770        Value::Object(o) => !o.is_empty(),
4771        _ => true,
4772    }
4773}
4774
4775/// True when `credential` satisfies `requirement`: its type array includes the
4776/// requirement's credential type, its credentialSubject has a non-null,
4777/// non-empty value at every field path, and every `expect_true` path holds
4778/// boolean `true`. Presence alone is not evidence: a heartbeat that reports an
4779/// envelope breach does not evidence having stayed inside the envelope.
4780fn credential_satisfies(credential: &Value, requirement: &ProfileRequirement) -> bool {
4781    if !credential_types(credential).contains(&requirement.credential) {
4782        return false;
4783    }
4784    let empty = Value::Object(Map::new());
4785    let subject = credential.get("credentialSubject").unwrap_or(&empty);
4786    for path in requirement.fields {
4787        match path_value(subject, path) {
4788            Some(v) if value_present(v) => {}
4789            _ => return false,
4790        }
4791    }
4792    for path in requirement.expect_true {
4793        if path_value(subject, path) != Some(&Value::Bool(true)) {
4794            return false;
4795        }
4796    }
4797    true
4798}
4799
4800/// Check the presented `credentials` against the named profile and return a
4801/// deterministic report. Each requirement is satisfied when some presented
4802/// credential matches its type and has every required field. The caller is
4803/// expected to have verified the credentials' signatures first; this checks
4804/// structure and coverage, not proofs.
4805///
4806/// Every requirement carries the provenance of its clause citation, and the
4807/// report totals them, so a result never reads as more authoritative about the
4808/// regulation than its sources are.
4809///
4810/// The report has exactly `{profileId, regime, version, conforms,
4811/// satisfiedCount, totalCount, citations:{...},
4812/// requirements:[{id, clause, title, satisfied, citation, citationNote?}]}`.
4813pub fn check_conformance(credentials: &[Value], profile_id: &str) -> Result<Value> {
4814    check_conformance_for(credentials, profile_id, None)
4815}
4816
4817/// [`check_conformance`] bound to one robot: with `robot_did`, only credentials
4818/// whose `credentialSubject.id` is that robot count (so another robot's
4819/// credential mixed into the set cannot fill a gap), and the report carries
4820/// `robotDid`.
4821pub fn check_conformance_for(
4822    credentials: &[Value],
4823    profile_id: &str,
4824    robot_did: Option<&str>,
4825) -> Result<Value> {
4826    let prof = conformance_profile(profile_id)
4827        .ok_or_else(|| CoreError::Json(format!("unknown conformance profile: {profile_id}")))?;
4828    if robot_did.is_some_and(str::is_empty) {
4829        return Err(CoreError::Json("robot_did must be a non-empty DID".into()));
4830    }
4831    let presented: Vec<&Value> = credentials
4832        .iter()
4833        .filter(|c| c.is_object())
4834        .filter(|c| {
4835            robot_did.is_none_or(|r| {
4836                c.get("credentialSubject")
4837                    .and_then(|s| s.get("id"))
4838                    .and_then(|x| x.as_str())
4839                    == Some(r)
4840            })
4841        })
4842        .collect();
4843
4844    let mut results: Vec<Value> = Vec::with_capacity(prof.requirements.len());
4845    let mut satisfied = 0i64;
4846    let mut citations = Map::new();
4847    for status in CITATION_STATUSES {
4848        citations.insert((*status).into(), json!(0i64));
4849    }
4850    for requirement in prof.requirements {
4851        let ok = presented
4852            .iter()
4853            .any(|c| credential_satisfies(c, requirement));
4854        if ok {
4855            satisfied += 1;
4856        }
4857        let seen = citations
4858            .get(requirement.citation)
4859            .and_then(|v| v.as_i64())
4860            .unwrap_or(0);
4861        citations.insert(requirement.citation.into(), json!(seen + 1));
4862        let mut result = Map::new();
4863        result.insert("id".into(), json!(requirement.id));
4864        result.insert("clause".into(), json!(requirement.clause));
4865        result.insert("title".into(), json!(requirement.title));
4866        result.insert("satisfied".into(), json!(ok));
4867        result.insert("citation".into(), json!(requirement.citation));
4868        if let Some(note) = requirement.citation_note {
4869            result.insert("citationNote".into(), json!(note));
4870        }
4871        results.push(Value::Object(result));
4872    }
4873    let total = prof.requirements.len() as i64;
4874
4875    let mut report = Map::new();
4876    report.insert("profileId".into(), json!(profile_id));
4877    report.insert("regime".into(), json!(prof.regime));
4878    report.insert("version".into(), json!(prof.version));
4879    report.insert("conforms".into(), json!(satisfied == total));
4880    report.insert("satisfiedCount".into(), json!(satisfied));
4881    report.insert("totalCount".into(), json!(total));
4882    report.insert("citations".into(), Value::Object(citations));
4883    report.insert("requirements".into(), Value::Array(results));
4884    if let Some(r) = robot_did {
4885        report.insert("robotDid".into(), json!(r));
4886    }
4887    Ok(Value::Object(report))
4888}
4889
4890/// Multibase SHA-256 of the JCS-canonical report, for binding into an
4891/// attestation. Every language canonicalizes identically, so the digest is the
4892/// same byte string everywhere.
4893pub fn report_digest(report: &Value) -> String {
4894    mb64(&Sha256::digest(jcs::canonicalize(report)))
4895}
4896
4897/// Parameters for [`build_conformance_attestation`]. The signer is the robot, its
4898/// owner, or an assessing authority; `robot_did` names the robot the attestation
4899/// is about. `report` is produced by [`check_conformance`] and is embedded and
4900/// bound by digest. When `valid_seconds` is set it bounds the attestation.
4901#[derive(Debug, Clone)]
4902pub struct BuildConformanceAttestation {
4903    pub issuer_did: String,
4904    pub robot_did: String,
4905    pub report: Value,
4906    pub valid_from: String,
4907    pub valid_until: Option<String>,
4908}
4909
4910/// Build a signed point-in-time `RobotConformanceAttestation` for `robot_did`
4911/// over a `report` produced by [`check_conformance`]. The report is embedded and
4912/// bound by digest.
4913pub fn build_conformance_attestation(
4914    signer_seed: &[u8],
4915    params: &BuildConformanceAttestation,
4916) -> Result<Value> {
4917    if params.robot_did.is_empty() {
4918        return Err(CoreError::Json("robot_did is required".into()));
4919    }
4920    let report = params
4921        .report
4922        .as_object()
4923        .ok_or_else(|| CoreError::Json("report must come from check_conformance".into()))?;
4924    if !report.contains_key("profileId") || !report.contains_key("conforms") {
4925        return Err(CoreError::Json(
4926            "report must come from check_conformance".into(),
4927        ));
4928    }
4929
4930    let mut subject = Map::new();
4931    subject.insert("id".into(), json!(params.robot_did));
4932    subject.insert(
4933        "profileId".into(),
4934        report.get("profileId").cloned().unwrap_or(Value::Null),
4935    );
4936    subject.insert(
4937        "regime".into(),
4938        report.get("regime").cloned().unwrap_or(Value::Null),
4939    );
4940    subject.insert(
4941        "conforms".into(),
4942        report.get("conforms").cloned().unwrap_or(Value::Null),
4943    );
4944    subject.insert(
4945        "satisfiedCount".into(),
4946        report.get("satisfiedCount").cloned().unwrap_or(Value::Null),
4947    );
4948    subject.insert(
4949        "totalCount".into(),
4950        report.get("totalCount").cloned().unwrap_or(Value::Null),
4951    );
4952    subject.insert(
4953        "citations".into(),
4954        report
4955            .get("citations")
4956            .cloned()
4957            .unwrap_or_else(|| Value::Object(Map::new())),
4958    );
4959    subject.insert("reportDigest".into(), json!(report_digest(&params.report)));
4960    subject.insert("report".into(), params.report.clone());
4961
4962    let mut cred = Map::new();
4963    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4964    cred.insert(
4965        "type".into(),
4966        json!(["VerifiableCredential", CONFORMANCE_ATTESTATION_TYPE]),
4967    );
4968    cred.insert("issuer".into(), json!(params.issuer_did));
4969    cred.insert("validFrom".into(), json!(params.valid_from));
4970    if let Some(vu) = &params.valid_until {
4971        cred.insert("validUntil".into(), json!(vu));
4972    }
4973    cred.insert("credentialSubject".into(), Value::Object(subject));
4974
4975    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
4976    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
4977}
4978
4979/// Verify a conformance attestation: the issuer's proof bound to the issuer,
4980/// the window at `now_iso` (validFrom required), that the embedded report
4981/// matches its bound digest, that every summary field (profileId, regime,
4982/// conforms, satisfiedCount, totalCount) matches the report, and that
4983/// `conforms` is a boolean. When given, the attestation must be about
4984/// `robot_did` and its issuer must be in `trusted_issuers`. Returns the
4985/// credentialSubject on success, `None` if invalid.
4986pub fn verify_conformance_attestation(
4987    credential: &Value,
4988    keys: Keys<'_>,
4989    robot_did: Option<&str>,
4990    trusted_issuers: Option<&HashSet<String>>,
4991    now_iso: &str,
4992) -> Result<Option<Value>> {
4993    let now = rv::require_now(now_iso)?;
4994    let opts = VerifyOptions {
4995        trusted_issuers,
4996        ..VerifyOptions::window(Window::FromRequired)
4997    };
4998    let v = match rv::verify_robotics_credential(
4999        credential,
5000        keys,
5001        Some(CONFORMANCE_ATTESTATION_TYPE),
5002        now,
5003        opts,
5004    ) {
5005        Ok(v) => v,
5006        Err(_) => return Ok(None),
5007    };
5008    let subject = v.subject;
5009    let embedded = match subject.get("report") {
5010        Some(r) if r.is_object() => r,
5011        _ => return Ok(None),
5012    };
5013    if subject.get("reportDigest").and_then(|v| v.as_str())
5014        != Some(report_digest(embedded).as_str())
5015    {
5016        return Ok(None);
5017    }
5018    for name in [
5019        "profileId",
5020        "regime",
5021        "conforms",
5022        "satisfiedCount",
5023        "totalCount",
5024    ] {
5025        if subject.get(name) != embedded.get(name) {
5026            return Ok(None);
5027        }
5028    }
5029    if !subject.get("conforms").is_some_and(|c| c.is_boolean()) {
5030        return Ok(None);
5031    }
5032    // A report bound to one robot cannot be attested as being about another.
5033    if embedded.get("robotDid").is_some() && embedded.get("robotDid") != subject.get("id") {
5034        return Ok(None);
5035    }
5036    if robot_did.is_some_and(|r| subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
5037        return Ok(None);
5038    }
5039    Ok(Some(subject))
5040}
5041
5042// ---------------------------------------------------------------------------
5043// Post-quantum robot credentials (Phase 5.13)
5044// ---------------------------------------------------------------------------
5045//
5046// A robot fielded today lives for ten to twenty years, longer than classical
5047// Ed25519 is expected to stay safe, so a robot identity signed now could be
5048// forged once a quantum computer arrives. This section makes the hybrid
5049// post-quantum cryptosuite (`hybrid-eddsa-mldsa44-jcs-2026`, a classical
5050// Ed25519 signature alongside an ML-DSA-44 signature) available for robot
5051// credentials so they stay unforgeable across the robot's whole service life.
5052//
5053//   - sign_pq: attach a hybrid proof to a robot credential.
5054//   - verify_robot_credential: verify a robot credential whether it carries a
5055//     classical or a hybrid proof, auto-detected from the proof, so a fleet can
5056//     move to PQ gradually without breaking the classical credentials already in
5057//     the field.
5058//   - migrate_to_pq: re-sign a fielded robot's classical credential under PQ.
5059//
5060// This is the open layer: hybrid signing, backward-compatible verification, and
5061// a software re-signing migration path. It reuses the proof set of
5062// [`crate::hybrid`] and the ML-DSA-44 and multikey helpers rather than
5063// re-deriving any cryptography.
5064
5065/// The classical (Ed25519-only) robot credential cryptosuite.
5066pub const CLASSICAL_CRYPTOSUITE: &str = data_integrity::CRYPTOSUITE_ID;
5067/// The ML-DSA-44 proof a post-quantum robot credential carries next to its
5068/// classical proof, in a proof set.
5069pub const POST_QUANTUM_CRYPTOSUITE: &str = hybrid::MLDSA44_CRYPTOSUITE_ID;
5070
5071/// Coerce an ML-DSA-44 public key supplied either as raw 1312-byte bytes or as a
5072/// Multikey string into raw bytes. Errors on the wrong length or a non-ML-DSA
5073/// multikey.
5074pub fn coerce_mldsa44_public(mldsa44_public: &[u8]) -> Result<Vec<u8>> {
5075    if mldsa44_public.len() != MLDSA44_PUBLIC_LEN {
5076        return Err(CoreError::InvalidKeyLength {
5077            expected: MLDSA44_PUBLIC_LEN,
5078            got: mldsa44_public.len(),
5079        });
5080    }
5081    Ok(mldsa44_public.to_vec())
5082}
5083
5084/// Coerce an ML-DSA-44 Multikey string into raw public-key bytes. Errors if the
5085/// multikey does not carry an ML-DSA-44 key.
5086pub fn mldsa44_public_from_multikey(multikey_str: &str) -> Result<Vec<u8>> {
5087    let decoded = multikey::decode(multikey_str)?;
5088    if decoded.algorithm != "ML-DSA-44" {
5089        return Err(CoreError::InvalidMultikey(format!(
5090            "expected an ML-DSA-44 multikey, got {}",
5091            decoded.algorithm
5092        )));
5093    }
5094    coerce_mldsa44_public(&decoded.raw_key)
5095}
5096
5097fn pq_verification_method(credential: &Value) -> String {
5098    let issuer = credential
5099        .as_object()
5100        .and_then(|o| o.get("issuer"))
5101        .and_then(|v| v.as_str())
5102        .unwrap_or("");
5103    format!("{issuer}#key-1")
5104}
5105
5106/// The ML-DSA-44 verification method slot, matching the `#key-2` convention the
5107/// language SDKs derive for the post-quantum member of a proof set.
5108fn pq_mldsa_verification_method(credential: &Value) -> String {
5109    let issuer = credential
5110        .as_object()
5111        .and_then(|o| o.get("issuer"))
5112        .and_then(|v| v.as_str())
5113        .unwrap_or("");
5114    format!("{issuer}#key-2")
5115}
5116
5117/// Attach a hybrid (classical Ed25519 plus post-quantum ML-DSA-44) Data Integrity
5118/// proof to a pre-built robot `credential`. Any existing proof is replaced. The
5119/// robot signs with its Ed25519 seed and its ML-DSA-44 key pair; `created` is the
5120/// caller-supplied ISO-8601 instant, keeping the core deterministic.
5121pub fn sign_pq(
5122    credential: &Value,
5123    ed25519_seed: &[u8],
5124    mldsa: &MlDsa44KeyPair,
5125    created: &str,
5126) -> Result<Value> {
5127    let ed_vm = pq_verification_method(credential);
5128    let ml_vm = pq_mldsa_verification_method(credential);
5129    hybrid::sign_dual(credential, ed25519_seed, mldsa, &ed_vm, &ml_vm, created)
5130}
5131
5132/// Return true if `credential` carries a post-quantum proof: a `proof` array
5133/// holding an ML-DSA-44 proof. One proof object is never post-quantum (the
5134/// earlier composite proof is refused by every verifier).
5135pub fn is_pq(credential: &Value) -> bool {
5136    match credential.as_object().and_then(|o| o.get("proof")) {
5137        Some(Value::Array(proofs)) => proofs
5138            .iter()
5139            .any(|p| hybrid::Suite::of_proof(p) == Some(hybrid::Suite::Mldsa44)),
5140        _ => false,
5141    }
5142}
5143
5144/// Verify a post-quantum robot credential: a proof set whose Ed25519 and
5145/// ML-DSA-44 signatures both validate. One proof object is refused, the
5146/// earlier composite proof included.
5147fn verify_pq_proof_set(
5148    credential: &Value,
5149    ed25519_public_key: &[u8],
5150    mldsa44_public_key: &[u8],
5151) -> Result<bool> {
5152    match credential.as_object().and_then(|o| o.get("proof")) {
5153        Some(Value::Array(_)) => {
5154            hybrid::verify_dual(credential, ed25519_public_key, mldsa44_public_key)
5155        }
5156        _ => Ok(false),
5157    }
5158}
5159
5160/// Verify a hybrid robot credential. Both the Ed25519 and the ML-DSA-44 signature
5161/// MUST validate. `mldsa44_public_key` is raw 1312-byte bytes or an ML-DSA-44
5162/// Multikey string (pass `mldsa44_multikey` for the string form).
5163pub fn verify_pq(
5164    credential: &Value,
5165    ed25519_public_key: &[u8],
5166    mldsa44_public_key: &[u8],
5167) -> Result<bool> {
5168    let resolved_ml = coerce_mldsa44_public(mldsa44_public_key)?;
5169    verify_pq_proof_set(credential, ed25519_public_key, &resolved_ml)
5170}
5171
5172/// [`verify_robot_credential`] with the ML-DSA-44 key taken from a key source
5173/// like the Ed25519 key: a bare key, or a `{did: key}` map / resolver from which
5174/// the entry for the credential's issuer is used (no entry fails a
5175/// post-quantum credential). Map values are raw 1312-byte keys or ML-DSA-44
5176/// Multikey strings as UTF-8 bytes.
5177pub fn verify_robot_credential_keyed(
5178    credential: &Value,
5179    ed_keys: Keys<'_>,
5180    mldsa44_keys: Option<Keys<'_>>,
5181    expected_type: Option<&str>,
5182    now_iso: &str,
5183) -> Result<bool> {
5184    let ml = match mldsa44_keys {
5185        None => return verify_robot_credential(credential, ed_keys, None, expected_type, now_iso),
5186        Some(k) => k,
5187    };
5188    let issuer = rv::issuer_id(credential.get("issuer"))
5189        .unwrap_or("")
5190        .to_string();
5191    let picked: Option<Vec<u8>> = match ml {
5192        Keys::Embedded | Keys::Pinned(_) => None,
5193        Keys::Bare(k) => Some(k.to_vec()),
5194        Keys::One(d, k) => (d == issuer).then(|| k.to_vec()),
5195        Keys::Map(m) => m.get(&issuer).cloned(),
5196        Keys::Resolver(f) => f(&issuer),
5197    };
5198    match picked {
5199        Some(k) => verify_robot_credential(credential, ed_keys, Some(&k), expected_type, now_iso),
5200        // A post-quantum credential needs its issuer's ML-DSA key; a classical
5201        // one given an ML-DSA source is refused by the same rule as a bare key.
5202        None => Ok(false),
5203    }
5204}
5205
5206/// The backward-compatible robot credential verify a fleet uses while
5207/// migrating to post-quantum: auto-detects a hybrid proof set.
5208///
5209/// Every proof must be bound to the issuer (`proofPurpose` assertionMethod and
5210/// a verification method of the issuer DID), and the Ed25519 key must belong to
5211/// the issuer (the key inside a did:key, or `ed_keys` as a `{did: key}`
5212/// source for any other DID). Present validity bounds must be strict protocol
5213/// times with `now_iso` inside. When `expected_type` is given the credential
5214/// must carry it. A post-quantum credential requires `mldsa44_public_key`;
5215/// supplying one for a classical credential refuses it (so a stripped ML-DSA
5216/// proof cannot pass as classical). Malformed input returns `false`.
5217pub fn verify_robot_credential(
5218    credential: &Value,
5219    ed_keys: Keys<'_>,
5220    mldsa44_public_key: Option<&[u8]>,
5221    expected_type: Option<&str>,
5222    now_iso: &str,
5223) -> Result<bool> {
5224    let now = rv::require_now(now_iso)?;
5225    if !credential.is_object() {
5226        return Ok(false);
5227    }
5228    if is_pq(credential) {
5229        let ml = match mldsa44_public_key {
5230            Some(k) => k,
5231            None => return Ok(false),
5232        };
5233        let issuer = match rv::issuer_id(credential.get("issuer")) {
5234            Some(i) => i,
5235            None => return Ok(false),
5236        };
5237        if rv::input_too_large(credential, rv::MAX_CREDENTIAL_BYTES).is_some() {
5238            return Ok(false);
5239        }
5240        let types: Vec<&str> = match credential.get("type") {
5241            Some(Value::String(t)) => vec![t.as_str()],
5242            Some(Value::Array(a)) if a.iter().all(|t| t.is_string()) => {
5243                a.iter().filter_map(|t| t.as_str()).collect()
5244            }
5245            _ => return Ok(false),
5246        };
5247        if expected_type.is_some_and(|e| !types.contains(&e)) {
5248            return Ok(false);
5249        }
5250        let members: Vec<&Value> = match credential.get("proof") {
5251            Some(Value::Array(a)) => a.iter().collect(),
5252            Some(p) => vec![p],
5253            None => return Ok(false),
5254        };
5255        if members.is_empty()
5256            || members
5257                .iter()
5258                .any(|m| rv::proof_unbound_reason(m, issuer).is_some())
5259        {
5260            return Ok(false);
5261        }
5262        if rv::window_reason(credential, Window::IfPresent, now, 0).is_some() {
5263            return Ok(false);
5264        }
5265        let ed = match rv::resolve_issuer_key(issuer, ed_keys) {
5266            Ok(k) => k,
5267            Err(_) => return Ok(false),
5268        };
5269        let resolved_ml = match resolve_mldsa44_public(ml) {
5270            Ok(m) => m,
5271            Err(_) => return Ok(false),
5272        };
5273        return Ok(verify_pq_proof_set(credential, &ed, &resolved_ml).unwrap_or(false));
5274    }
5275    if mldsa44_public_key.is_some() {
5276        return Ok(false);
5277    }
5278    Ok(rv::verify_robotics_credential(
5279        credential,
5280        ed_keys,
5281        expected_type,
5282        now,
5283        VerifyOptions::window(Window::IfPresent),
5284    )
5285    .is_ok())
5286}
5287
5288/// Resolve an ML-DSA-44 public key given either raw bytes or a Multikey string.
5289/// A 1312-byte input is the raw key; otherwise it is parsed as a UTF-8 Multikey.
5290pub fn resolve_mldsa44_public(mldsa44_public_key: &[u8]) -> Result<Vec<u8>> {
5291    if mldsa44_public_key.len() == MLDSA44_PUBLIC_LEN {
5292        return Ok(mldsa44_public_key.to_vec());
5293    }
5294    let s = std::str::from_utf8(mldsa44_public_key).map_err(|_| {
5295        CoreError::InvalidMultikey("ML-DSA-44 key must be raw bytes or a Multikey string".into())
5296    })?;
5297    mldsa44_public_from_multikey(s)
5298}
5299
5300/// Re-sign a fielded robot's classical `credential` under the hybrid PQ
5301/// cryptosuite, preserving its body. The robot holds its current Ed25519 seed and
5302/// an ML-DSA-44 key pair; `created` is the caller-supplied re-signing instant.
5303pub fn migrate_to_pq(
5304    credential: &Value,
5305    ed25519_seed: &[u8],
5306    mldsa: &MlDsa44KeyPair,
5307    created: &str,
5308) -> Result<Value> {
5309    sign_pq(credential, ed25519_seed, mldsa, created)
5310}
5311
5312// ---------------------------------------------------------------------------
5313// Cross-embodiment identity continuity (Phase 5.15)
5314// ---------------------------------------------------------------------------
5315//
5316// An AI agent (a policy with its own Vouch identity) can run on one robot body
5317// today and a different body tomorrow. An embodiment credential binds the agent
5318// identity to a specific body (a hardware-rooted robot identity) and that body's
5319// hardware root for a period, signed by the agent's own persistent key. Linking
5320// each embodiment to the previous forms a continuity chain a verifier walks to
5321// confirm the same accountable agent persisted across bodies, re-binding to each
5322// body's hardware root as it moved. A fork check confirms the agent was never
5323// actively embodied in two bodies at once.
5324//
5325// This is the inverse of the ownership custody chain: there one body passes
5326// between owners; here one mind passes between bodies, and the constant that
5327// signs every link is the agent identity itself.
5328//
5329// This is the open layer: plain signed embodiment credentials, continuity-chain
5330// verification, and software fork detection. It reuses the core proof path
5331// ([`data_integrity`]) rather than re-deriving any cryptography.
5332
5333pub const EMBODIMENT_TYPE: &str = "AgentEmbodimentCredential";
5334
5335/// Parameters for [`build_embodiment`]. The signer is the agent's own persistent
5336/// key; `agent_did` is both issuer and subject id, so the whole continuity chain
5337/// is signed by one accountable identity. `from_body`, when set, links this
5338/// embodiment to the body the agent left, forming the chain. `valid_until`, when
5339/// set, bounds the active window (used by [`check_no_fork`]).
5340#[derive(Debug, Clone)]
5341pub struct BuildEmbodiment {
5342    pub agent_did: String,
5343    pub body_did: String,
5344    pub body_hardware_root: String,
5345    pub from_body: Option<String>,
5346    pub embodied_at: String,
5347    pub valid_until: Option<String>,
5348}
5349
5350/// Build a signed embodiment credential: the agent `agent_did` authorizes running
5351/// on `body_did`, re-binding to that body's hardware root `body_hardware_root`.
5352/// Signed by the agent's own persistent key. `from_body` links this embodiment to
5353/// the body the agent left.
5354pub fn build_embodiment(agent_seed: &[u8], params: &BuildEmbodiment) -> Result<Value> {
5355    if params.agent_did.is_empty()
5356        || params.body_did.is_empty()
5357        || params.body_hardware_root.is_empty()
5358    {
5359        return Err(CoreError::Json(
5360            "agent_did, body_did, and body_hardware_root are required".into(),
5361        ));
5362    }
5363
5364    let mut subject = Map::new();
5365    subject.insert("id".into(), json!(params.agent_did));
5366    subject.insert("body".into(), json!(params.body_did));
5367    subject.insert("bodyHardwareRoot".into(), json!(params.body_hardware_root));
5368    if let Some(from_body) = &params.from_body {
5369        subject.insert("fromBody".into(), json!(from_body));
5370    }
5371
5372    let mut cred = Map::new();
5373    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5374    cred.insert(
5375        "type".into(),
5376        json!(["VerifiableCredential", EMBODIMENT_TYPE]),
5377    );
5378    cred.insert("issuer".into(), json!(params.agent_did));
5379    cred.insert("validFrom".into(), json!(params.embodied_at));
5380    if let Some(vu) = &params.valid_until {
5381        cred.insert("validUntil".into(), json!(vu));
5382    }
5383    cred.insert("credentialSubject".into(), Value::Object(subject));
5384
5385    let opts = BuildProofOptions::new(format!("{}#key-1", params.agent_did), &params.embodied_at);
5386    data_integrity::sign(&Value::Object(cred), agent_seed, &opts)
5387}
5388
5389/// Verify an embodiment credential: the agent's proof bound to the agent as
5390/// issuer (a mind authorizes its own embodiment, so the issuer must be
5391/// `credentialSubject.id`), the window at `now_iso` (validFrom required), and
5392/// that the subject carries a `body` and a `bodyHardwareRoot`. When
5393/// `body_hardware_roots` (body DID -> trusted hardware-root key) is given, the
5394/// credential's `bodyHardwareRoot` must match the entry for its body. Returns
5395/// the credentialSubject on success, `None` if invalid.
5396pub fn verify_embodiment(
5397    credential: &Value,
5398    agent_keys: Keys<'_>,
5399    body_hardware_roots: Option<&std::collections::BTreeMap<String, String>>,
5400    now_iso: &str,
5401) -> Result<Option<Value>> {
5402    let v = match bound(
5403        credential,
5404        agent_keys,
5405        EMBODIMENT_TYPE,
5406        now_iso,
5407        Window::FromRequired,
5408    )? {
5409        Some(v) if issuer_is_subject(&v) => v,
5410        _ => return Ok(None),
5411    };
5412    let body = non_empty_str(&v.subject, "body");
5413    let root = non_empty_str(&v.subject, "bodyHardwareRoot");
5414    let (body, root) = match (body, root) {
5415        (Some(b), Some(r)) => (b, r),
5416        _ => return Ok(None),
5417    };
5418    if let Some(roots) = body_hardware_roots {
5419        if roots.get(body).map(String::as_str) != Some(root) {
5420            return Ok(None);
5421        }
5422    }
5423    Ok(Some(v.subject))
5424}
5425
5426/// Verify an ordered list of embodiment credentials forms a valid continuity
5427/// chain: every link verifies under the same agent (the persistent mind), each
5428/// link's `fromBody` matches the previous link's `body`, and (when given) the
5429/// first `fromBody` is `origin_body`. Links start in order; each earlier link
5430/// must still have been valid when the next one started, and the last link
5431/// must be valid at `now_iso`. The verified links are then checked for forks.
5432/// Returns `(ok, current_body)`.
5433pub fn verify_continuity_chain(
5434    embodiments: &[Value],
5435    agent_keys: Keys<'_>,
5436    origin_body: Option<&str>,
5437    body_hardware_roots: Option<&std::collections::BTreeMap<String, String>>,
5438    now_iso: &str,
5439) -> Result<(bool, Option<String>)> {
5440    rv::require_now(now_iso)?;
5441    let mut expected_from: Option<String> = origin_body.map(String::from);
5442    let mut current_body: Option<String> = origin_body.map(String::from);
5443    let mut agent: Option<String> = None;
5444    let mut prev_start: Option<i128> = None;
5445    for (i, embodiment) in embodiments.iter().enumerate() {
5446        let at: String = match embodiments.get(i + 1) {
5447            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
5448                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
5449                _ => return Ok((false, None)),
5450            },
5451            None => now_iso.to_string(),
5452        };
5453        let subject = match verify_embodiment(embodiment, agent_keys, body_hardware_roots, &at)? {
5454            Some(s) => s,
5455            None => return Ok((false, None)),
5456        };
5457        let id = subject.get("id").and_then(|v| v.as_str()).map(String::from);
5458        match &agent {
5459            None => agent = id,
5460            Some(a) if id.as_deref() == Some(a.as_str()) => {}
5461            _ => return Ok((false, None)),
5462        }
5463        match rv::time_ns(embodiment.get("validFrom")) {
5464            Some(t) if prev_start.is_none_or(|p| t >= p) => prev_start = Some(t),
5465            _ => return Ok((false, None)),
5466        }
5467        if let Some(expected) = &expected_from {
5468            if subject.get("fromBody").and_then(|v| v.as_str()) != Some(expected.as_str()) {
5469                return Ok((false, None));
5470            }
5471        }
5472        current_body = subject
5473            .get("body")
5474            .and_then(|v| v.as_str())
5475            .map(String::from);
5476        expected_from = current_body.clone();
5477    }
5478    if !check_no_fork(embodiments)?.0 {
5479        return Ok((false, None));
5480    }
5481    Ok((true, current_body))
5482}
5483
5484/// Two conflicting bodies surfaced by [`check_no_fork`].
5485#[derive(Debug, Clone, PartialEq, Eq)]
5486pub struct ForkConflict {
5487    pub body_a: String,
5488    pub body_b: String,
5489}
5490
5491/// Half-open intervals [start, end); a missing end is open-ended (+infinity). A
5492/// clean handover sets one window's end to the next window's start, which does not
5493/// overlap.
5494fn windows_overlap(start_a: i128, end_a: Option<i128>, start_b: i128, end_b: Option<i128>) -> bool {
5495    let a_before_b = end_a.map(|e| e <= start_b).unwrap_or(false);
5496    let b_before_a = end_b.map(|e| e <= start_a).unwrap_or(false);
5497    !(a_before_b || b_before_a)
5498}
5499
5500/// Confirm no two embodiments place the agent in different bodies with overlapping
5501/// active windows. Each embodiment is active from `validFrom` to `validUntil` (a
5502/// missing `validUntil` is treated as open-ended). Two embodiments on different
5503/// bodies whose windows overlap are a fork. Returns `(ok, conflict)` where
5504/// conflict, when present, names the two conflicting bodies.
5505pub fn check_no_fork(embodiments: &[Value]) -> Result<(bool, Option<ForkConflict>)> {
5506    let mut windows: Vec<(String, i128, Option<i128>)> = Vec::with_capacity(embodiments.len());
5507    for embodiment in embodiments {
5508        let subject = embodiment
5509            .get("credentialSubject")
5510            .and_then(|s| s.as_object());
5511        let body = subject
5512            .and_then(|s| s.get("body"))
5513            .and_then(|v| v.as_str())
5514            .filter(|s| !s.is_empty());
5515        let start = rv::time_ns(embodiment.get("validFrom"));
5516        let (body, start) = match (body, start) {
5517            (Some(b), Some(s)) => (b.to_string(), s),
5518            _ => return Ok((false, None)),
5519        };
5520        // A present end must be a strict time; only an absent end is open-ended.
5521        let end = match embodiment.get("validUntil") {
5522            None => None,
5523            Some(v) => match rv::time_ns(Some(v)) {
5524                Some(t) => Some(t),
5525                None => return Ok((false, None)),
5526            },
5527        };
5528        windows.push((body, start, end));
5529    }
5530
5531    let Some(first) = first_forked_index(&windows) else {
5532        return Ok((true, None));
5533    };
5534    let (body_i, start_i, end_i) = &windows[first];
5535    for (body_j, start_j, end_j) in &windows[first + 1..] {
5536        if body_i != body_j && windows_overlap(*start_i, *end_i, *start_j, *end_j) {
5537            return Ok((
5538                false,
5539                Some(ForkConflict {
5540                    body_a: body_i.clone(),
5541                    body_b: body_j.clone(),
5542                }),
5543            ));
5544        }
5545    }
5546    unreachable!("the forked window has a partner")
5547}
5548
5549/// The most windows on one body a segmented fork check keeps at once (the
5550/// windows whose ends still matter). A real history holds a handful; a
5551/// history that needs more is refused and must be checked whole.
5552pub const MAX_FORK_WINDOWS: usize = 4096;
5553
5554/// Why a segmented fork check failed for a reason other than a fork.
5555#[derive(Debug, Clone, PartialEq, Eq)]
5556pub enum ForkFailure {
5557    /// An embodiment has no body, no valid `validFrom`, or a `validUntil`
5558    /// that is not a protocol time. The whole check answers `(false, None)`.
5559    Malformed(u64),
5560    /// An embodiment starts before the one before it. The segmented check
5561    /// reads a history in `validFrom` order.
5562    OutOfOrder(u64),
5563    /// More than [`MAX_FORK_WINDOWS`] windows on one body overlap at once.
5564    TooManyWindows(u64),
5565}
5566
5567/// Where a fork check stands after the first embodiments of a history, so a
5568/// long history is checked one segment at a time with bounded memory. The
5569/// history must be in `validFrom` order (the order a history is recorded
5570/// in); for such a history the verdict after the last segment is the one
5571/// [`check_no_fork`] gives for the whole list, conflict included.
5572///
5573/// The bookkeeping: while no fork has been seen, every window still open at
5574/// the latest start is on one body (two such windows on different bodies
5575/// would overlap). `windows` keeps, for that body, the points where the
5576/// latest end so far grows: `(start, latest end up to that start)`, with
5577/// `None` for an open end. A later window on another body forks exactly
5578/// when some kept window that starts before its end also ends after its
5579/// start.
5580#[derive(Debug, Clone, PartialEq, Eq)]
5581pub struct ForkProgress {
5582    /// Embodiments checked so far.
5583    pub count: u64,
5584    /// The latest `validFrom` seen, in nanoseconds.
5585    pub last_start: Option<i128>,
5586    /// The body every open window is on.
5587    pub body: Option<String>,
5588    /// `(start, latest end)` steps for `body`, oldest first.
5589    pub windows: Vec<(i128, Option<i128>)>,
5590    /// The first fork, as [`check_no_fork`] reports it.
5591    pub conflict: Option<ForkConflict>,
5592    /// A failure that is not a fork.
5593    pub failure: Option<ForkFailure>,
5594}
5595
5596impl Default for ForkProgress {
5597    fn default() -> Self {
5598        Self::start()
5599    }
5600}
5601
5602/// `a` ends after instant `t` (an open end is after everything).
5603fn ends_after(end: Option<i128>, t: i128) -> bool {
5604    end.is_none_or(|e| e > t)
5605}
5606
5607impl ForkProgress {
5608    pub fn start() -> Self {
5609        Self {
5610            count: 0,
5611            last_start: None,
5612            body: None,
5613            windows: Vec::new(),
5614            conflict: None,
5615            failure: None,
5616        }
5617    }
5618
5619    /// The verdict over every embodiment checked so far: `(ok, conflict)`
5620    /// as [`check_no_fork`] gives it, plus a reason when not ok.
5621    pub fn result(&self) -> (bool, Option<ForkConflict>, Option<String>) {
5622        match &self.failure {
5623            Some(ForkFailure::Malformed(i)) => (
5624                false,
5625                None,
5626                Some(format!(
5627                    "embodiment {i} has no body, or a bad validFrom or validUntil"
5628                )),
5629            ),
5630            Some(ForkFailure::OutOfOrder(i)) => (
5631                false,
5632                None,
5633                Some(format!(
5634                    "embodiment {i} starts before the one before it; a segmented check reads the history in validFrom order"
5635                )),
5636            ),
5637            Some(ForkFailure::TooManyWindows(i)) => (
5638                false,
5639                None,
5640                Some(format!(
5641                    "at embodiment {i} more than {MAX_FORK_WINDOWS} windows on one body are open at once; check this history whole"
5642                )),
5643            ),
5644            None => match &self.conflict {
5645                Some(c) => (
5646                    false,
5647                    Some(c.clone()),
5648                    Some("the agent is in two bodies at once".into()),
5649                ),
5650                None => (true, None, None),
5651            },
5652        }
5653    }
5654}
5655
5656/// Check the next `embodiments` of a history (one segment) for forks and
5657/// move `progress` past them.
5658pub fn check_no_fork_segment(progress: &mut ForkProgress, embodiments: &[Value]) {
5659    for embodiment in embodiments {
5660        let i = progress.count;
5661        progress.count = progress.count.saturating_add(1);
5662        if matches!(
5663            progress.failure,
5664            Some(ForkFailure::Malformed(_)) | Some(ForkFailure::OutOfOrder(_))
5665        ) {
5666            continue;
5667        }
5668        let body = embodiment
5669            .get("credentialSubject")
5670            .and_then(|s| s.as_object())
5671            .and_then(|s| s.get("body"))
5672            .and_then(|v| v.as_str())
5673            .filter(|s| !s.is_empty());
5674        let start = rv::time_ns(embodiment.get("validFrom"));
5675        let end = match embodiment.get("validUntil") {
5676            None => Ok(None),
5677            Some(v) => rv::time_ns(Some(v)).map(Some).ok_or(()),
5678        };
5679        let (body, start, end) = match (body, start, end) {
5680            (Some(b), Some(s), Ok(e)) => (b, s, e),
5681            _ => {
5682                // The whole check answers (false, None) for a malformed
5683                // entry anywhere in the list, a fork or not.
5684                progress.failure = Some(ForkFailure::Malformed(i));
5685                continue;
5686            }
5687        };
5688        if progress.conflict.is_some() || progress.failure.is_some() {
5689            // The verdict is set; only a malformed entry can still change it.
5690            continue;
5691        }
5692        if progress.last_start.is_some_and(|p| start < p) {
5693            progress.failure = Some(ForkFailure::OutOfOrder(i));
5694            continue;
5695        }
5696        progress.last_start = Some(start);
5697        // Steps whose latest end is not after this start can never overlap
5698        // this or any later window (later windows start no earlier).
5699        let live = progress
5700            .windows
5701            .iter()
5702            .position(|(_, e)| ends_after(*e, start))
5703            .unwrap_or(progress.windows.len());
5704        progress.windows.drain(..live);
5705        if progress.windows.is_empty() {
5706            progress.body = None;
5707        }
5708        let same_body = progress.body.as_deref() == Some(body);
5709        if !same_body && progress.body.is_some() {
5710            // The latest end over the open windows on the other body that
5711            // start before this window's end. A window that ends after it
5712            // starts is past every kept start.
5713            let latest = progress
5714                .windows
5715                .iter()
5716                .take_while(|(s, _)| end.is_none_or(|e| *s < e))
5717                .last()
5718                .map(|(_, e)| *e);
5719            if let Some(latest) = latest {
5720                if ends_after(latest, start) {
5721                    progress.conflict = Some(ForkConflict {
5722                        body_a: progress.body.clone().unwrap_or_default(),
5723                        body_b: body.to_string(),
5724                    });
5725                    continue;
5726                }
5727            }
5728        }
5729        // A window that ends at or before its start never overlaps a later
5730        // window, so it is not kept.
5731        if !ends_after(end, start) {
5732            continue;
5733        }
5734        if !same_body {
5735            progress.body = Some(body.to_string());
5736            progress.windows.clear();
5737        }
5738        let grows = match progress.windows.last() {
5739            None => true,
5740            Some((_, latest)) => match (latest, end) {
5741                (None, _) => false,
5742                (Some(_), None) => true,
5743                (Some(l), Some(e)) => e > *l,
5744            },
5745        };
5746        if grows {
5747            if progress.windows.len() >= MAX_FORK_WINDOWS {
5748                progress.failure = Some(ForkFailure::TooManyWindows(i));
5749                continue;
5750            }
5751            progress.windows.push((start, end));
5752        }
5753    }
5754}
5755
5756/// The smallest i whose window overlaps a later window on another body, or
5757/// None: the window a pairwise scan in list order reports first, found in
5758/// O(n log n).
5759///
5760/// Times become ranks. Walking the list from the end, a Fenwick tree indexed by
5761/// start rank holds the later windows; each node keeps the latest end for its
5762/// range plus the latest end on any other body. Window i overlaps a later
5763/// window j on another body exactly when some j with start_j < end_i, on
5764/// another body, has end_j > start_i.
5765fn first_forked_index(windows: &[(String, i128, Option<i128>)]) -> Option<usize> {
5766    let mut times: Vec<i128> = windows
5767        .iter()
5768        .flat_map(|(_, s, e)| std::iter::once(*s).chain(*e))
5769        .collect();
5770    times.sort_unstable();
5771    times.dedup();
5772    let size = times.len();
5773    let rank = |t: i128| times.binary_search(&t).expect("every time is ranked") as i64;
5774    let mut body_ids: std::collections::HashMap<&str, i64> = std::collections::HashMap::new();
5775    let ranked: Vec<(i64, i64, i64)> = windows
5776        .iter()
5777        .map(|(b, s, e)| {
5778            let next = body_ids.len() as i64;
5779            let id = *body_ids.entry(b.as_str()).or_insert(next);
5780            (id, rank(*s), e.map_or(size as i64, rank))
5781        })
5782        .collect();
5783
5784    let mut tree = vec![TopTwo::EMPTY; size + 1];
5785    let mut first = None;
5786    for i in (0..ranked.len()).rev() {
5787        let (body, start, end) = ranked[i];
5788        let mut acc = TopTwo::EMPTY;
5789        let mut k = (end as usize).min(size);
5790        while k > 0 {
5791            acc.add(tree[k].end, tree[k].body);
5792            acc.add(tree[k].other_end, tree[k].other_body);
5793            k &= k - 1;
5794        }
5795        let other_end = if acc.body != body {
5796            acc.end
5797        } else {
5798            acc.other_end
5799        };
5800        if other_end > start {
5801            first = Some(i);
5802        }
5803        let mut k = start as usize + 1;
5804        while k <= size {
5805            tree[k].add(end, body);
5806            k += k & k.wrapping_neg();
5807        }
5808    }
5809    first
5810}
5811
5812/// The latest end in a range, and the latest end on a body other than its own.
5813#[derive(Clone, Copy)]
5814struct TopTwo {
5815    end: i64,
5816    body: i64,
5817    other_end: i64,
5818    other_body: i64,
5819}
5820
5821impl TopTwo {
5822    const EMPTY: TopTwo = TopTwo {
5823        end: -1,
5824        body: -1,
5825        other_end: -1,
5826        other_body: -1,
5827    };
5828
5829    fn add(&mut self, end: i64, body: i64) {
5830        if body < 0 {
5831            return;
5832        }
5833        if body == self.body {
5834            self.end = self.end.max(end);
5835        } else if body == self.other_body {
5836            if end > self.other_end {
5837                self.other_end = end;
5838                if self.other_end > self.end {
5839                    std::mem::swap(&mut self.end, &mut self.other_end);
5840                    std::mem::swap(&mut self.body, &mut self.other_body);
5841                }
5842            }
5843        } else if end > self.end {
5844            self.other_end = self.end;
5845            self.other_body = self.body;
5846            self.end = end;
5847            self.body = body;
5848        } else if end > self.other_end {
5849            self.other_end = end;
5850            self.other_body = body;
5851        }
5852    }
5853}
5854
5855// ---------------------------------------------------------------------------
5856// Physical custody handoff (Phase 5.16)
5857// ---------------------------------------------------------------------------
5858//
5859// A physical task or object passes across a chain of actors, human and robot: a
5860// person picks an item, hands it to a robot, that robot hands it to another
5861// robot, which places it. Each handoff is a signed custody transition, so a
5862// physical-world event traces to the exact hop and the actor responsible.
5863//
5864// A custody handoff credential records that a receiving actor accepted custody
5865// of a task or object from a releasing actor, signed by the receiver. Linking
5866// each handoff to the previous forms a chain a verifier walks to establish who
5867// held the task at any time. A condition attested at each handoff lets a state
5868// change be localized to the specific hop whose holder was responsible.
5869//
5870// This is the open layer: signed handoff credentials, chain verification, a
5871// holder-at-time helper, and software condition localization. It reuses the core
5872// proof path ([`data_integrity`]) rather than re-deriving any cryptography.
5873
5874pub const CUSTODY_HANDOFF_TYPE: &str = "CustodyHandoffCredential";
5875
5876/// A signed custody release: the actor handing a task over states that it
5877/// releases custody to the receiver. The receiver embeds it in its handoff.
5878pub const CUSTODY_RELEASE_TYPE: &str = "CustodyReleaseCredential";
5879
5880/// Build a signed custody release by `releaser_did` (the signer) for
5881/// `task_id` to `to_actor`, dated `released_at`.
5882pub fn build_release(
5883    releaser_seed: &[u8],
5884    releaser_did: &str,
5885    task_id: &str,
5886    to_actor: &str,
5887    released_at: &str,
5888) -> Result<Value> {
5889    if task_id.is_empty() || to_actor.is_empty() {
5890        return Err(CoreError::Json("task_id and to_actor are required".into()));
5891    }
5892    let cred = json!({
5893        "@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
5894        "type": ["VerifiableCredential", CUSTODY_RELEASE_TYPE],
5895        "issuer": releaser_did,
5896        "validFrom": released_at,
5897        "credentialSubject": {"id": task_id, "fromActor": releaser_did, "toActor": to_actor},
5898    });
5899    let opts = BuildProofOptions::new(format!("{releaser_did}#key-1"), released_at);
5900    data_integrity::sign(&cred, releaser_seed, &opts)
5901}
5902
5903/// Parameters for [`build_handoff`]. The signer is the receiver (`to_actor`), the
5904/// party taking responsibility. `condition`, when set, attests the state of the
5905/// task or object as received, which lets a later state change be localized to
5906/// a hop. `release` is the releasing actor's signed [`build_release`]
5907/// credential (a chain verifier requires it). `prev_handoff_id` is the previous
5908/// handoff's `id`; `credential_id` is this handoff's own `id`. `valid_until`,
5909/// when set, bounds the handoff's active window.
5910#[derive(Debug, Clone)]
5911pub struct BuildHandoff {
5912    pub task_id: String,
5913    pub from_actor: String,
5914    pub to_actor: String,
5915    pub condition: Option<String>,
5916    pub handoff_at: String,
5917    pub valid_until: Option<String>,
5918    pub release: Option<Value>,
5919    pub prev_handoff_id: Option<String>,
5920    pub credential_id: String,
5921}
5922
5923/// Build a signed custody handoff: the receiving actor `to_actor` accepts custody
5924/// of `task_id` from `from_actor`, signed by the receiver. The issuer is the
5925/// receiver, so a party attests its own acceptance of custody.
5926pub fn build_handoff(receiver_seed: &[u8], params: &BuildHandoff) -> Result<Value> {
5927    if params.task_id.is_empty() || params.from_actor.is_empty() || params.to_actor.is_empty() {
5928        return Err(CoreError::Json(
5929            "task_id, from_actor, and to_actor are required".into(),
5930        ));
5931    }
5932    if params.credential_id.is_empty() {
5933        return Err(CoreError::Json("credential_id is required".into()));
5934    }
5935
5936    let mut subject = Map::new();
5937    subject.insert("id".into(), json!(params.task_id));
5938    subject.insert("fromActor".into(), json!(params.from_actor));
5939    subject.insert("toActor".into(), json!(params.to_actor));
5940    if let Some(condition) = &params.condition {
5941        subject.insert("condition".into(), json!(condition));
5942    }
5943    if let Some(release) = &params.release {
5944        subject.insert("release".into(), release.clone());
5945    }
5946    if let Some(prev) = &params.prev_handoff_id {
5947        subject.insert("prevHandoffId".into(), json!(prev));
5948    }
5949
5950    let mut cred = Map::new();
5951    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5952    cred.insert("id".into(), json!(params.credential_id));
5953    cred.insert(
5954        "type".into(),
5955        json!(["VerifiableCredential", CUSTODY_HANDOFF_TYPE]),
5956    );
5957    cred.insert("issuer".into(), json!(params.to_actor));
5958    cred.insert("validFrom".into(), json!(params.handoff_at));
5959    if let Some(vu) = &params.valid_until {
5960        cred.insert("validUntil".into(), json!(vu));
5961    }
5962    cred.insert("credentialSubject".into(), Value::Object(subject));
5963
5964    let opts = BuildProofOptions::new(format!("{}#key-1", params.to_actor), &params.handoff_at);
5965    data_integrity::sign(&Value::Object(cred), receiver_seed, &opts)
5966}
5967
5968/// True when the handoff `subject` embeds a release signed by its `fromActor`
5969/// that names the same task and receiver.
5970fn release_ok(subject: &Value, releaser_keys: Keys<'_>, now_ns: i128) -> bool {
5971    let release = match subject.get("release") {
5972        Some(r) => r,
5973        None => return false,
5974    };
5975    let v = match rv::verify_robotics_credential(
5976        release,
5977        releaser_keys,
5978        Some(CUSTODY_RELEASE_TYPE),
5979        now_ns,
5980        VerifyOptions::window(Window::FromRequired),
5981    ) {
5982        Ok(v) => v,
5983        Err(_) => return false,
5984    };
5985    let s = |x: &Value, k: &str| x.get(k).and_then(|y| y.as_str()).map(String::from);
5986    Some(v.issuer.clone()) == s(subject, "fromActor")
5987        && s(&v.subject, "fromActor").as_deref() == Some(v.issuer.as_str())
5988        && s(&v.subject, "id") == s(subject, "id")
5989        && s(&v.subject, "toActor") == s(subject, "toActor")
5990}
5991
5992/// Options for [`verify_handoff`].
5993#[derive(Clone, Copy, Default)]
5994pub struct HandoffCheck<'a> {
5995    /// The handoff must be for this task.
5996    pub task_id: Option<&'a str>,
5997    /// Key source for the releasing actor; giving one requires the release.
5998    pub releaser_keys: Option<Keys<'a>>,
5999    /// Require the releasing actor's signed release (keys from the receiver
6000    /// source when no `releaser_keys` is given).
6001    pub require_release: bool,
6002    /// The releasing actor the caller expects. The release must be signed by
6003    /// it and name it as `fromActor`; with no releaser key a did:key releaser
6004    /// verifies under its own key only when this names it, and the receiver
6005    /// is then pinned to the toActor that verified release names.
6006    pub from_actor: Option<&'a str>,
6007}
6008
6009/// Verify a custody handoff: the receiver's proof bound to the issuer, the
6010/// issuer is the receiving actor (`toActor`), `id` / `fromActor` / `toActor`
6011/// are non-empty strings, and the window at `now_iso` (validFrom required).
6012/// With [`HandoffCheck`] options, the task is pinned and the embedded release
6013/// must be signed by the `fromActor` and name the same task and receiver.
6014pub fn verify_handoff(
6015    credential: &Value,
6016    receiver_keys: Keys<'_>,
6017    check: HandoffCheck<'_>,
6018    now_iso: &str,
6019) -> Result<Option<Value>> {
6020    let now = rv::require_now(now_iso)?;
6021    let releaser_keys = rv::pin_if_keyless(
6022        check.releaser_keys.unwrap_or(receiver_keys),
6023        check.from_actor,
6024    );
6025    // With no receiver key, the receiver is pinned to the toActor named by the
6026    // release the pinned releaser signed.
6027    let mut receiver_pin: Option<String> = None;
6028    if check.from_actor.is_some() && rv::no_key_source(&receiver_keys) {
6029        if let Some(rel) = credential
6030            .get("credentialSubject")
6031            .and_then(|s| s.get("release"))
6032        {
6033            if let Ok(r) = rv::verify_robotics_credential(
6034                rel,
6035                releaser_keys,
6036                Some(CUSTODY_RELEASE_TYPE),
6037                now,
6038                VerifyOptions::window(Window::FromRequired),
6039            ) {
6040                if r.subject.get("fromActor").and_then(|x| x.as_str()) == Some(r.issuer.as_str()) {
6041                    receiver_pin = non_empty_str(&r.subject, "toActor").map(String::from);
6042                }
6043            }
6044        }
6045    }
6046    let v = match rv::verify_robotics_credential(
6047        credential,
6048        rv::pin_if_keyless(receiver_keys, receiver_pin.as_deref()),
6049        Some(CUSTODY_HANDOFF_TYPE),
6050        now,
6051        VerifyOptions::window(Window::FromRequired),
6052    ) {
6053        Ok(v) => v,
6054        Err(_) => return Ok(None),
6055    };
6056    for f in ["id", "fromActor", "toActor"] {
6057        if non_empty_str(&v.subject, f).is_none() {
6058            return Ok(None);
6059        }
6060    }
6061    if v.subject.get("toActor").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
6062        return Ok(None);
6063    }
6064    if check
6065        .task_id
6066        .is_some_and(|t| v.subject.get("id").and_then(|x| x.as_str()) != Some(t))
6067    {
6068        return Ok(None);
6069    }
6070    if check
6071        .from_actor
6072        .is_some_and(|f| v.subject.get("fromActor").and_then(|x| x.as_str()) != Some(f))
6073    {
6074        return Ok(None);
6075    }
6076    if (check.require_release || check.releaser_keys.is_some() || check.from_actor.is_some())
6077        && !release_ok(&v.subject, releaser_keys, now)
6078    {
6079        return Ok(None);
6080    }
6081    Ok(Some(v.subject))
6082}
6083
6084/// One actor's public key, looked up by actor DID, for [`verify_handoff_chain`].
6085#[derive(Debug, Clone)]
6086pub struct ActorKey {
6087    pub did: String,
6088    pub public_key: Vec<u8>,
6089}
6090
6091/// Verify an ordered list of handoff credentials forms a valid custody chain for
6092/// `task_id`: every handoff verifies under its receiver's key and (with
6093/// `require_release`) carries a release signed by its releasing actor (keys for
6094/// both from `public_keys`); each `toActor` matches the next link's
6095/// `fromActor`; each link after the first names the previous link's `id` as
6096/// `prevHandoffId`; links are in time order; and the first `fromActor` is
6097/// `origin_actor`. Each earlier link must still have been valid when the next
6098/// began, and the last at `now_iso`. Returns `(ok, current_holder)`.
6099///
6100/// `origin_actor` is required: with no known first holder, anyone could sign a
6101/// first link handing the task from themselves. Each link's releaser is pinned
6102/// (the origin, then each `toActor`), so did:key actors verify under their own
6103/// keys even with no entry in `public_keys`.
6104pub fn verify_handoff_chain(
6105    handoffs: &[Value],
6106    public_keys: &[ActorKey],
6107    task_id: &str,
6108    origin_actor: Option<&str>,
6109    require_release: bool,
6110    now_iso: &str,
6111) -> Result<(bool, Option<String>)> {
6112    rv::require_now(now_iso)?;
6113    if task_id.is_empty() || origin_actor.is_none_or(str::is_empty) {
6114        return Ok((false, None));
6115    }
6116    let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
6117    let keys = Keys::Map(&map);
6118    let mut expected_from: Option<String> = origin_actor.map(String::from);
6119    let mut current_holder: Option<String> = origin_actor.map(String::from);
6120    let mut prev_id: Option<String> = None;
6121    let mut prev_time: Option<i128> = None;
6122    for (i, handoff) in handoffs.iter().enumerate() {
6123        let at: String = match handoffs.get(i + 1) {
6124            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
6125                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
6126                _ => return Ok((false, None)),
6127            },
6128            None => now_iso.to_string(),
6129        };
6130        let check = HandoffCheck {
6131            task_id: Some(task_id),
6132            releaser_keys: if require_release { Some(keys) } else { None },
6133            require_release,
6134            from_actor: if require_release {
6135                expected_from.as_deref()
6136            } else {
6137                None
6138            },
6139        };
6140        let subject = match verify_handoff(handoff, keys, check, &at)? {
6141            Some(s) => s,
6142            None => return Ok((false, None)),
6143        };
6144        if let Some(expected) = &expected_from {
6145            if subject.get("fromActor").and_then(|v| v.as_str()) != Some(expected.as_str()) {
6146                return Ok((false, None));
6147            }
6148        }
6149        match rv::time_ns(handoff.get("validFrom")) {
6150            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
6151            _ => return Ok((false, None)),
6152        }
6153        if i > 0 {
6154            match &prev_id {
6155                Some(p) if subject.get("prevHandoffId").and_then(|v| v.as_str()) == Some(p) => {}
6156                _ => return Ok((false, None)),
6157            }
6158        }
6159        prev_id = non_empty_str(handoff, "id").map(String::from);
6160        current_holder = subject
6161            .get("toActor")
6162            .and_then(|v| v.as_str())
6163            .map(String::from);
6164        expected_from = current_holder.clone();
6165    }
6166    Ok((true, current_holder))
6167}
6168
6169/// Return the actor holding the task at protocol time `at`: the receiver
6170/// (`toActor`) of the most recent handoff whose `validFrom` is at or before
6171/// `at`. Returns `None` if no handoff had occurred yet or `at` is not a strict
6172/// protocol time. `handoffs` is assumed in chain order.
6173pub fn holder_at(handoffs: &[Value], at: &str) -> Option<String> {
6174    let when = crate::time::parse_protocol_time_ns(at).ok()?;
6175    let mut holder: Option<String> = None;
6176    for handoff in handoffs {
6177        if let Some(start) = rv::time_ns(handoff.get("validFrom")) {
6178            if start <= when {
6179                holder = handoff
6180                    .get("credentialSubject")
6181                    .and_then(|s| s.get("toActor"))
6182                    .and_then(|v| v.as_str())
6183                    .map(String::from);
6184            }
6185        }
6186    }
6187    holder
6188}
6189
6190/// A condition change localized to the hop responsible for it, surfaced by
6191/// [`locate_condition_change`].
6192#[derive(Debug, Clone, PartialEq, Eq)]
6193pub struct ConditionChange {
6194    pub responsible_holder: Option<String>,
6195    pub from_condition: String,
6196    pub to_condition: String,
6197}
6198
6199/// Find the first hop where the attested condition differs from the previous
6200/// handoff. The holder responsible for the change is the actor who held the task
6201/// during it (the previous handoff's receiver). Returns the change, or `None` if
6202/// the condition never changed. Handoffs without a condition are skipped for the
6203/// comparison.
6204pub fn locate_condition_change(handoffs: &[Value]) -> Option<ConditionChange> {
6205    let mut prev_condition: Option<String> = None;
6206    let mut prev_holder: Option<String> = None;
6207    for handoff in handoffs {
6208        let subject = handoff.get("credentialSubject");
6209        let condition = subject
6210            .and_then(|s| s.get("condition"))
6211            .and_then(|v| v.as_str());
6212        let condition = match condition {
6213            Some(c) => c,
6214            None => continue,
6215        };
6216        if let Some(prev) = &prev_condition {
6217            if condition != prev {
6218                return Some(ConditionChange {
6219                    responsible_holder: prev_holder,
6220                    from_condition: prev.clone(),
6221                    to_condition: condition.to_string(),
6222                });
6223            }
6224        }
6225        prev_condition = Some(condition.to_string());
6226        prev_holder = subject
6227            .and_then(|s| s.get("toActor"))
6228            .and_then(|v| v.as_str())
6229            .map(String::from);
6230    }
6231    None
6232}
6233
6234// ---------------------------------------------------------------------------
6235// Robot-to-infrastructure bounded access (Phase 5.17)
6236// ---------------------------------------------------------------------------
6237//
6238// A robot in a warehouse, hospital, or building needs to open doors, call
6239// elevators, dock at chargers, and operate machines. This gives it a bounded,
6240// revocable, auditable way to do so. The infrastructure operator issues an access
6241// grant naming a resource, the permitted operations, an optional zone, and a time
6242// window, signed by the operator. The robot presents a signed access request for a
6243// specific operation on a specific resource, and the resource authorizes it
6244// offline: the grant must be valid and operator-signed, the request valid and
6245// robot-signed, the operation permitted, and the moment inside the window. The
6246// grant plus the request is a tamper-evident, attributable record of the access.
6247//
6248// This is the open layer: signed grants and requests, an offline authorize
6249// decision, shrink-only attenuation, and the audit record. Hardware-enforced
6250// actuation in the resource and managed fleet access-policy orchestration are out
6251// of scope for the open layer.
6252
6253pub const ACCESS_GRANT_TYPE: &str = "InfrastructureAccessGrant";
6254pub const ACCESS_REQUEST_TYPE: &str = "InfrastructureAccessRequest";
6255
6256/// Parameters for [`build_access_grant`]. The signer is the operator; the grant
6257/// names the robot, the resource, the permitted operations, an optional zone, and
6258/// a validity window. `valid_until`, when set, bounds the window (the wrapper
6259/// derives it from a `valid_seconds` lifetime added to `granted_at`, keeping the
6260/// core's clock caller-supplied).
6261#[derive(Debug, Clone)]
6262pub struct BuildAccessGrant {
6263    pub operator_did: String,
6264    pub robot_did: String,
6265    pub resource: String,
6266    pub operations: Vec<String>,
6267    pub zone: Option<String>,
6268    pub granted_at: String,
6269    pub valid_until: Option<String>,
6270}
6271
6272/// Build a signed access grant: the operator grants `robot_did` permission to
6273/// perform `operations` on `resource` (optionally within `zone`) for the window.
6274/// Signed by the operator.
6275pub fn build_access_grant(operator_seed: &[u8], params: &BuildAccessGrant) -> Result<Value> {
6276    if params.robot_did.is_empty() || params.resource.is_empty() {
6277        return Err(CoreError::Json(
6278            "robot_did and resource are required".into(),
6279        ));
6280    }
6281    if params.operations.is_empty() {
6282        return Err(CoreError::Json(
6283            "operations must be a non-empty list".into(),
6284        ));
6285    }
6286
6287    let mut subject = Map::new();
6288    subject.insert("id".into(), json!(params.robot_did));
6289    subject.insert("resource".into(), json!(params.resource));
6290    subject.insert("operations".into(), json!(params.operations));
6291    if let Some(zone) = &params.zone {
6292        subject.insert("zone".into(), json!(zone));
6293    }
6294
6295    let mut cred = Map::new();
6296    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6297    cred.insert(
6298        "type".into(),
6299        json!(["VerifiableCredential", ACCESS_GRANT_TYPE]),
6300    );
6301    cred.insert("issuer".into(), json!(params.operator_did));
6302    cred.insert("validFrom".into(), json!(params.granted_at));
6303    if let Some(vu) = &params.valid_until {
6304        cred.insert("validUntil".into(), json!(vu));
6305    }
6306    cred.insert("credentialSubject".into(), Value::Object(subject));
6307
6308    let opts = BuildProofOptions::new(format!("{}#key-1", params.operator_did), &params.granted_at);
6309    data_integrity::sign(&Value::Object(cred), operator_seed, &opts)
6310}
6311
6312/// Verify an access grant: the operator's proof bound to the issuer
6313/// (`operator_keys` is a `{did: key}` source, or the bare key of a did:key
6314/// operator), validFrom and validUntil present strict protocol times with
6315/// `now_iso` inside, a non-empty string `resource`, a non-empty list of string
6316/// `operations`, and (when given) the operator in `trusted_operators`. Returns
6317/// the credentialSubject on success, `None` if invalid.
6318pub fn verify_access_grant(
6319    credential: &Value,
6320    operator_keys: Keys<'_>,
6321    trusted_operators: Option<&HashSet<String>>,
6322    now_iso: &str,
6323) -> Result<Option<Value>> {
6324    let now = rv::require_now(now_iso)?;
6325    let opts = VerifyOptions {
6326        trusted_issuers: trusted_operators,
6327        ..VerifyOptions::window(Window::Required)
6328    };
6329    let v = match rv::verify_robotics_credential(
6330        credential,
6331        operator_keys,
6332        Some(ACCESS_GRANT_TYPE),
6333        now,
6334        opts,
6335    ) {
6336        Ok(v) => v,
6337        Err(_) => return Ok(None),
6338    };
6339    if non_empty_str(&v.subject, "resource").is_none() {
6340        return Ok(None);
6341    }
6342    match v.subject.get("operations") {
6343        Some(Value::Array(ops)) if !ops.is_empty() && ops.iter().all(|o| o.is_string()) => {}
6344        _ => return Ok(None),
6345    }
6346    Ok(Some(v.subject))
6347}
6348
6349/// Parameters for [`build_access_request`]. The signer is the robot; the request
6350/// names the resource and the single operation the robot wants to perform.
6351#[derive(Debug, Clone)]
6352pub struct BuildAccessRequest {
6353    pub robot_did: String,
6354    pub resource: String,
6355    pub operation: String,
6356    pub requested_at: String,
6357    /// A one-time value the resource remembers to refuse a replay.
6358    pub nonce: String,
6359}
6360
6361/// Build a signed access request: the robot requests to perform `operation` on
6362/// `resource`. Signed by the robot.
6363pub fn build_access_request(robot_seed: &[u8], params: &BuildAccessRequest) -> Result<Value> {
6364    if params.robot_did.is_empty() || params.resource.is_empty() || params.operation.is_empty() {
6365        return Err(CoreError::Json(
6366            "robot_did, resource, and operation are required".into(),
6367        ));
6368    }
6369    if params.nonce.is_empty() {
6370        return Err(CoreError::Json("nonce is required".into()));
6371    }
6372
6373    let mut subject = Map::new();
6374    subject.insert("id".into(), json!(params.robot_did));
6375    subject.insert("resource".into(), json!(params.resource));
6376    subject.insert("operation".into(), json!(params.operation));
6377    subject.insert("nonce".into(), json!(params.nonce));
6378
6379    let mut cred = Map::new();
6380    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6381    cred.insert(
6382        "type".into(),
6383        json!(["VerifiableCredential", ACCESS_REQUEST_TYPE]),
6384    );
6385    cred.insert("issuer".into(), json!(params.robot_did));
6386    cred.insert("validFrom".into(), json!(params.requested_at));
6387    cred.insert("credentialSubject".into(), Value::Object(subject));
6388
6389    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.requested_at);
6390    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
6391}
6392
6393/// The outcome of an offline access authorization: `ok` plus any reasons it
6394/// failed. Surfaced by [`authorize_access`].
6395#[derive(Debug, Clone)]
6396pub struct AuthorizeResult {
6397    pub ok: bool,
6398    pub reasons: Vec<String>,
6399}
6400
6401/// Decide, offline, whether to allow the requested access. The grant must verify
6402/// under the operator's key and be in window, the request must verify bound to
6403/// the robot as issuer (and name it as subject) with validFrom no later than
6404/// `now_iso` (keys are `{did: key}` sources, or bare keys of did:key parties), the grant and request must
6405/// name the same robot and resource, and the requested operation must be permitted
6406/// by the grant. Returns an [`AuthorizeResult`] with the reasons for any refusal.
6407/// How old an access request may be by default (seconds).
6408pub const DEFAULT_MAX_REQUEST_AGE_SECONDS: i64 = 60;
6409
6410/// Replay limits for [`authorize_access`]: the request may be no older than
6411/// `max_age_seconds` and not from the future (both with `clock_skew_seconds`),
6412/// and its nonce must not be in `seen_nonces` (it is added when access is
6413/// allowed).
6414pub struct RequestReplay<'a> {
6415    pub seen_nonces: &'a mut HashSet<String>,
6416    pub max_age_seconds: i64,
6417    pub clock_skew_seconds: i64,
6418    /// With no operator key, the grant verifies only when its did:key
6419    /// operator is in this non-empty set.
6420    pub trusted_operators: Option<&'a HashSet<String>>,
6421}
6422
6423impl<'a> RequestReplay<'a> {
6424    /// The default limits (60 s age, 30 s skew) over `seen_nonces`.
6425    pub fn new(seen_nonces: &'a mut HashSet<String>) -> Self {
6426        Self {
6427            seen_nonces,
6428            max_age_seconds: DEFAULT_MAX_REQUEST_AGE_SECONDS,
6429            clock_skew_seconds: 30,
6430            trusted_operators: None,
6431        }
6432    }
6433}
6434
6435pub fn authorize_access(
6436    grant: &Value,
6437    request: &Value,
6438    operator_keys: Keys<'_>,
6439    robot_keys: Keys<'_>,
6440    replay: RequestReplay<'_>,
6441    now_iso: &str,
6442) -> Result<AuthorizeResult> {
6443    let current = rv::require_now(now_iso)?;
6444    let mut reasons: Vec<String> = Vec::new();
6445
6446    let grant_subject =
6447        match verify_access_grant(grant, operator_keys, replay.trusted_operators, now_iso)? {
6448            Some(s) => s,
6449            None => {
6450                reasons.push("grant invalid or out of window".into());
6451                return Ok(AuthorizeResult { ok: false, reasons });
6452            }
6453        };
6454
6455    // With no robot key, only the robot the verified grant names may sign.
6456    let granted_robot = grant_subject
6457        .get("id")
6458        .and_then(|v| v.as_str())
6459        .map(String::from);
6460    let req_subject = match bound(
6461        request,
6462        rv::pin_if_keyless(robot_keys, granted_robot.as_deref()),
6463        ACCESS_REQUEST_TYPE,
6464        now_iso,
6465        Window::FromRequired,
6466    )? {
6467        Some(v) if issuer_is_subject(&v) => v.subject,
6468        _ => {
6469            reasons.push("request invalid".into());
6470            return Ok(AuthorizeResult { ok: false, reasons });
6471        }
6472    };
6473    let second: i128 = 1_000_000_000;
6474    let skew = i128::from(replay.clock_skew_seconds) * second;
6475    match rv::time_ns(request.get("validFrom")) {
6476        Some(issued) if issued > current + skew => {
6477            reasons.push("request is dated in the future".into())
6478        }
6479        Some(issued) if current - issued > i128::from(replay.max_age_seconds) * second + skew => {
6480            reasons.push("request is too old".into())
6481        }
6482        Some(_) => {}
6483        None => reasons.push("request is dated in the future".into()),
6484    }
6485    let nonce = non_empty_str(&req_subject, "nonce").map(String::from);
6486    match &nonce {
6487        None => reasons.push("request carries no nonce".into()),
6488        Some(n) if replay.seen_nonces.contains(n) => {
6489            reasons.push("request was already used (replay)".into())
6490        }
6491        Some(_) => {}
6492    }
6493    if !reasons.is_empty() {
6494        return Ok(AuthorizeResult { ok: false, reasons });
6495    }
6496    let req_id = req_subject.get("id").and_then(|v| v.as_str());
6497
6498    if grant_subject.get("id").and_then(|v| v.as_str()) != req_id {
6499        reasons.push("grant and request name different robots".into());
6500    }
6501    if grant_subject.get("resource").and_then(|v| v.as_str())
6502        != req_subject.get("resource").and_then(|v| v.as_str())
6503    {
6504        reasons.push("grant and request name different resources".into());
6505    }
6506    let operation = req_subject.get("operation").and_then(|v| v.as_str());
6507    let permitted = grant_subject
6508        .get("operations")
6509        .and_then(|v| v.as_array())
6510        .map(|ops| operation.is_some() && ops.iter().any(|o| o.as_str() == operation))
6511        .unwrap_or(false);
6512    if !permitted {
6513        reasons.push("operation not permitted by the grant".into());
6514    }
6515    if reasons.is_empty() {
6516        if let Some(n) = nonce {
6517            replay.seen_nonces.insert(n);
6518        }
6519    }
6520
6521    Ok(AuthorizeResult {
6522        ok: reasons.is_empty(),
6523        reasons,
6524    })
6525}
6526
6527/// Return true if `child` is a valid attenuation of `parent`: the same resource, a
6528/// subset of the operations, and the same zone (or the parent had no zone). A
6529/// sub-grant may only narrow, never widen, the access it inherits.
6530pub fn attenuates_grant(parent: &Value, child: &Value) -> bool {
6531    let p = parent.get("credentialSubject");
6532    let c = child.get("credentialSubject");
6533    let p_resource = p.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
6534    let c_resource = c.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
6535    if p_resource != c_resource {
6536        return false;
6537    }
6538    let p_ops: HashSet<&str> = p
6539        .and_then(|s| s.get("operations"))
6540        .and_then(|v| v.as_array())
6541        .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
6542        .unwrap_or_default();
6543    let c_ops: HashSet<&str> = c
6544        .and_then(|s| s.get("operations"))
6545        .and_then(|v| v.as_array())
6546        .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
6547        .unwrap_or_default();
6548    if !c_ops.is_subset(&p_ops) {
6549        return false;
6550    }
6551    let p_zone = p.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
6552    let c_zone = c.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
6553    if p_zone.is_some() && c_zone != p_zone {
6554        return false;
6555    }
6556    true
6557}
6558
6559// ---------------------------------------------------------------------------
6560// Fused-sensor provenance (Phase 5.18)
6561// ---------------------------------------------------------------------------
6562//
6563// Perception provenance signs individual sensor frames. A robot rarely acts on
6564// one frame, though: it fuses many frames, from cameras, lidar, radar, and other
6565// sensors, into a single world model, an object set, an occupancy grid, or a
6566// pose estimate, and acts on that. This binds a fused output to the exact set of
6567// input frames that produced it and the fusion method that produced it, signed by
6568// the robot, so a manipulated fusion result or a silently dropped or substituted
6569// input is detectable at the provenance layer.
6570//
6571// A fused-perception attestation carries the hash of the fused output, an ordered
6572// list of the input frame hashes, a digest over those inputs, and a fusion method
6573// identifier, signed by the robot. A verifier reproduces the input digest from the
6574// listed inputs and, when it holds the raw fused output, reproduces its hash, so
6575// the attestation commits to exactly those inputs and that output. Checking each
6576// listed input against the robot's signed perception log confirms every fused
6577// input traces to a frame the robot actually recorded.
6578//
6579// This is the open layer: the robot signs the binding of a fused output to its
6580// inputs in software, reusing the perception frame hashes. Hardware sensor
6581// attestation and managed sensor-fusion orchestration are out of scope for the
6582// open layer.
6583
6584pub const FUSED_PERCEPTION_TYPE: &str = "FusedPerceptionAttestation";
6585
6586/// Multibase (base64url) SHA-256 of a raw fused output. Only the hash travels in
6587/// the attestation; the fused output stays wherever the deployment keeps it.
6588pub fn hash_fused_output(output: &[u8]) -> String {
6589    mb64(&Sha256::digest(output))
6590}
6591
6592/// Input-digest version 1: SHA-256 of the hashes joined by "\n" (the
6593/// original; assumed when an attestation names no version).
6594pub const INPUTS_DIGEST_V1: &str = "1";
6595/// Input-digest version 2: SHA-256 of the JCS JSON array of the hashes (the
6596/// default for new attestations).
6597pub const INPUTS_DIGEST_V2: &str = "2";
6598
6599/// Deterministic multibase digest over an ordered list of input frame hashes
6600/// (version 2, the default). It commits to the exact inputs and their order.
6601pub fn fusion_inputs_digest(input_frame_hashes: &[String]) -> Result<String> {
6602    fusion_inputs_digest_version(input_frame_hashes, INPUTS_DIGEST_V2)
6603}
6604
6605/// [`fusion_inputs_digest`] under a named version. Version 1 refuses a hash
6606/// that contains "\n" (otherwise two different lists could share a digest).
6607pub fn fusion_inputs_digest_version(
6608    input_frame_hashes: &[String],
6609    version: &str,
6610) -> Result<String> {
6611    if input_frame_hashes.is_empty() {
6612        return Err(CoreError::Json(
6613            "input_frame_hashes must be a non-empty list".into(),
6614        ));
6615    }
6616    for h in input_frame_hashes {
6617        if h.is_empty() {
6618            return Err(CoreError::Json(
6619                "each input frame hash must be a non-empty string".into(),
6620            ));
6621        }
6622    }
6623    match version {
6624        INPUTS_DIGEST_V2 => Ok(mb64(&Sha256::digest(jcs::canonicalize(&json!(
6625            input_frame_hashes
6626        ))))),
6627        INPUTS_DIGEST_V1 => {
6628            if input_frame_hashes.iter().any(|h| h.contains('\n')) {
6629                return Err(CoreError::Json(
6630                    "a version 1 input digest cannot carry a hash containing a newline".into(),
6631                ));
6632            }
6633            Ok(mb64(&Sha256::digest(
6634                input_frame_hashes.join("\n").as_bytes(),
6635            )))
6636        }
6637        other => Err(CoreError::Json(format!(
6638            "unknown inputs digest version {other:?}"
6639        ))),
6640    }
6641}
6642
6643/// Parameters for [`build_fused_attestation`]. The robot self-issues the
6644/// credential with its own Ed25519 seed. Provide either the raw `fused_output` (it
6645/// is hashed) or a precomputed `fused_output_hash`, not both. `captured_at`, when
6646/// `None`, defaults to `valid_from`.
6647#[derive(Debug, Clone)]
6648pub struct BuildFusedAttestation {
6649    pub robot_did: String,
6650    pub fusion_method: String,
6651    pub input_frame_hashes: Vec<String>,
6652    pub fused_output: Option<Vec<u8>>,
6653    pub fused_output_hash: Option<String>,
6654    pub captured_at: Option<String>,
6655    pub valid_from: String,
6656    pub valid_until: Option<String>,
6657}
6658
6659/// Build a signed `FusedPerceptionAttestation`: the robot attests that a fused
6660/// output was produced by `fusion_method` from the frames named in
6661/// `input_frame_hashes`. The attestation carries a digest over the ordered inputs,
6662/// so the set of inputs is tamper-evident. Signed by the robot.
6663pub fn build_fused_attestation(robot_seed: &[u8], params: &BuildFusedAttestation) -> Result<Value> {
6664    if params.robot_did.is_empty() {
6665        return Err(CoreError::Json("robot_did is required".into()));
6666    }
6667    if params.fusion_method.is_empty() {
6668        return Err(CoreError::Json("fusion_method is required".into()));
6669    }
6670    if params.input_frame_hashes.is_empty() {
6671        return Err(CoreError::Json(
6672            "input_frame_hashes must be a non-empty list".into(),
6673        ));
6674    }
6675    if params.fused_output.is_some() && params.fused_output_hash.is_some() {
6676        return Err(CoreError::Json(
6677            "provide either fused_output or fused_output_hash, not both".into(),
6678        ));
6679    }
6680    let fused_output_hash = match (&params.fused_output, &params.fused_output_hash) {
6681        (Some(o), None) => hash_fused_output(o),
6682        (None, Some(h)) if !h.is_empty() => h.clone(),
6683        _ => {
6684            return Err(CoreError::Json(
6685                "fused_output or fused_output_hash is required".into(),
6686            ))
6687        }
6688    };
6689
6690    let captured = params
6691        .captured_at
6692        .clone()
6693        .unwrap_or_else(|| params.valid_from.clone());
6694
6695    let mut subject = Map::new();
6696    subject.insert("id".into(), json!(params.robot_did));
6697    subject.insert("fusionMethod".into(), json!(params.fusion_method));
6698    subject.insert("fusedOutputHash".into(), json!(fused_output_hash));
6699    subject.insert("inputFrameHashes".into(), json!(params.input_frame_hashes));
6700    subject.insert(
6701        "inputsDigest".into(),
6702        json!(fusion_inputs_digest(&params.input_frame_hashes)?),
6703    );
6704    subject.insert("inputsDigestVersion".into(), json!(INPUTS_DIGEST_V2));
6705    subject.insert("capturedAt".into(), json!(captured));
6706
6707    let mut cred = Map::new();
6708    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6709    cred.insert(
6710        "type".into(),
6711        json!(["VerifiableCredential", FUSED_PERCEPTION_TYPE]),
6712    );
6713    cred.insert("issuer".into(), json!(params.robot_did));
6714    cred.insert("validFrom".into(), json!(params.valid_from));
6715    if let Some(vu) = &params.valid_until {
6716        cred.insert("validUntil".into(), json!(vu));
6717    }
6718    cred.insert("credentialSubject".into(), Value::Object(subject));
6719
6720    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
6721    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
6722}
6723
6724/// Verify a `FusedPerceptionAttestation`: the robot's proof bound to the robot
6725/// as issuer (which must also be `credentialSubject.id`), the window at
6726/// `now_iso` (validFrom required), that the digest over
6727/// the listed inputs reproduces the attested `inputsDigest` (so the inputs are
6728/// internally consistent and tamper-evident), and, when the raw `fused_output` is
6729/// supplied, that its hash reproduces the attested `fusedOutputHash`. Returns the
6730/// credentialSubject on success, `None` if invalid.
6731pub fn verify_fused_attestation(
6732    credential: &Value,
6733    keys: Keys<'_>,
6734    fused_output: Option<&[u8]>,
6735    now_iso: &str,
6736) -> Result<Option<Value>> {
6737    let v = match bound(
6738        credential,
6739        keys,
6740        FUSED_PERCEPTION_TYPE,
6741        now_iso,
6742        Window::FromRequired,
6743    )? {
6744        Some(v) if issuer_is_subject(&v) => v,
6745        _ => return Ok(None),
6746    };
6747    let subject = v.subject;
6748    let fused_output_hash = non_empty_str(&subject, "fusedOutputHash");
6749    let inputs: Vec<String> = match subject.get("inputFrameHashes") {
6750        Some(Value::Array(a)) if !a.is_empty() && a.iter().all(|e| e.is_string()) => a
6751            .iter()
6752            .filter_map(|e| e.as_str().map(String::from))
6753            .collect(),
6754        _ => return Ok(None),
6755    };
6756    if fused_output_hash.is_none() {
6757        return Ok(None);
6758    }
6759    let version = match subject.get("inputsDigestVersion") {
6760        None => INPUTS_DIGEST_V1,
6761        Some(Value::String(v)) if v == INPUTS_DIGEST_V1 || v == INPUTS_DIGEST_V2 => v.as_str(),
6762        _ => return Ok(None),
6763    };
6764    match fusion_inputs_digest_version(&inputs, version) {
6765        Ok(d) => {
6766            if Some(d.as_str()) != subject.get("inputsDigest").and_then(|v| v.as_str()) {
6767                return Ok(None);
6768            }
6769        }
6770        Err(_) => return Ok(None),
6771    }
6772    if let Some(o) = fused_output {
6773        if Some(hash_fused_output(o).as_str()) != fused_output_hash {
6774            return Ok(None);
6775        }
6776    }
6777    Ok(Some(subject))
6778}
6779
6780/// The outcome of confirming an attestation's inputs against a perception log:
6781/// `ok` plus the input frame hashes not found. Surfaced by [`verify_fusion_inputs`].
6782#[derive(Debug, Clone)]
6783pub struct FusionInputsResult {
6784    pub ok: bool,
6785    pub missing: Vec<String>,
6786}
6787
6788/// Confirm every input frame the attestation names was actually recorded in the
6789/// robot's perception log. Returns `ok` plus `missing`, the input frame hashes that
6790/// do not appear as a recorded frame, so a dropped or substituted fused input is
6791/// named rather than hidden.
6792pub fn verify_fusion_inputs(credential: &Value, log_entries: &[Value]) -> FusionInputsResult {
6793    let recorded: HashSet<&str> = log_entries
6794        .iter()
6795        .filter_map(|e| e.get("frameHash").and_then(|v| v.as_str()))
6796        .filter(|h| !h.is_empty())
6797        .collect();
6798    // A missing or empty input list is malformed: fail closed.
6799    let inputs = match credential
6800        .get("credentialSubject")
6801        .and_then(|s| s.get("inputFrameHashes"))
6802        .and_then(|v| v.as_array())
6803    {
6804        Some(a) if !a.is_empty() => a,
6805        _ => {
6806            return FusionInputsResult {
6807                ok: false,
6808                missing: Vec::new(),
6809            }
6810        }
6811    };
6812    let missing: Vec<String> = inputs
6813        .iter()
6814        .filter(|h| !h.as_str().is_some_and(|s| recorded.contains(s)))
6815        .map(|h| match h.as_str() {
6816            Some(s) => s.to_string(),
6817            None => h.to_string(),
6818        })
6819        .collect();
6820    FusionInputsResult {
6821        ok: missing.is_empty(),
6822        missing,
6823    }
6824}
6825
6826// ---------------------------------------------------------------------------
6827// Wear and degradation attestation (Phase 5.19)
6828// ---------------------------------------------------------------------------
6829//
6830// A robot does not stay as capable as it left the factory. Actuators wear, joints
6831// develop backlash, sensors drift out of calibration, and error rates creep up.
6832// This lets a robot sign its own degradation state, bound to its identity and
6833// hash-linked over time so the history is tamper-evident, and derives a narrowed
6834// physical capability scope from that state, so a worn robot operates inside a
6835// tighter, verifiable envelope instead of trusting the static limit it shipped
6836// with.
6837//
6838// A wear attestation carries a normalized wear level (0 for as-new, 1 for fully
6839// worn) and optional detailed metrics, signed by the robot. Linking each
6840// attestation to the previous one by its proof value forms a chain a verifier
6841// walks to see how the robot degraded over its life. `attenuate_for_wear` derives
6842// a physical scope whose numeric caps are scaled down by the wear level, and the
6843// result is a valid attenuation of the original scope, so the same attenuation
6844// rule the rest of Vouch uses carries the derating.
6845//
6846// This is the open layer: the robot signs its wear state and derives the narrowed
6847// scope credential in software. Firmware-level enforcement of the narrowed
6848// envelope and managed predictive-maintenance modeling are out of scope for the
6849// open layer.
6850
6851pub const WEAR_ATTESTATION_TYPE: &str = "RobotWearAttestation";
6852
6853/// Numeric caps that scale down with wear. Zones and shift windows are preserved
6854/// unchanged, so the derived scope stays a valid attenuation of the original.
6855const WEAR_DERATED_CAPS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
6856
6857/// Parameters for [`build_wear_attestation`]. The robot self-issues the credential
6858/// with its own Ed25519 seed. `metrics`, when present, is carried through into the
6859/// subject unchanged. `prev_proof`, when present, links this attestation to the
6860/// previous one, forming a wear history. `attested_at`, when `None`, defaults to
6861/// `valid_from`.
6862#[derive(Debug, Clone)]
6863pub struct BuildWearAttestation {
6864    pub robot_did: String,
6865    pub wear_level: f64,
6866    pub metrics: Option<Value>,
6867    pub prev_proof: Option<String>,
6868    pub attested_at: Option<String>,
6869    pub valid_from: String,
6870    pub valid_until: Option<String>,
6871}
6872
6873/// Build a signed `RobotWearAttestation`: the robot attests its own degradation as
6874/// a normalized `wear_level` in `[0, 1]`, optionally with detailed `metrics`. When
6875/// `prev_proof` is the proof value of the previous attestation, the new one links
6876/// to it, forming a tamper-evident wear history. Signed by the robot.
6877pub fn build_wear_attestation(robot_seed: &[u8], params: &BuildWearAttestation) -> Result<Value> {
6878    if params.robot_did.is_empty() {
6879        return Err(CoreError::Json("robot_did is required".into()));
6880    }
6881    if params.wear_level < 0.0 || params.wear_level > 1.0 {
6882        return Err(CoreError::Json(
6883            "wear_level must be between 0.0 and 1.0".into(),
6884        ));
6885    }
6886
6887    let attested = params
6888        .attested_at
6889        .clone()
6890        .unwrap_or_else(|| params.valid_from.clone());
6891
6892    let mut subject = Map::new();
6893    subject.insert("id".into(), json!(params.robot_did));
6894    subject.insert("wearLevel".into(), json!(params.wear_level));
6895    subject.insert("attestedAt".into(), json!(attested));
6896    if let Some(m) = &params.metrics {
6897        subject.insert("metrics".into(), m.clone());
6898    }
6899    if let Some(prev) = &params.prev_proof {
6900        subject.insert("prevProof".into(), json!(prev));
6901    }
6902
6903    let mut cred = Map::new();
6904    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6905    cred.insert(
6906        "type".into(),
6907        json!(["VerifiableCredential", WEAR_ATTESTATION_TYPE]),
6908    );
6909    cred.insert("issuer".into(), json!(params.robot_did));
6910    cred.insert("validFrom".into(), json!(params.valid_from));
6911    if let Some(vu) = &params.valid_until {
6912        cred.insert("validUntil".into(), json!(vu));
6913    }
6914    cred.insert("credentialSubject".into(), Value::Object(subject));
6915
6916    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
6917    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
6918}
6919
6920/// Verify a `RobotWearAttestation`: the robot's proof bound to the robot as
6921/// issuer (which must also be `credentialSubject.id`), the window at `now_iso`
6922/// (validFrom required), and that the wear level is a finite number in [0, 1]. Returns the credentialSubject on
6923/// success, `None` if invalid.
6924pub fn verify_wear_attestation(
6925    credential: &Value,
6926    keys: Keys<'_>,
6927    now_iso: &str,
6928) -> Result<Option<Value>> {
6929    let v = match bound(
6930        credential,
6931        keys,
6932        WEAR_ATTESTATION_TYPE,
6933        now_iso,
6934        Window::FromRequired,
6935    )? {
6936        Some(v) if issuer_is_subject(&v) => v,
6937        _ => return Ok(None),
6938    };
6939    match rv::finite_number(v.subject.get("wearLevel")) {
6940        Some(level) if (0.0..=1.0).contains(&level) => Ok(Some(v.subject)),
6941        _ => Ok(None),
6942    }
6943}
6944
6945/// Verify an ordered wear history: each attestation verifies under the same
6946/// robot, each one after the first links to the previous by its proof value,
6947/// and they are in time order. Each earlier attestation must still have been
6948/// valid when the next was made, and the last at `now_iso`. Returns the latest
6949/// credentialSubject on success, `None` if the chain is empty or invalid.
6950pub fn verify_wear_chain(
6951    attestations: &[Value],
6952    keys: Keys<'_>,
6953    now_iso: &str,
6954) -> Result<Option<Value>> {
6955    rv::require_now(now_iso)?;
6956    if attestations.is_empty() {
6957        return Ok(None);
6958    }
6959    let mut prev_proof: Option<String> = None;
6960    let mut prev_time: Option<i128> = None;
6961    let mut robot: Option<String> = None;
6962    let mut latest: Option<Value> = None;
6963    for (i, att) in attestations.iter().enumerate() {
6964        let at: String = match attestations.get(i + 1) {
6965            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
6966                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
6967                _ => return Ok(None),
6968            },
6969            None => now_iso.to_string(),
6970        };
6971        let subject = match verify_wear_attestation(att, keys, &at)? {
6972            Some(s) => s,
6973            None => return Ok(None),
6974        };
6975        let id = subject.get("id").and_then(|v| v.as_str()).map(String::from);
6976        match &robot {
6977            None => robot = id,
6978            Some(r) if id.as_deref() == Some(r.as_str()) => {}
6979            _ => return Ok(None),
6980        }
6981        if let Some(prev) = &prev_proof {
6982            if subject.get("prevProof").and_then(|v| v.as_str()) != Some(prev.as_str()) {
6983                return Ok(None);
6984            }
6985        }
6986        match rv::time_ns(att.get("validFrom")) {
6987            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
6988            _ => return Ok(None),
6989        }
6990        prev_proof = att
6991            .get("proof")
6992            .and_then(|p| p.get("proofValue"))
6993            .and_then(|v| v.as_str())
6994            .map(String::from);
6995        latest = Some(subject);
6996    }
6997    Ok(latest)
6998}
6999
7000/// Derive a physical scope narrowed for the given wear level: each numeric cap is
7001/// scaled by `(1 - wear_level)`, and the allowed zones and shift windows are
7002/// carried through unchanged. The result is a valid attenuation of `scope` (never
7003/// broader on any dimension), so the same attenuation check the rest of Vouch uses
7004/// accepts it. A wear level of 0 returns the caps unchanged.
7005pub fn attenuate_for_wear(scope: &Value, wear_level: f64) -> Result<Value> {
7006    // `contains` is false for NaN, so a NaN wear level is refused here rather
7007    // than turning every cap into NaN (which a NaN-unaware check would ignore).
7008    if !(0.0..=1.0).contains(&wear_level) {
7009        return Err(CoreError::Json(
7010            "wear_level must be between 0.0 and 1.0".into(),
7011        ));
7012    }
7013    let problems = scope_problems(scope);
7014    if !problems.is_empty() {
7015        return Err(CoreError::Json(problems.join("; ")));
7016    }
7017    let factor = 1.0 - wear_level;
7018    let empty = Map::new();
7019    let src = scope.as_object().unwrap_or(&empty);
7020    let mut narrowed = Map::new();
7021    for (key, value) in src {
7022        if WEAR_DERATED_CAPS.contains(&key.as_str()) {
7023            if let Some(n) = value.as_f64() {
7024                narrowed.insert(key.clone(), json!(n * factor));
7025                continue;
7026            }
7027        }
7028        narrowed.insert(key.clone(), value.clone());
7029    }
7030    Ok(Value::Object(narrowed))
7031}
7032
7033// ---------------------------------------------------------------------------
7034// Bystander-consent evidence (Phase 5.20)
7035// ---------------------------------------------------------------------------
7036//
7037// A robot working in a shared or public space captures people incidentally
7038// through its cameras and microphones. This lets the robot record, at capture
7039// time, the basis on which a capture was permitted, bound to the specific capture
7040// and to the robot's identity, and lets a bystander (or their device) sign a
7041// consent token bound to that one capture. Only hashes and a consent basis are
7042// stored, never an image or a bystander's identifying data, so the evidence is
7043// verifiable without retaining anyone's biometrics.
7044//
7045// A bystander consent token is signed by the bystander over the hash of the
7046// capture and the robot's DID, so it verifies only against the capture it was
7047// given for and cannot be replayed to a different recording. A bystander-consent
7048// evidence credential is signed by the robot, binding the capture hash to a
7049// consent basis (an explicit token, posted notice, a legitimate interest, or a
7050// redaction that was applied) and, when the basis is explicit consent, to the
7051// tokens that cover it.
7052//
7053// This is the open layer: the cryptographic binding of a consent basis to a
7054// capture, and its verification, holding only hashes. On-device biometric
7055// detection and redaction, and managed consent-registry orchestration, are out of
7056// scope for the open layer.
7057
7058pub const CONSENT_EVIDENCE_TYPE: &str = "BystanderConsentEvidence";
7059pub const CONSENT_TOKEN_TYPE: &str = "BystanderConsentToken";
7060
7061/// Accepted consent bases: the interoperable set a verifier can rely on.
7062/// Implementers MAY use additional values.
7063pub const CONSENT_BASES: [&str; 4] = [
7064    "explicit-consent",
7065    "posted-notice",
7066    "legitimate-interest",
7067    "redacted",
7068];
7069
7070/// Multibase (base64url) SHA-256 of a raw capture. Only the hash travels in the
7071/// token and the evidence; the capture stays wherever the deployment keeps it.
7072pub fn hash_capture(capture: &[u8]) -> String {
7073    mb64(&Sha256::digest(capture))
7074}
7075
7076/// Parameters for [`build_consent_token`]. The signer is the bystander; the token
7077/// binds their consent to one capture (named by `capture_hash`) by one robot
7078/// (`robot_did`). `valid_until`, when set, bounds the window (the wrapper derives
7079/// it from a `valid_seconds` lifetime added to `granted_at`, keeping the core's
7080/// clock caller-supplied). `scope`, when set, records what the consent covers.
7081#[derive(Debug, Clone)]
7082pub struct BuildConsentToken {
7083    pub bystander_did: String,
7084    pub capture_hash: String,
7085    pub robot_did: String,
7086    pub scope: Option<String>,
7087    pub granted_at: String,
7088    pub valid_until: Option<String>,
7089}
7090
7091/// Build a signed `BystanderConsentToken`: a bystander grants consent for a
7092/// specific capture (named by `capture_hash`) by a specific robot (`robot_did`),
7093/// signed by the bystander. Binding the token to the capture hash means it cannot
7094/// be replayed to a different recording. Signed by the bystander.
7095pub fn build_consent_token(bystander_seed: &[u8], params: &BuildConsentToken) -> Result<Value> {
7096    if params.bystander_did.is_empty()
7097        || params.capture_hash.is_empty()
7098        || params.robot_did.is_empty()
7099    {
7100        return Err(CoreError::Json(
7101            "bystander_did, capture_hash, and robot_did are required".into(),
7102        ));
7103    }
7104
7105    let mut subject = Map::new();
7106    subject.insert("id".into(), json!(params.bystander_did));
7107    subject.insert("captureHash".into(), json!(params.capture_hash));
7108    subject.insert("robotDid".into(), json!(params.robot_did));
7109    if let Some(scope) = &params.scope {
7110        subject.insert("scope".into(), json!(scope));
7111    }
7112
7113    let mut cred = Map::new();
7114    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
7115    cred.insert(
7116        "type".into(),
7117        json!(["VerifiableCredential", CONSENT_TOKEN_TYPE]),
7118    );
7119    cred.insert("issuer".into(), json!(params.bystander_did));
7120    cred.insert("validFrom".into(), json!(params.granted_at));
7121    if let Some(vu) = &params.valid_until {
7122        cred.insert("validUntil".into(), json!(vu));
7123    }
7124    cred.insert("credentialSubject".into(), Value::Object(subject));
7125
7126    let opts = BuildProofOptions::new(
7127        format!("{}#key-1", params.bystander_did),
7128        &params.granted_at,
7129    );
7130    data_integrity::sign(&Value::Object(cred), bystander_seed, &opts)
7131}
7132
7133/// Verify a `BystanderConsentToken`: the bystander's proof bound to the issuer
7134/// (`bystander_keys` is a `{did: key}` source, or the bare key of a did:key
7135/// bystander), that the issuer is the bystander (`credentialSubject.id`), that
7136/// the token is bound to this capture and this robot, and that it is within its
7137/// window at `now_iso` (validFrom required, strict times). Returns the
7138/// credentialSubject on success, `None` if invalid.
7139pub fn verify_consent_token(
7140    token: &Value,
7141    bystander_keys: Keys<'_>,
7142    capture_hash: &str,
7143    robot_did: &str,
7144    now_iso: &str,
7145) -> Result<Option<Value>> {
7146    let v = match bound(
7147        token,
7148        bystander_keys,
7149        CONSENT_TOKEN_TYPE,
7150        now_iso,
7151        Window::FromRequired,
7152    )? {
7153        Some(v) if issuer_is_subject(&v) => v,
7154        _ => return Ok(None),
7155    };
7156    if v.subject.get("captureHash").and_then(|v| v.as_str()) != Some(capture_hash)
7157        || v.subject.get("robotDid").and_then(|v| v.as_str()) != Some(robot_did)
7158    {
7159        return Ok(None);
7160    }
7161    Ok(Some(v.subject))
7162}
7163
7164/// Parameters for [`build_consent_evidence`]. The signer is the robot; the
7165/// evidence records that a capture (named by `capture_hash`) was permitted on
7166/// `basis`, one of [`CONSENT_BASES`]. `consent_tokens`, when the basis is explicit
7167/// consent, are the bystander tokens that cover it, committed by their proof value.
7168/// `redaction_hash`, when set, records that a redacted output was produced.
7169/// `valid_until`, when set, bounds the window.
7170#[derive(Debug, Clone)]
7171pub struct BuildConsentEvidence {
7172    pub robot_did: String,
7173    pub capture_hash: String,
7174    pub basis: String,
7175    pub consent_tokens: Vec<Value>,
7176    pub redaction_hash: Option<String>,
7177    pub valid_from: String,
7178    pub valid_until: Option<String>,
7179}
7180
7181/// A privacy-preserving reference to a token: its proof value. Never embeds a
7182/// bystander's identifying data.
7183fn consent_token_ref(token: &Value) -> Result<String> {
7184    token
7185        .get("proof")
7186        .and_then(|p| p.get("proofValue"))
7187        .and_then(|v| v.as_str())
7188        .map(String::from)
7189        .ok_or_else(|| CoreError::Json("consent token is missing a proof value".into()))
7190}
7191
7192/// Build a signed `BystanderConsentEvidence` credential: the robot records that a
7193/// capture (named by `capture_hash`) was permitted on `basis`, one of
7194/// [`CONSENT_BASES`]. When the basis is explicit consent, the `consent_tokens` are
7195/// the bystander tokens that cover it, and the evidence commits to them by their
7196/// proof value (never embedding a bystander's identifying data). Signed by the
7197/// robot.
7198pub fn build_consent_evidence(robot_seed: &[u8], params: &BuildConsentEvidence) -> Result<Value> {
7199    if params.robot_did.is_empty() || params.capture_hash.is_empty() {
7200        return Err(CoreError::Json(
7201            "robot_did and capture_hash are required".into(),
7202        ));
7203    }
7204    if !CONSENT_BASES.contains(&params.basis.as_str()) {
7205        return Err(CoreError::Json(format!(
7206            "basis must be one of {:?}, got {:?}",
7207            CONSENT_BASES, params.basis
7208        )));
7209    }
7210    if params.basis == "explicit-consent" && params.consent_tokens.is_empty() {
7211        return Err(CoreError::Json(
7212            "explicit-consent basis requires at least one consent token".into(),
7213        ));
7214    }
7215
7216    let mut subject = Map::new();
7217    subject.insert("id".into(), json!(params.robot_did));
7218    subject.insert("captureHash".into(), json!(params.capture_hash));
7219    subject.insert("basis".into(), json!(params.basis));
7220    if !params.consent_tokens.is_empty() {
7221        let mut refs = Vec::with_capacity(params.consent_tokens.len());
7222        for t in &params.consent_tokens {
7223            refs.push(consent_token_ref(t)?);
7224        }
7225        subject.insert("consentTokenRefs".into(), json!(refs));
7226    }
7227    if let Some(rh) = &params.redaction_hash {
7228        subject.insert("redactionHash".into(), json!(rh));
7229    }
7230
7231    let mut cred = Map::new();
7232    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
7233    cred.insert(
7234        "type".into(),
7235        json!(["VerifiableCredential", CONSENT_EVIDENCE_TYPE]),
7236    );
7237    cred.insert("issuer".into(), json!(params.robot_did));
7238    cred.insert("validFrom".into(), json!(params.valid_from));
7239    if let Some(vu) = &params.valid_until {
7240        cred.insert("validUntil".into(), json!(vu));
7241    }
7242    cred.insert("credentialSubject".into(), Value::Object(subject));
7243
7244    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
7245    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
7246}
7247
7248/// One bystander's public key, looked up by bystander DID, for
7249/// [`verify_consent_evidence`].
7250#[derive(Debug, Clone)]
7251pub struct BystanderKey {
7252    pub did: String,
7253    pub public_key: Vec<u8>,
7254}
7255
7256/// Verify a `BystanderConsentEvidence` credential: the robot's proof bound to
7257/// the robot as issuer (which must also be `credentialSubject.id`), the window
7258/// at `now_iso` (validFrom required), and an accepted basis. When `capture` is
7259/// supplied, its hash must reproduce the attested capture hash.
7260///
7261/// An explicit-consent evidence is only as good as its tokens, so for that
7262/// basis `consent_tokens` and `bystander_keys` are required: every committed
7263/// reference must be matched by a token that verifies, is bound to this
7264/// capture and this robot, and is in its window. For other bases, tokens that
7265/// are supplied are checked the same way. Returns the credentialSubject on
7266/// success, `None` if invalid.
7267pub fn verify_consent_evidence(
7268    evidence: &Value,
7269    robot_keys: Keys<'_>,
7270    capture: Option<&[u8]>,
7271    consent_tokens: Option<&[Value]>,
7272    bystander_keys: Option<&[BystanderKey]>,
7273    now_iso: &str,
7274) -> Result<Option<Value>> {
7275    let v = match bound(
7276        evidence,
7277        robot_keys,
7278        CONSENT_EVIDENCE_TYPE,
7279        now_iso,
7280        Window::FromRequired,
7281    )? {
7282        Some(v) if issuer_is_subject(&v) => v,
7283        _ => return Ok(None),
7284    };
7285    let subject = v.subject;
7286    let basis = subject.get("basis").and_then(|v| v.as_str());
7287    match basis {
7288        Some(b) if CONSENT_BASES.contains(&b) => {}
7289        _ => return Ok(None),
7290    }
7291    let capture_hash = match non_empty_str(&subject, "captureHash") {
7292        Some(h) => h.to_string(),
7293        None => return Ok(None),
7294    };
7295    if let Some(c) = capture {
7296        if hash_capture(c) != capture_hash {
7297            return Ok(None);
7298        }
7299    }
7300
7301    let refs: Vec<&str> = match subject.get("consentTokenRefs") {
7302        None => Vec::new(),
7303        Some(Value::Array(a)) if a.iter().all(|r| r.is_string()) => {
7304            a.iter().filter_map(|r| r.as_str()).collect()
7305        }
7306        _ => return Ok(None),
7307    };
7308    let explicit = basis == Some("explicit-consent");
7309    if explicit && refs.is_empty() {
7310        return Ok(None);
7311    }
7312    if explicit && (consent_tokens.is_none() || bystander_keys.is_none()) {
7313        return Ok(None);
7314    }
7315
7316    if let (Some(tokens), Some(keys)) = (consent_tokens, bystander_keys) {
7317        let map = Keys::map_of(keys.iter().map(|k| (k.did.clone(), &k.public_key)));
7318        let mut matched: HashSet<String> = HashSet::new();
7319        for token in tokens {
7320            let tok_ok = !map.is_empty()
7321                && verify_consent_token(token, Keys::Map(&map), &capture_hash, &v.issuer, now_iso)?
7322                    .is_some();
7323            if !tok_ok {
7324                return Ok(None);
7325            }
7326            let r = match consent_token_ref(token) {
7327                Ok(r) if refs.contains(&r.as_str()) => r,
7328                _ => return Ok(None),
7329            };
7330            matched.insert(r);
7331        }
7332        if explicit {
7333            let all: HashSet<String> = refs.iter().map(|r| r.to_string()).collect();
7334            if matched != all {
7335                return Ok(None);
7336            }
7337        }
7338    }
7339
7340    Ok(Some(subject))
7341}
7342
7343#[cfg(test)]
7344mod tests {
7345    use super::*;
7346    use crate::keys::Ed25519KeyPair;
7347    #[allow(unused_imports)]
7348    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
7349    #[allow(unused_imports)]
7350    use crate::robotics_verify::Keys;
7351    use std::fs;
7352
7353    fn load_vector() -> Value {
7354        let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
7355            .expect("interop vector present");
7356        serde_json::from_str(&raw).unwrap()
7357    }
7358
7359    fn software_root_attest(root_seed: &[u8], robot_did: &str, robot_key_mb: &str) -> Vec<u8> {
7360        let kp = Ed25519KeyPair::from_seed_slice(root_seed).unwrap();
7361        let binding = robot_identity_binding(robot_did, robot_key_mb);
7362        kp.sign(&binding).to_vec()
7363    }
7364
7365    // Cross-language interop: Go and TypeScript verify this same Python-minted
7366    // credential; the Rust core must too.
7367    #[test]
7368    fn verifies_python_interop_vector() {
7369        let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
7370            .expect("interop vector present");
7371        let vector: Value = serde_json::from_str(&raw).unwrap();
7372        let jwk_x = vector["robot_public_key_jwk"]["x"].as_str().unwrap();
7373        let robot_pub = URL_SAFE_NO_PAD.decode(jwk_x).unwrap();
7374        let cred = vector["robot_identity_credential"].clone();
7375
7376        let subject = verify_robot_identity(&cred, kd(&cred, &robot_pub), None, TNOW).unwrap();
7377        let subject = subject.expect("the Python interop vector must verify in Rust");
7378        assert_eq!(subject["make"], json!("Acme Robotics"));
7379    }
7380
7381    #[test]
7382    fn mint_verify_roundtrip() {
7383        let robot_seed = [3u8; 32];
7384        let root_seed = [7u8; 32];
7385        let robot_did = "did:web:robot.example.com";
7386        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
7387        let root_kp = Ed25519KeyPair::from_seed(&root_seed);
7388
7389        let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
7390        let params = MintRobotIdentity {
7391            robot_did: robot_did.into(),
7392            make: "Acme".into(),
7393            model: "AR-7".into(),
7394            serial: "SN-1".into(),
7395            owner: Some("did:web:owner.example.com".into()),
7396            root_kind: "TPM".into(),
7397            root_public_multibase: root_kp.public_multikey(),
7398            attestation,
7399            lifecycle: None,
7400            valid_from: "2026-01-01T00:00:00Z".into(),
7401            valid_until: None,
7402        };
7403        let cred = mint_robot_identity(&robot_seed, &params).unwrap();
7404        let subject =
7405            verify_robot_identity(&cred, kd(&cred, &robot_kp.public_key()), None, TNOW).unwrap();
7406        assert!(subject.is_some(), "round-trip identity must verify");
7407    }
7408
7409    // Cross-language interop: this HalosSafetyEvidenceCredential, its black-box
7410    // entries, and the robot public key were produced by the Python reference
7411    // (vouch/robotics/halos.py) from a fixed Ed25519 seed (0x05 x32), a fixed
7412    // black-box key, and a fixed `created` timestamp. The Rust verify must accept
7413    // it, and must reject a tampered entry or a wrong entry count.
7414    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"}}"#;
7415
7416    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"}]"#;
7417
7418    // Robot public key (raw 32-byte Ed25519) as base64url-no-pad.
7419    const PY_HALOS_ROBOT_PUB: &str = "bnoc3Smwt4_ROvTFWY_v9O8qlxZuPKby5Pv8zYBQW_E";
7420
7421    #[test]
7422    fn build_verify_safety_evidence_roundtrip() {
7423        let robot_seed = [5u8; 32];
7424        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
7425
7426        // A black-box chain the robot recorded.
7427        let mut log = BlackBoxLog::new(&[9u8; 32], None).unwrap();
7428        log.append(
7429            "hazard_detected",
7430            &json!({"zone": "cell-3"}),
7431            "2026-01-01T00:00:01Z",
7432        )
7433        .unwrap();
7434        log.append(
7435            "slow_stop",
7436            &json!({"reason": "human"}),
7437            "2026-01-01T00:00:02Z",
7438        )
7439        .unwrap();
7440        let entries: Vec<Value> = log.entries().to_vec();
7441
7442        let params = BuildSafetyEvidence {
7443            halos_stack: json!({"igxSom": "IGX-Orin-64", "halosCore": "1.4.0"}),
7444            window_from: "2026-01-01T00:00:00Z".into(),
7445            window_to: "2026-01-01T00:00:10Z".into(),
7446            blackbox_head: log.head().to_string(),
7447            entry_count: entries.len() as u64,
7448            robot_identity: Some("urn:uuid:robot-identity-1".into()),
7449            valid_seconds: Some(3600),
7450            valid_from: "2026-01-01T00:00:00Z".into(),
7451            created: "2026-01-01T00:00:00Z".into(),
7452            robot_did: None,
7453        };
7454        let cred = build_safety_evidence(&robot_seed, &params).unwrap();
7455
7456        // The issuer is the did:key derived from the seed and the validUntil is
7457        // rendered from the valid_seconds lifetime.
7458        assert_eq!(
7459            cred["issuer"],
7460            json!("did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
7461        );
7462        assert_eq!(cred["validUntil"], json!("2026-01-01T01:00:00Z"));
7463
7464        let (ok, subject) = verify_safety_evidence(
7465            &cred,
7466            kd(&cred, &robot_kp.public_key()),
7467            Some(&entries),
7468            TNOW,
7469        )
7470        .unwrap();
7471        assert!(ok, "a Rust-built evidence credential must verify in Rust");
7472        assert_eq!(subject.unwrap()["entryCount"], json!(2));
7473
7474        // A credential whose issuer is not the subject id is rejected.
7475        let mut forged = cred.clone();
7476        forged["issuer"] = json!("did:key:z6Mkother");
7477        let (ok_forged, _) =
7478            verify_safety_evidence(&forged, kd(&forged, &robot_kp.public_key()), None, TNOW)
7479                .unwrap();
7480        assert!(!ok_forged, "issuer must equal credentialSubject.id");
7481    }
7482
7483    #[test]
7484    fn verifies_python_halos_evidence() {
7485        let credential: Value = serde_json::from_str(PY_HALOS_CREDENTIAL).unwrap();
7486        let entries: Vec<Value> = serde_json::from_str(PY_HALOS_ENTRIES).unwrap();
7487        let robot_pub = URL_SAFE_NO_PAD.decode(PY_HALOS_ROBOT_PUB).unwrap();
7488
7489        // The Python-produced credential and its entries verify in Rust.
7490        let (ok, subject) = verify_safety_evidence(
7491            &credential,
7492            kd(&credential, &robot_pub),
7493            Some(&entries),
7494            TNOW,
7495        )
7496        .unwrap();
7497        assert!(ok, "the Python Halos evidence must verify in Rust");
7498        let subject = subject.expect("subject present on success");
7499        assert_eq!(subject["entryCount"], json!(3));
7500        assert_eq!(
7501            subject["blackboxHead"],
7502            json!("utfv4sSWc6TH-n0HrNqB35Hacy3lYVksU0QYz6gbHol8")
7503        );
7504
7505        // The proof and issuer binding hold even without the entries.
7506        let (ok_no_entries, _) =
7507            verify_safety_evidence(&credential, kd(&credential, &robot_pub), None, TNOW).unwrap();
7508        assert!(
7509            ok_no_entries,
7510            "proof and issuer binding verify without entries"
7511        );
7512
7513        // Tampering one entry breaks the chain, so verification fails.
7514        let mut tampered = entries.clone();
7515        tampered[1]["ciphertext"] = json!("utampered_ciphertext_value_that_does_not_match_hash");
7516        let (ok_tampered, subj_tampered) = verify_safety_evidence(
7517            &credential,
7518            kd(&credential, &robot_pub),
7519            Some(&tampered),
7520            TNOW,
7521        )
7522        .unwrap();
7523        assert!(!ok_tampered, "a tampered entry must be rejected");
7524        assert!(subj_tampered.is_none());
7525
7526        // A wrong entry count (here a truncated log) is rejected against the seal.
7527        let truncated = entries[..2].to_vec();
7528        let (ok_truncated, _) = verify_safety_evidence(
7529            &credential,
7530            kd(&credential, &robot_pub),
7531            Some(&truncated),
7532            TNOW,
7533        )
7534        .unwrap();
7535        assert!(!ok_truncated, "a wrong entry count must be rejected");
7536    }
7537
7538    #[test]
7539    fn forged_hardware_root_fails() {
7540        let robot_seed = [3u8; 32];
7541        let root_seed = [7u8; 32];
7542        let attacker_seed = [9u8; 32];
7543        let robot_did = "did:web:robot.example.com";
7544        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
7545        let root_kp = Ed25519KeyPair::from_seed(&root_seed);
7546        let attacker_kp = Ed25519KeyPair::from_seed(&attacker_seed);
7547
7548        let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
7549        let params = MintRobotIdentity {
7550            robot_did: robot_did.into(),
7551            make: "Acme".into(),
7552            model: "AR-7".into(),
7553            serial: "SN-1".into(),
7554            owner: None,
7555            root_kind: "TPM".into(),
7556            root_public_multibase: root_kp.public_multikey(),
7557            attestation,
7558            lifecycle: None,
7559            valid_from: "2026-01-01T00:00:00Z".into(),
7560            valid_until: None,
7561        };
7562        let mut cred = mint_robot_identity(&robot_seed, &params).unwrap();
7563
7564        // Point the hardware-root key at an attacker's and re-sign the credential
7565        // proof; the attestation over the binding no longer matches.
7566        cred["credentialSubject"]["hardwareRoot"]["publicKeyMultibase"] =
7567            json!(attacker_kp.public_multikey());
7568        let resigned = {
7569            let mut bare = cred.clone();
7570            bare.as_object_mut().unwrap().remove("proof");
7571            let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), "2026-01-01T00:00:00Z");
7572            data_integrity::sign(&bare, &robot_seed, &opts).unwrap()
7573        };
7574        assert!(verify_robot_identity(
7575            &resigned,
7576            kd(&resigned, &robot_kp.public_key()),
7577            None,
7578            TNOW
7579        )
7580        .unwrap()
7581        .is_none());
7582    }
7583
7584    // Cross-language interop: Rust reproduces the exact configHash Python pinned.
7585    #[test]
7586    fn config_hash_matches_interop_vector() {
7587        let vector = load_vector();
7588        let got = config_hash(&vector["config"]);
7589        assert_eq!(got, vector["expected_config_hash"].as_str().unwrap());
7590        assert_eq!(got, "uMh9_H2Lk51-m9SpBhiEa1oqIwwwA7yT27e2QFS0YKUs");
7591    }
7592
7593    #[test]
7594    fn provenance_roundtrip_and_config_tamper() {
7595        let seed = [4u8; 32];
7596        let kp = Ed25519KeyPair::from_seed(&seed);
7597        let config = load_vector()["config"].clone();
7598        let params = BuildProvenance {
7599            issuer_did: "did:web:robot.example.com".into(),
7600            robot_did: "did:web:robot.example.com".into(),
7601            model_name: "openvla-7b".into(),
7602            weights_hash: "uABCDEF".into(),
7603            safety_policy: "did:web:authority.example.com#policy-v3".into(),
7604            config: Some(config.clone()),
7605            version: Some("2026.06".into()),
7606            supersedes: None,
7607            valid_from: "2026-01-01T00:00:00Z".into(),
7608            valid_until: None,
7609        };
7610        let att = build_provenance_attestation(&seed, &params).unwrap();
7611        assert!(verify_provenance_attestation(
7612            &att,
7613            kd(&att, &kp.public_key()),
7614            Some(&config),
7615            TNOW
7616        )
7617        .unwrap()
7618        .is_some());
7619        // A different config than the one signed must be rejected.
7620        let tampered = json!({"temperature": 1.0, "max_torque": 99.0});
7621        assert!(verify_provenance_attestation(
7622            &att,
7623            kd(&att, &kp.public_key()),
7624            Some(&tampered),
7625            TNOW
7626        )
7627        .unwrap()
7628        .is_none());
7629    }
7630
7631    #[test]
7632    fn capability_build_check_attenuate() {
7633        let seed = [6u8; 32];
7634        let kp = Ed25519KeyPair::from_seed(&seed);
7635        let params = BuildPhysicalScope {
7636            issuer_did: "did:web:fleet.example.com".into(),
7637            subject_did: "did:web:robot.example.com".into(),
7638            max_force_n: Some(80.0),
7639            max_speed_mps: Some(2.0),
7640            max_speed_near_humans_mps: Some(0.5),
7641            allowed_zones: Some(vec!["warehouse-a".into(), "dock-3".into()]),
7642            shift_windows: Some(vec![ShiftWindow {
7643                start: "08:00".into(),
7644                end: "18:00".into(),
7645            }]),
7646            valid_from: "2026-01-01T00:00:00Z".into(),
7647            valid_until: None,
7648        };
7649        let cred = build_physical_scope_credential(&seed, &params).unwrap();
7650        assert!(cred["type"]
7651            .as_array()
7652            .unwrap()
7653            .contains(&json!(PHYSICAL_SCOPE_TYPE)));
7654        assert!(data_integrity::verify_proof(&cred, &kp.public_key()).unwrap());
7655
7656        let scope = cred["credentialSubject"]["physicalScope"].clone();
7657        let within = check_physical_action(
7658            &scope,
7659            &PhysicalAction {
7660                force_n: Some(50.0),
7661                speed_mps: Some(1.5),
7662                zone: Some("warehouse-a".into()),
7663                time_hm: Some("09:30".into()),
7664                ..Default::default()
7665            },
7666        );
7667        assert!(within.ok, "within-scope action: {:?}", within.reasons);
7668        assert!(
7669            !check_physical_action(
7670                &scope,
7671                &PhysicalAction {
7672                    force_n: Some(120.0),
7673                    ..Default::default()
7674                }
7675            )
7676            .ok
7677        );
7678        // Near humans the 0.5 m/s cap applies; 1.5 is fine away from them.
7679        assert!(
7680            !check_physical_action(
7681                &scope,
7682                &PhysicalAction {
7683                    speed_mps: Some(1.5),
7684                    near_humans: true,
7685                    ..Default::default()
7686                }
7687            )
7688            .ok
7689        );
7690        assert!(
7691            check_physical_action(
7692                &scope,
7693                &PhysicalAction {
7694                    speed_mps: Some(1.5),
7695                    near_humans: false,
7696                    ..Default::default()
7697                }
7698            )
7699            .ok
7700        );
7701        assert!(
7702            !check_physical_action(
7703                &scope,
7704                &PhysicalAction {
7705                    zone: Some("loading-bay-9".into()),
7706                    ..Default::default()
7707                }
7708            )
7709            .ok
7710        );
7711        assert!(
7712            !check_physical_action(
7713                &scope,
7714                &PhysicalAction {
7715                    time_hm: Some("23:00".into()),
7716                    ..Default::default()
7717                }
7718            )
7719            .ok
7720        );
7721    }
7722
7723    #[test]
7724    fn attenuation_rules() {
7725        let parent = json!({
7726            "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
7727            "allowedZones": ["warehouse-a", "dock-3"],
7728            "shiftWindows": [{"start": "08:00", "end": "18:00"}]
7729        });
7730        let narrower = json!({
7731            "maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3,
7732            "allowedZones": ["warehouse-a"],
7733            "shiftWindows": [{"start": "09:00", "end": "17:00"}]
7734        });
7735        assert!(attenuates(&parent, &narrower));
7736        assert!(!attenuates(
7737            &parent,
7738            &json!({"maxForceN": 100.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"]})
7739        ));
7740        assert!(!attenuates(
7741            &parent,
7742            &json!({"maxForceN": 50.0, "allowedZones": ["warehouse-a"]})
7743        ));
7744        assert!(!attenuates(
7745            &parent,
7746            &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["loading-bay-9"]})
7747        ));
7748        assert!(!attenuates(
7749            &parent,
7750            &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"], "shiftWindows": [{"start": "06:00", "end": "20:00"}]})
7751        ));
7752    }
7753
7754    #[test]
7755    fn handshake_full_flow() {
7756        let a_seed = [11u8; 32];
7757        let b_seed = [12u8; 32];
7758        let a = Ed25519KeyPair::from_seed(&a_seed);
7759        let b = Ed25519KeyPair::from_seed(&b_seed);
7760        let a_did = "did:web:robot-a.example.com";
7761        let b_did = "did:web:robot-b.example.com";
7762        let policy_b = TrustPolicy::new(["robot-a.example.com".to_string()], false);
7763
7764        let hello = build_hello(
7765            &a_seed,
7766            &BuildHello {
7767                from_did: a_did.into(),
7768                proposed_scope: vec!["lift".into(), "carry".into(), "scan".into()],
7769                nonce: "abc123".into(),
7770                peer_did: Some(b_did.into()),
7771                issued_at: "2026-01-01T00:00:00Z".into(),
7772            },
7773        )
7774        .unwrap();
7775
7776        let accept = build_accept(
7777            &b_seed,
7778            &hello,
7779            Keys::One(a_did, &a.public_key()),
7780            &policy_b,
7781            &BuildAccept {
7782                from_did: b_did.into(),
7783                offered_scope: vec!["carry".into(), "scan".into(), "weld".into()],
7784                session_id: "urn:uuid:sess-1".into(),
7785                valid_until: "2026-01-01T00:05:00Z".into(),
7786                created: "2026-01-01T00:00:01Z".into(),
7787            },
7788        )
7789        .unwrap();
7790
7791        let session = verify_accept(
7792            &accept,
7793            Keys::One(b_did, &b.public_key()),
7794            &hello,
7795            Some("abc123"),
7796            None,
7797            "2026-01-01T00:00:01Z",
7798        )
7799        .unwrap()
7800        .expect("accept verifies");
7801        // A bare key cannot vouch for a did:web peer, and a stale or expired
7802        // exchange is refused.
7803        assert!(verify_accept(
7804            &accept,
7805            Keys::Bare(&b.public_key()),
7806            &hello,
7807            None,
7808            None,
7809            "2026-01-01T00:00:01Z"
7810        )
7811        .unwrap()
7812        .is_none());
7813        assert!(verify_accept(
7814            &accept,
7815            Keys::One(b_did, &b.public_key()),
7816            &hello,
7817            None,
7818            None,
7819            "2026-01-01T00:06:00Z"
7820        )
7821        .unwrap()
7822        .is_none());
7823        // An ACCEPT replayed against another HELLO is refused.
7824        let other_hello = build_hello(
7825            &a_seed,
7826            &BuildHello {
7827                from_did: a_did.into(),
7828                proposed_scope: vec!["carry".into()],
7829                nonce: "zzz".into(),
7830                peer_did: Some(b_did.into()),
7831                issued_at: "2026-01-01T00:00:00Z".into(),
7832            },
7833        )
7834        .unwrap();
7835        assert!(verify_accept(
7836            &accept,
7837            Keys::One(b_did, &b.public_key()),
7838            &other_hello,
7839            None,
7840            None,
7841            "2026-01-01T00:00:01Z"
7842        )
7843        .unwrap()
7844        .is_none());
7845        assert_eq!(session.scope, vec!["carry".to_string(), "scan".to_string()]);
7846        assert_eq!(session.initiator, a_did);
7847        assert_eq!(session.responder, b_did);
7848
7849        let confirm = build_confirm(&a_seed, a_did, &session, "2026-01-01T00:00:02Z").unwrap();
7850        assert!(verify_confirm(
7851            &confirm,
7852            Keys::One(a_did, &a.public_key()),
7853            &accept,
7854            "2026-01-01T00:00:02Z"
7855        )
7856        .unwrap());
7857        assert!(!verify_confirm(
7858            &confirm,
7859            Keys::One(a_did, &a.public_key()),
7860            &accept,
7861            "2026-01-01T00:06:00Z"
7862        )
7863        .unwrap());
7864        // A stale HELLO is refused by the responder.
7865        assert!(build_accept(
7866            &b_seed,
7867            &hello,
7868            Keys::One(a_did, &a.public_key()),
7869            &policy_b,
7870            &BuildAccept {
7871                from_did: b_did.into(),
7872                offered_scope: vec!["carry".into()],
7873                session_id: "s2".into(),
7874                valid_until: "2026-01-01T01:00:00Z".into(),
7875                created: "2026-01-01T00:10:00Z".into(),
7876            }
7877        )
7878        .is_err());
7879    }
7880
7881    #[test]
7882    fn handshake_untrusted_tamper_and_nonce() {
7883        let a_seed = [11u8; 32];
7884        let b_seed = [12u8; 32];
7885        let a = Ed25519KeyPair::from_seed(&a_seed);
7886        let b = Ed25519KeyPair::from_seed(&b_seed);
7887        let a_did = "did:web:robot-a.example.com";
7888        let b_did = "did:web:robot-b.example.com";
7889
7890        let hello = build_hello(
7891            &a_seed,
7892            &BuildHello {
7893                from_did: a_did.into(),
7894                proposed_scope: vec!["lift".into()],
7895                nonce: "n1".into(),
7896                peer_did: None,
7897                issued_at: "2026-01-01T00:00:00Z".into(),
7898            },
7899        )
7900        .unwrap();
7901
7902        // Untrusted initiator.
7903        let strict = TrustPolicy::new(["someone-else.example.com".to_string()], false);
7904        assert!(build_accept(
7905            &b_seed,
7906            &hello,
7907            Keys::One(a_did, &a.public_key()),
7908            &strict,
7909            &BuildAccept {
7910                from_did: b_did.into(),
7911                offered_scope: vec!["lift".into()],
7912                session_id: "s".into(),
7913                valid_until: "2026-01-01T00:05:00Z".into(),
7914                created: "2026-01-01T00:00:01Z".into(),
7915            },
7916        )
7917        .is_err());
7918
7919        // Tampered HELLO (scope broadened after signing) fails signature check.
7920        let open = TrustPolicy::new(Vec::<String>::new(), true);
7921        let mut tampered = hello.clone();
7922        tampered["proposedScope"] = json!(["lift", "weld"]);
7923        assert!(build_accept(
7924            &b_seed,
7925            &tampered,
7926            Keys::One(a_did, &a.public_key()),
7927            &open,
7928            &BuildAccept {
7929                from_did: b_did.into(),
7930                offered_scope: vec!["lift".into(), "weld".into()],
7931                session_id: "s".into(),
7932                valid_until: "2026-01-01T00:05:00Z".into(),
7933                created: "2026-01-01T00:00:01Z".into(),
7934            },
7935        )
7936        .is_err());
7937
7938        // Nonce mismatch on a valid ACCEPT.
7939        let accept = build_accept(
7940            &b_seed,
7941            &hello,
7942            Keys::One(a_did, &a.public_key()),
7943            &open,
7944            &BuildAccept {
7945                from_did: b_did.into(),
7946                offered_scope: vec!["lift".into()],
7947                session_id: "s".into(),
7948                valid_until: "2026-01-01T00:05:00Z".into(),
7949                created: "2026-01-01T00:00:01Z".into(),
7950            },
7951        )
7952        .unwrap();
7953        assert!(verify_accept(
7954            &accept,
7955            Keys::One(b_did, &b.public_key()),
7956            &hello,
7957            Some("wrong-nonce"),
7958            Some(&open),
7959            "2026-01-01T00:00:01Z"
7960        )
7961        .unwrap()
7962        .is_none());
7963    }
7964
7965    #[test]
7966    fn did_web_domain_parsing() {
7967        let domain = |did: &str| did_web_domain(did);
7968        assert_eq!(
7969            domain("did:web:example.com").as_deref(),
7970            Some("example.com")
7971        );
7972        // A path is part of the name, so a bare-domain entry never covers it.
7973        assert_eq!(
7974            domain("did:web:robot.example.com:agent").as_deref(),
7975            Some("robot.example.com:agent")
7976        );
7977        assert_eq!(domain("did:web:robot.example.com:"), None);
7978        assert_eq!(domain("did:key:z6Mk"), None);
7979        // A did:webvh DID gives its parsed host, never read as did:web.
7980        let scid = "QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ";
7981        assert_eq!(
7982            domain(&format!("did:webvh:{scid}:Robot.Example.com%3A8443:agents")).as_deref(),
7983            Some("robot.example.com:agents")
7984        );
7985        // One that does not parse has no domain.
7986        assert_eq!(domain("did:webvh:{SCID}:robot.example.com"), None);
7987        assert_eq!(domain(&format!("did:webvh:{scid}:127.0.0.1")), None);
7988        assert_eq!(domain("did:webvhx:robot.example.com"), None);
7989        let policy = TrustPolicy::new(["robot.example.com".to_string()], false);
7990        assert!(policy.is_trusted(&format!("did:webvh:{scid}:robot.example.com")));
7991        assert!(!policy.is_trusted(&format!("did:webvh:{scid}:other.example.com")));
7992        assert!(!policy.is_trusted("did:webvh:{SCID}:robot.example.com"));
7993    }
7994
7995    #[test]
7996    fn blackbox_append_open_and_chain() {
7997        let key = [0x11u8; 32];
7998        let mut log = BlackBoxLog::new(&key, None).unwrap();
7999        let e0 = log
8000            .append(
8001                "motion",
8002                &json!({"speed": 1.5, "joint": "elbow"}),
8003                "2026-01-01T00:00:00Z",
8004            )
8005            .unwrap();
8006        log.append("stop", &json!({"reason": "human"}), "2026-01-01T00:00:01Z")
8007            .unwrap();
8008
8009        // Round-trip decrypt.
8010        let opened = log.open(&e0).unwrap();
8011        assert_eq!(opened["joint"], json!("elbow"));
8012
8013        // Chain verifies, in memory and after a JSON round trip.
8014        assert!(verify_blackbox_chain(log.entries(), None).ok);
8015        let wire: Vec<Value> =
8016            serde_json::from_str(&serde_json::to_string(log.entries()).unwrap()).unwrap();
8017        assert!(verify_blackbox_chain(&wire, None).ok);
8018        assert_eq!(open_entry(&wire[0], &key).unwrap()["joint"], json!("elbow"));
8019
8020        // Tamper detection.
8021        let mut tampered = wire.clone();
8022        tampered[1]["event"] = json!("tampered");
8023        assert!(!verify_blackbox_chain(&tampered, None).ok);
8024
8025        // Wrong key fails decryption; bad key length rejected.
8026        assert!(open_entry(&e0, &[0x22u8; 32]).is_err());
8027        assert!(BlackBoxLog::new(&[0u8; 16], None).is_err());
8028
8029        // Genesis constant matches the multibase of 32 zero bytes.
8030        assert_eq!(genesis_prev_hash(), format!("u{}", "A".repeat(43)));
8031    }
8032
8033    #[test]
8034    fn killswitch_build_verify_and_trust() {
8035        let seed = [13u8; 32];
8036        let kp = Ed25519KeyPair::from_seed(&seed);
8037        let cred = build_killswitch_credential(
8038            &seed,
8039            &BuildKillswitch {
8040                issuer_did: "did:web:safety.example.com".into(),
8041                target: "did:web:robot.example.com".into(),
8042                reason: "human in path".into(),
8043                command: None,
8044                scope: Some(vec!["arm".into(), "drive".into()]),
8045                valid_from: "2026-01-01T00:00:00Z".into(),
8046                valid_until: None,
8047            },
8048        )
8049        .unwrap();
8050
8051        let mut trusted = HashSet::new();
8052        trusted.insert("did:web:safety.example.com".to_string());
8053        let subject =
8054            verify_killswitch_credential(&cred, kd(&cred, &kp.public_key()), Some(&trusted), TNOW)
8055                .unwrap()
8056                .expect("trusted authority verifies");
8057        assert_eq!(subject["command"], json!(EMERGENCY_STOP));
8058
8059        // Untrusted issuer rejected though the signature is valid.
8060        let mut other = HashSet::new();
8061        other.insert("did:web:someone-else.example.com".to_string());
8062        assert!(verify_killswitch_credential(
8063            &cred,
8064            kd(&cred, &kp.public_key()),
8065            Some(&other),
8066            TNOW
8067        )
8068        .unwrap()
8069        .is_none());
8070
8071        // Wrong type rejected.
8072        let mut wrong = cred.clone();
8073        wrong["type"] = json!(["VerifiableCredential"]);
8074        assert!(
8075            verify_killswitch_credential(&wrong, kd(&wrong, &kp.public_key()), None, TNOW)
8076                .unwrap()
8077                .is_none()
8078        );
8079    }
8080
8081    #[test]
8082    fn passport_build_encode_verify() {
8083        let seed = [14u8; 32];
8084        let kp = Ed25519KeyPair::from_seed(&seed);
8085        let did = "did:web:robot.example.com";
8086        let pass = build_passport(
8087            &seed,
8088            &BuildPassport {
8089                issuer_did: did.into(),
8090                robot_did: did.into(),
8091                make: "Acme Robotics".into(),
8092                model: "AR-7".into(),
8093                owner: "did:web:owner.example.com".into(),
8094                authorized_actions: vec!["lift".into(), "carry".into()],
8095                certification: Some("ISO-10218".into()),
8096                status: None,
8097                valid_from: "2026-01-01T00:00:00Z".into(),
8098                valid_until: None,
8099            },
8100        )
8101        .unwrap();
8102
8103        // Direct verify.
8104        let subject = verify_passport(
8105            &pass,
8106            kd(&pass, &kp.public_key()),
8107            None,
8108            "2026-06-01T00:00:00Z",
8109        )
8110        .unwrap()
8111        .expect("passport verifies");
8112        assert_eq!(subject["owner"], json!("did:web:owner.example.com"));
8113        assert_eq!(subject["status"], json!(STATUS_ACTIVE));
8114
8115        // Encode to a URI, decode, and verify the offline-scan path.
8116        let uri = encode_passport(&pass);
8117        assert!(uri.starts_with("vouch-passport:u"));
8118        let decoded = decode_passport(&uri).unwrap();
8119        assert!(verify_passport(
8120            &decoded,
8121            kd(&decoded, &kp.public_key()),
8122            None,
8123            "2026-06-01T00:00:00Z"
8124        )
8125        .unwrap()
8126        .is_some());
8127        assert!(verify_passport_uri(
8128            &uri,
8129            Keys::Resolver(&any_did(&kp.public_key())),
8130            None,
8131            "2026-06-01T00:00:00Z"
8132        )
8133        .unwrap()
8134        .is_some());
8135
8136        // Tamper and wrong type rejected.
8137        let mut tampered = pass.clone();
8138        tampered["credentialSubject"]["owner"] = json!("did:web:attacker.example.com");
8139        assert!(verify_passport(
8140            &tampered,
8141            kd(&tampered, &kp.public_key()),
8142            None,
8143            "2026-06-01T00:00:00Z"
8144        )
8145        .unwrap()
8146        .is_none());
8147
8148        // Malformed URI.
8149        assert!(decode_passport("https://example.com/x").is_err());
8150    }
8151
8152    #[test]
8153    fn passport_expiry_and_suspended() {
8154        let seed = [15u8; 32];
8155        let kp = Ed25519KeyPair::from_seed(&seed);
8156        let did = "did:web:robot.example.com";
8157
8158        // Expiry: valid inside the window, expired past validUntil.
8159        let timed = build_passport(
8160            &seed,
8161            &BuildPassport {
8162                issuer_did: did.into(),
8163                robot_did: did.into(),
8164                make: "Acme".into(),
8165                model: "AR-7".into(),
8166                owner: "did:web:owner.example.com".into(),
8167                authorized_actions: vec!["lift".into()],
8168                certification: None,
8169                status: None,
8170                valid_from: "2026-01-01T00:00:00Z".into(),
8171                valid_until: Some("2026-01-01T00:01:00Z".into()),
8172            },
8173        )
8174        .unwrap();
8175        assert!(verify_passport(
8176            &timed,
8177            kd(&timed, &kp.public_key()),
8178            None,
8179            "2026-01-01T00:00:30Z"
8180        )
8181        .unwrap()
8182        .is_some());
8183        assert!(verify_passport(
8184            &timed,
8185            kd(&timed, &kp.public_key()),
8186            None,
8187            "2026-01-01T00:02:00Z"
8188        )
8189        .unwrap()
8190        .is_none());
8191
8192        // Suspended still verifies but the status is surfaced.
8193        let suspended = build_passport(
8194            &seed,
8195            &BuildPassport {
8196                issuer_did: did.into(),
8197                robot_did: did.into(),
8198                make: "Acme".into(),
8199                model: "AR-7".into(),
8200                owner: "did:web:owner.example.com".into(),
8201                authorized_actions: vec!["lift".into()],
8202                certification: None,
8203                status: Some(STATUS_SUSPENDED.into()),
8204                valid_from: "2026-01-01T00:00:00Z".into(),
8205                valid_until: None,
8206            },
8207        )
8208        .unwrap();
8209        let subject = verify_passport(
8210            &suspended,
8211            kd(&suspended, &kp.public_key()),
8212            None,
8213            "2026-06-01T00:00:00Z",
8214        )
8215        .unwrap()
8216        .expect("a suspended passport still verifies");
8217        assert_eq!(subject["status"], json!(STATUS_SUSPENDED));
8218    }
8219
8220    // Cross-language interop: Rust reproduces the exact motion digest Python
8221    // pinned from the same fixed samples against the same physical scope.
8222    #[test]
8223    fn motion_digest_matches_interop_vector() {
8224        let vector = load_vector();
8225        let scope = vector["physical_scope"].clone();
8226        let mut collector = MotionCollector::new(Some(scope));
8227        collector
8228            .record(&MotionSample {
8229                force_n: Some(12.0),
8230                speed_mps: Some(0.4),
8231                near_humans: false,
8232                zone: Some("cell-3".into()),
8233                time_hm: None,
8234            })
8235            .unwrap();
8236        collector
8237            .record(&MotionSample {
8238                force_n: Some(20.0),
8239                speed_mps: Some(0.2),
8240                near_humans: true,
8241                zone: Some("cell-3".into()),
8242                time_hm: None,
8243            })
8244            .unwrap();
8245        assert_eq!(collector.digest(), vector["expected_motion_digest"]);
8246    }
8247
8248    #[test]
8249    fn heartbeat_build_verify_and_liveness() {
8250        let seed = [21u8; 32];
8251        let kp = Ed25519KeyPair::from_seed(&seed);
8252        let did = "did:web:robot.example.com";
8253        let digest = json!({
8254            "samples": 2, "maxForceN": 20.0, "maxSpeedMps": 0.4,
8255            "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 0,
8256            "withinEnvelope": true
8257        });
8258        let hb = build_robot_heartbeat(
8259            &seed,
8260            &BuildRobotHeartbeat {
8261                robot_did: did.into(),
8262                session_id: "urn:uuid:sess-1".into(),
8263                interval_index: 0,
8264                interval_seconds: 60,
8265                motion_digest: digest,
8266                valid_from: "2026-01-01T00:00:00Z".into(),
8267            },
8268        )
8269        .unwrap();
8270
8271        let subject = verify_robot_heartbeat(&hb, kd(&hb, &kp.public_key()), TNOW)
8272            .unwrap()
8273            .expect("heartbeat verifies");
8274        assert_eq!(subject["sessionId"], json!("urn:uuid:sess-1"));
8275
8276        // Fresh and in-envelope: live. Stale: not live.
8277        assert!(is_live(&hb, "2026-01-01T00:01:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
8278        assert!(!is_live(&hb, "2026-01-01T01:00:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
8279
8280        // Out-of-envelope heartbeat is never live, even when fresh.
8281        let breached = json!({
8282            "samples": 1, "maxForceN": 99.0, "maxSpeedMps": 0.4,
8283            "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 1,
8284            "withinEnvelope": false
8285        });
8286        let hb2 = build_robot_heartbeat(
8287            &seed,
8288            &BuildRobotHeartbeat {
8289                robot_did: did.into(),
8290                session_id: "s".into(),
8291                interval_index: 1,
8292                interval_seconds: 60,
8293                motion_digest: breached,
8294                valid_from: "2026-01-01T00:00:00Z".into(),
8295            },
8296        )
8297        .unwrap();
8298        assert!(!is_live(&hb2, "2026-01-01T00:00:30Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
8299
8300        // Tamper and wrong type rejected.
8301        let mut tampered = hb.clone();
8302        tampered["credentialSubject"]["sessionId"] = json!("urn:uuid:other");
8303        assert!(
8304            verify_robot_heartbeat(&tampered, kd(&tampered, &kp.public_key()), TNOW)
8305                .unwrap()
8306                .is_none()
8307        );
8308    }
8309
8310    // Cross-language interop: Rust reproduces the exact hash-linked ledger and
8311    // the summary Python pinned from the same fixed events and timestamps.
8312    #[test]
8313    fn safety_log_matches_interop_vector() {
8314        let vector = load_vector();
8315        let mut log = SafetyEventLog::new(None);
8316        log.append(
8317            "near_miss",
8318            "low",
8319            Some(&json!({"zone": "cell-3"})),
8320            None,
8321            "2026-01-01T00:00:00Z",
8322        )
8323        .unwrap();
8324        log.append(
8325            "envelope_breach",
8326            "high",
8327            None,
8328            None,
8329            "2026-01-01T00:01:00Z",
8330        )
8331        .unwrap();
8332
8333        assert_eq!(
8334            Value::Array(log.entries().to_vec()),
8335            vector["safety_log_entries"]
8336        );
8337        assert_eq!(
8338            log.head(),
8339            vector["expected_safety_log_head"].as_str().unwrap()
8340        );
8341        assert_eq!(log.summarize(), vector["expected_safety_summary"]);
8342        assert!(verify_safety_log(log.entries(), None).ok);
8343    }
8344
8345    #[test]
8346    fn safety_record_build_verify_and_tamper() {
8347        let seed = [22u8; 32];
8348        let kp = Ed25519KeyPair::from_seed(&seed);
8349        let mut log = SafetyEventLog::new(None);
8350        log.append("near_miss", "low", None, None, "2026-01-01T00:00:00Z")
8351            .unwrap();
8352        let summary = log.summarize();
8353
8354        let record = build_safety_record(
8355            &seed,
8356            &BuildSafetyRecord {
8357                issuer_did: "did:web:owner.example.com".into(),
8358                robot_did: "did:web:robot.example.com".into(),
8359                summary,
8360                period_start: Some("2026-01-01T00:00:00Z".into()),
8361                period_end: Some("2026-01-31T00:00:00Z".into()),
8362                valid_from: "2026-02-01T00:00:00Z".into(),
8363                valid_until: None,
8364            },
8365        )
8366        .unwrap();
8367
8368        let subject = verify_safety_record(
8369            &record,
8370            kd(&record, &kp.public_key()),
8371            SafetyRecordCheck::default(),
8372            "2026-03-01T00:00:00Z",
8373        )
8374        .unwrap()
8375        .expect("safety record verifies");
8376        assert_eq!(subject["totalEvents"], json!(1));
8377        assert_eq!(subject["period"]["start"], json!("2026-01-01T00:00:00Z"));
8378
8379        let mut tampered = record.clone();
8380        tampered["credentialSubject"]["totalEvents"] = json!(99);
8381        assert!(verify_safety_record(
8382            &tampered,
8383            kd(&tampered, &kp.public_key()),
8384            SafetyRecordCheck::default(),
8385            "2026-03-01T00:00:00Z"
8386        )
8387        .unwrap()
8388        .is_none());
8389
8390        // Tamper detection in the ledger itself.
8391        let mut entries = log.entries().to_vec();
8392        entries[0]["severity"] = json!("critical");
8393        assert!(!verify_safety_log(&entries, None).ok);
8394    }
8395
8396    // Cross-language interop: Rust reproduces the exact credentialStatus entry.
8397    #[test]
8398    fn status_entry_matches_interop_vector() {
8399        let vector = load_vector();
8400        let entry = build_status_list_entry(
8401            "https://fleet.example.com/status/1",
8402            42,
8403            STATUS_PURPOSE_REVOCATION,
8404            None,
8405        )
8406        .unwrap();
8407        assert_eq!(entry, vector["expected_credential_status_entry"]);
8408    }
8409
8410    #[test]
8411    fn attach_and_check_credential_status() {
8412        let seed = [23u8; 32];
8413        let kp = Ed25519KeyPair::from_seed(&seed);
8414        let did = "did:web:robot.example.com";
8415
8416        // Mint a passport, then attach a revocation status and re-sign.
8417        let pass = build_passport(
8418            &seed,
8419            &BuildPassport {
8420                issuer_did: did.into(),
8421                robot_did: did.into(),
8422                make: "Acme".into(),
8423                model: "AR-7".into(),
8424                owner: "did:web:owner.example.com".into(),
8425                authorized_actions: vec!["lift".into()],
8426                certification: None,
8427                status: None,
8428                valid_from: "2026-01-01T00:00:00Z".into(),
8429                valid_until: None,
8430            },
8431        )
8432        .unwrap();
8433
8434        let with_status = attach_credential_status(
8435            &pass,
8436            &seed,
8437            &AttachCredentialStatus {
8438                status_list_credential: "https://fleet.example.com/status/1".into(),
8439                status_list_index: 42,
8440                status_purpose: STATUS_PURPOSE_REVOCATION.into(),
8441                entry_id: None,
8442                created: "2026-01-01T00:00:00Z".into(),
8443            },
8444        )
8445        .unwrap();
8446
8447        // The re-signed credential still verifies and now carries the entry.
8448        assert!(data_integrity::verify_proof(&with_status, &kp.public_key()).unwrap());
8449        assert_eq!(
8450            with_status["credentialStatus"]["statusListIndex"],
8451            json!("42")
8452        );
8453
8454        // Build a status list with bit 42 set, then check the entry resolves.
8455        let mut bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
8456        crate::status_list::set_status(&mut bits, 42, true).unwrap();
8457        let encoded = crate::status_list::encode_bitstring(&bits).unwrap();
8458        let status_list = json!({
8459            "id": "https://fleet.example.com/status/1",
8460            "issuer": did,
8461            "type": ["VerifiableCredential", "BitstringStatusListCredential"],
8462            "credentialSubject": {
8463                "type": "BitstringStatusList",
8464                "statusPurpose": "revocation",
8465                "encodedList": encoded,
8466            }
8467        });
8468        assert!(
8469            check_credential_status(&with_status, &status_list, STATUS_PURPOSE_REVOCATION).unwrap()
8470        );
8471
8472        // A credential with no status entry is not revoked.
8473        assert!(!check_credential_status(&pass, &status_list, STATUS_PURPOSE_REVOCATION).unwrap());
8474
8475        // A list with the bit clear reports not-revoked.
8476        let clear_bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
8477        let clear_encoded = crate::status_list::encode_bitstring(&clear_bits).unwrap();
8478        let mut clear_list = status_list.clone();
8479        clear_list["credentialSubject"]["encodedList"] = json!(clear_encoded);
8480        assert!(
8481            !check_credential_status(&with_status, &clear_list, STATUS_PURPOSE_REVOCATION).unwrap()
8482        );
8483
8484        // A list from another issuer, or a list the entry does not name, cannot
8485        // answer: an error, never "not revoked".
8486        let mut foreign = status_list.clone();
8487        foreign["issuer"] = json!("did:web:someone-else.example.com");
8488        assert!(
8489            check_credential_status(&with_status, &foreign, STATUS_PURPOSE_REVOCATION).is_err()
8490        );
8491        let mut other = status_list.clone();
8492        other["id"] = json!("https://fleet.example.com/status/2");
8493        assert!(check_credential_status(&with_status, &other, STATUS_PURPOSE_REVOCATION).is_err());
8494    }
8495
8496    // Cross-language interop: Rust reproduces the exact frame hash Python pinned.
8497    #[test]
8498    fn frame_hash_matches_interop_vector() {
8499        let vector = load_vector();
8500        let sample_frame: Vec<u8> = (0u8..64).collect();
8501        let got = hash_frame(&sample_frame);
8502        assert_eq!(got, vector["expected_frame_hash"].as_str().unwrap());
8503        assert_eq!(got, "u_eq5rPNxA2K9JljNyaKej5x1f8-YEWA6jER80dkVEQg");
8504    }
8505
8506    // Cross-language interop: Rust reproduces the exact hash-linked perception log
8507    // Python pinned from the same fixed frames and timestamps.
8508    #[test]
8509    fn perception_log_matches_interop_vector() {
8510        let vector = load_vector();
8511        let sample_frame: Vec<u8> = (0u8..64).collect();
8512        let mut log = PerceptionLog::new(None);
8513        log.record(
8514            "cam-front",
8515            "camera",
8516            Some(&sample_frame),
8517            None,
8518            "2026-01-01T00:00:00Z",
8519        )
8520        .unwrap();
8521        log.record(
8522            "lidar-top",
8523            "lidar",
8524            None,
8525            Some(&hash_frame(b"scan-0")),
8526            "2026-01-01T00:00:01Z",
8527        )
8528        .unwrap();
8529
8530        assert_eq!(
8531            Value::Array(log.entries().to_vec()),
8532            vector["perception_log_entries"]
8533        );
8534        assert_eq!(
8535            log.head(),
8536            vector["expected_perception_log_head"].as_str().unwrap()
8537        );
8538        assert!(verify_perception_log(log.entries(), None).ok);
8539    }
8540
8541    #[test]
8542    fn perception_record_validation_and_tamper() {
8543        let mut log = PerceptionLog::new(None);
8544        // Unknown modality rejected.
8545        assert!(log
8546            .record("cam", "sonar", Some(b"x"), None, "2026-01-01T00:00:00Z")
8547            .is_err());
8548        // Both frame and frame_hash rejected.
8549        assert!(log
8550            .record(
8551                "cam",
8552                "camera",
8553                Some(b"x"),
8554                Some("uABC"),
8555                "2026-01-01T00:00:00Z"
8556            )
8557            .is_err());
8558        // Neither frame nor frame_hash rejected.
8559        assert!(log
8560            .record("cam", "camera", None, None, "2026-01-01T00:00:00Z")
8561            .is_err());
8562        // Empty sensor id rejected.
8563        assert!(log
8564            .record("", "camera", Some(b"x"), None, "2026-01-01T00:00:00Z")
8565            .is_err());
8566
8567        log.record(
8568            "cam",
8569            "camera",
8570            Some(b"frame-0"),
8571            None,
8572            "2026-01-01T00:00:00Z",
8573        )
8574        .unwrap();
8575        log.record(
8576            "cam",
8577            "camera",
8578            Some(b"frame-1"),
8579            None,
8580            "2026-01-01T00:00:01Z",
8581        )
8582        .unwrap();
8583        assert!(verify_perception_log(log.entries(), None).ok);
8584
8585        // Tamper detection in the chain.
8586        let mut entries = log.entries().to_vec();
8587        entries[0]["frameHash"] = json!("uTAMPERED");
8588        assert!(!verify_perception_log(&entries, None).ok);
8589    }
8590
8591    #[test]
8592    fn perception_attestation_build_verify_and_tamper() {
8593        let seed = [24u8; 32];
8594        let kp = Ed25519KeyPair::from_seed(&seed);
8595        let did = "did:web:robot.example.com";
8596        let frame = b"sensor-frame-bytes";
8597        let frame_hash = hash_frame(frame);
8598
8599        let cred = build_perception_attestation(
8600            &seed,
8601            &BuildPerception {
8602                robot_did: did.into(),
8603                sensor_id: "cam-front".into(),
8604                modality: "camera".into(),
8605                frame_hash: frame_hash.clone(),
8606                captured_at: Some("2026-01-01T00:00:00Z".into()),
8607                log_head: Some("uHEAD".into()),
8608                log_count: None,
8609                valid_from: "2026-01-01T00:00:00Z".into(),
8610                valid_until: None,
8611            },
8612        )
8613        .unwrap();
8614
8615        // Verify the proof and the embedded provenance, and recompute the frame.
8616        let subject =
8617            verify_perception_attestation(&cred, kd(&cred, &kp.public_key()), Some(frame), TNOW)
8618                .unwrap()
8619                .expect("perception attestation verifies");
8620        assert_eq!(subject["sensorId"], json!("cam-front"));
8621        assert_eq!(subject["frameHash"], json!(frame_hash));
8622        assert_eq!(subject["logHead"], json!("uHEAD"));
8623
8624        // Verify without the raw frame still passes (proof only).
8625        assert!(
8626            verify_perception_attestation(&cred, kd(&cred, &kp.public_key()), None, TNOW)
8627                .unwrap()
8628                .is_some()
8629        );
8630
8631        // A different frame than the one attested is rejected.
8632        assert!(verify_perception_attestation(
8633            &cred,
8634            kd(&cred, &kp.public_key()),
8635            Some(b"other-frame"),
8636            TNOW
8637        )
8638        .unwrap()
8639        .is_none());
8640
8641        // Tampered subject fails the proof.
8642        let mut tampered = cred.clone();
8643        tampered["credentialSubject"]["sensorId"] = json!("cam-rear");
8644        assert!(verify_perception_attestation(
8645            &tampered,
8646            kd(&tampered, &kp.public_key()),
8647            None,
8648            TNOW
8649        )
8650        .unwrap()
8651        .is_none());
8652
8653        // Wrong type rejected.
8654        let mut wrong = cred.clone();
8655        wrong["type"] = json!(["VerifiableCredential"]);
8656        assert!(
8657            verify_perception_attestation(&wrong, kd(&wrong, &kp.public_key()), None, TNOW)
8658                .unwrap()
8659                .is_none()
8660        );
8661
8662        // Bad modality and missing frame_hash rejected at build time.
8663        assert!(build_perception_attestation(
8664            &seed,
8665            &BuildPerception {
8666                robot_did: did.into(),
8667                sensor_id: "s".into(),
8668                modality: "sonar".into(),
8669                frame_hash: frame_hash.clone(),
8670                captured_at: None,
8671                log_head: None,
8672                log_count: None,
8673                valid_from: "2026-01-01T00:00:00Z".into(),
8674                valid_until: None,
8675            },
8676        )
8677        .is_err());
8678        assert!(build_perception_attestation(
8679            &seed,
8680            &BuildPerception {
8681                robot_did: did.into(),
8682                sensor_id: "s".into(),
8683                modality: "camera".into(),
8684                frame_hash: String::new(),
8685                captured_at: None,
8686                log_head: None,
8687                log_count: None,
8688                valid_from: "2026-01-01T00:00:00Z".into(),
8689                valid_until: None,
8690            },
8691        )
8692        .is_err());
8693    }
8694
8695    fn jwk_pub(jwk: &Value) -> Vec<u8> {
8696        URL_SAFE_NO_PAD
8697            .decode(jwk["x"].as_str().unwrap())
8698            .expect("base64url JWK x")
8699    }
8700
8701    // Cross-language interop: Go and TypeScript verify this same Python-signed
8702    // delegation lease; the Rust core must too.
8703    #[test]
8704    fn verifies_python_lease_interop_vector() {
8705        let vector = load_vector();
8706        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
8707        let lease = vector["delegation_lease_credential"].clone();
8708
8709        let subject = verify_delegation_lease(
8710            &lease,
8711            kd(&lease, &robot_pub),
8712            "did:web:robot.example.com",
8713            None,
8714            None,
8715            "2026-06-01T00:00:00Z",
8716        )
8717        .unwrap()
8718        .expect("the Python lease interop vector must verify in Rust");
8719        assert_eq!(subject["leaseId"], json!("lease-vector-1"));
8720    }
8721
8722    // Cross-language interop: Rust authorizes the Python-signed quorum with the
8723    // same two approver keys and a threshold of 2.
8724    #[test]
8725    fn verifies_python_quorum_interop_vector() {
8726        let vector = load_vector();
8727        let approvals = vector["quorum_approvals"].as_array().unwrap().clone();
8728        let action_id = vector["quorum_action_id"].as_str().unwrap();
8729        let keys: Vec<ApproverKey> = vector["quorum_approver_keys"]
8730            .as_object()
8731            .unwrap()
8732            .iter()
8733            .map(|(did, jwk)| ApproverKey {
8734                did: did.clone(),
8735                public_key: jwk_pub(jwk),
8736            })
8737            .collect();
8738
8739        let (ok, approvers) = verify_action_authorization(
8740            &approvals,
8741            action_id,
8742            "did:web:robot.example.com",
8743            &keys,
8744            2,
8745            None,
8746            vector["quorum_now"].as_str().unwrap(),
8747        )
8748        .unwrap();
8749        assert!(
8750            ok,
8751            "the Python quorum interop vector must authorize in Rust"
8752        );
8753        assert_eq!(approvers.len(), 2);
8754        assert_eq!(approvers[0], "did:web:approver-1.example.com");
8755        assert_eq!(approvers[1], "did:web:approver-2.example.com");
8756    }
8757
8758    #[test]
8759    fn lease_build_verify_permits_and_expiry() {
8760        let seed = [31u8; 32];
8761        let kp = Ed25519KeyPair::from_seed(&seed);
8762        let did = "did:web:robot.example.com";
8763        let scope = json!({
8764            "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
8765            "allowedZones": ["warehouse-a", "dock-3"]
8766        });
8767        let lease = build_delegation_lease(
8768            &seed,
8769            &BuildDelegationLease {
8770                issuer_did: did.into(),
8771                robot_did: did.into(),
8772                lease_id: "lease-1".into(),
8773                scope: scope.clone(),
8774                parent_lease_id: None,
8775                valid_from: "2026-01-01T00:00:00Z".into(),
8776                valid_until: "2026-01-01T01:00:00Z".into(),
8777            },
8778        )
8779        .unwrap();
8780
8781        // Round-trip verify, in-window.
8782        let subject = verify_delegation_lease(
8783            &lease,
8784            kd(&lease, &kp.public_key()),
8785            "did:web:robot.example.com",
8786            None,
8787            None,
8788            "2026-01-01T00:30:00Z",
8789        )
8790        .unwrap()
8791        .expect("lease verifies in window");
8792        assert_eq!(subject["leaseId"], json!("lease-1"));
8793
8794        // Permits a within-scope action, denies an out-of-scope one.
8795        assert!(lease_permits(
8796            &subject,
8797            &PhysicalAction {
8798                force_n: Some(50.0),
8799                zone: Some("warehouse-a".into()),
8800                ..Default::default()
8801            },
8802            Some(&lease),
8803            kd(&lease, &kp.public_key()),
8804            None,
8805            "2026-01-01T00:30:00Z",
8806        )
8807        .unwrap());
8808        assert!(!lease_permits(
8809            &subject,
8810            &PhysicalAction {
8811                force_n: Some(120.0),
8812                ..Default::default()
8813            },
8814            Some(&lease),
8815            kd(&lease, &kp.public_key()),
8816            None,
8817            "2026-01-01T00:30:00Z",
8818        )
8819        .unwrap());
8820
8821        // Expired window: verify fails and the lease no longer permits.
8822        assert!(verify_delegation_lease(
8823            &lease,
8824            kd(&lease, &kp.public_key()),
8825            "did:web:robot.example.com",
8826            None,
8827            None,
8828            "2026-01-01T02:00:00Z"
8829        )
8830        .unwrap()
8831        .is_none());
8832        assert!(!lease_permits(
8833            &subject,
8834            &PhysicalAction {
8835                force_n: Some(50.0),
8836                ..Default::default()
8837            },
8838            Some(&lease),
8839            kd(&lease, &kp.public_key()),
8840            None,
8841            "2026-01-01T02:00:00Z",
8842        )
8843        .unwrap());
8844
8845        // Tamper and wrong type rejected.
8846        let mut tampered = lease.clone();
8847        tampered["credentialSubject"]["leaseId"] = json!("lease-other");
8848        assert!(verify_delegation_lease(
8849            &tampered,
8850            kd(&tampered, &kp.public_key()),
8851            "did:web:robot.example.com",
8852            None,
8853            None,
8854            "2026-01-01T00:30:00Z"
8855        )
8856        .unwrap()
8857        .is_none());
8858    }
8859
8860    #[test]
8861    fn lease_sub_grant_attenuation() {
8862        let parent_seed = [32u8; 32];
8863        let child_seed = [33u8; 32];
8864        let parent_kp = Ed25519KeyPair::from_seed(&parent_seed);
8865        let child_kp = Ed25519KeyPair::from_seed(&child_seed);
8866        let parent_scope = json!({
8867            "maxForceN": 80.0, "maxSpeedMps": 2.0,
8868            "allowedZones": ["warehouse-a", "dock-3"]
8869        });
8870
8871        // A narrower sub-lease attenuates the parent: accepted.
8872        let narrower = build_delegation_lease(
8873            &child_seed,
8874            &BuildDelegationLease {
8875                issuer_did: "did:web:integrator.example.com".into(),
8876                robot_did: "did:web:robot.example.com".into(),
8877                lease_id: "lease-2".into(),
8878                scope: json!({
8879                    "maxForceN": 50.0, "maxSpeedMps": 1.0,
8880                    "allowedZones": ["warehouse-a"]
8881                }),
8882                parent_lease_id: Some("lease-1".into()),
8883                valid_from: "2026-01-01T00:00:00Z".into(),
8884                valid_until: "2026-01-01T01:00:00Z".into(),
8885            },
8886        )
8887        .unwrap();
8888        assert!(verify_delegation_lease(
8889            &narrower,
8890            kd(&narrower, &child_kp.public_key()),
8891            "did:web:robot.example.com",
8892            Some(&parent_scope),
8893            None,
8894            "2026-01-01T00:30:00Z"
8895        )
8896        .unwrap()
8897        .is_some());
8898
8899        // A widening sub-lease (force above the parent) is rejected against the
8900        // parent scope.
8901        let wider = build_delegation_lease(
8902            &parent_seed,
8903            &BuildDelegationLease {
8904                issuer_did: "did:web:integrator.example.com".into(),
8905                robot_did: "did:web:robot.example.com".into(),
8906                lease_id: "lease-3".into(),
8907                scope: json!({
8908                    "maxForceN": 200.0, "maxSpeedMps": 1.0,
8909                    "allowedZones": ["warehouse-a"]
8910                }),
8911                parent_lease_id: Some("lease-1".into()),
8912                valid_from: "2026-01-01T00:00:00Z".into(),
8913                valid_until: "2026-01-01T01:00:00Z".into(),
8914            },
8915        )
8916        .unwrap();
8917        assert!(verify_delegation_lease(
8918            &wider,
8919            kd(&wider, &parent_kp.public_key()),
8920            "did:web:robot.example.com",
8921            Some(&parent_scope),
8922            None,
8923            "2026-01-01T00:30:00Z"
8924        )
8925        .unwrap()
8926        .is_none());
8927    }
8928
8929    #[test]
8930    fn quorum_threshold_and_distinct_counting() {
8931        let s1 = [41u8; 32];
8932        let s2 = [42u8; 32];
8933        let k1 = Ed25519KeyPair::from_seed(&s1);
8934        let k2 = Ed25519KeyPair::from_seed(&s2);
8935        let a1 = "did:web:approver-1.example.com";
8936        let a2 = "did:web:approver-2.example.com";
8937        let robot = "did:web:robot.example.com";
8938        let action = "action-x";
8939
8940        let build = |seed: &[u8], did: &str, decision: &str| {
8941            build_action_approval(
8942                seed,
8943                &BuildActionApproval {
8944                    approver_did: did.into(),
8945                    action_id: action.into(),
8946                    robot_did: robot.into(),
8947                    decision: decision.into(),
8948                    valid_from: "2026-01-01T00:00:00Z".into(),
8949                    valid_until: None,
8950                },
8951            )
8952            .unwrap()
8953        };
8954
8955        let ap1 = build(&s1, a1, APPROVE);
8956        let ap2 = build(&s2, a2, APPROVE);
8957        let keys = vec![
8958            ApproverKey {
8959                did: a1.into(),
8960                public_key: k1.public_key().to_vec(),
8961            },
8962            ApproverKey {
8963                did: a2.into(),
8964                public_key: k2.public_key().to_vec(),
8965            },
8966        ];
8967
8968        // Two distinct approvers meet a threshold of 2.
8969        let (ok, approvers) = verify_action_authorization(
8970            &[ap1.clone(), ap2],
8971            action,
8972            robot,
8973            &keys,
8974            2,
8975            None,
8976            "2026-01-01T00:01:00Z",
8977        )
8978        .unwrap();
8979        assert!(ok);
8980        assert_eq!(approvers, vec![a1.to_string(), a2.to_string()]);
8981
8982        // Duplicate approvals from one approver count once: threshold 2 not met.
8983        let dup = build(&s1, a1, APPROVE);
8984        let (ok2, approvers2) = verify_action_authorization(
8985            &[ap1.clone(), dup],
8986            action,
8987            robot,
8988            &keys,
8989            2,
8990            None,
8991            "2026-01-01T00:01:00Z",
8992        )
8993        .unwrap();
8994        assert!(!ok2);
8995        assert_eq!(approvers2, vec![a1.to_string()]);
8996
8997        // A single valid approver does not meet a threshold of 2.
8998        let (ok3, _) = verify_action_authorization(
8999            &[ap1],
9000            action,
9001            robot,
9002            &keys,
9003            2,
9004            None,
9005            "2026-01-01T00:01:00Z",
9006        )
9007        .unwrap();
9008        assert!(!ok3);
9009
9010        // A rejection vetoes the action (each approver's latest decision counts).
9011        let rej = build(&s1, a1, REJECT);
9012        let approve2 = build(&s2, a2, APPROVE);
9013        let (ok4, approvers4) = verify_action_authorization(
9014            &[rej, approve2],
9015            action,
9016            robot,
9017            &keys,
9018            2,
9019            None,
9020            "2026-01-01T00:01:00Z",
9021        )
9022        .unwrap();
9023        assert!(!ok4);
9024        assert!(approvers4.is_empty());
9025    }
9026
9027    // Cross-language interop: Rust verifies the Python-signed ownership transfer
9028    // under the owner's key from the vector.
9029    #[test]
9030    fn verifies_python_ownership_transfer_interop_vector() {
9031        let vector = load_vector();
9032        let owner_pub = jwk_pub(&vector["ownership_transfer_owner_key"]);
9033        let cred = vector["ownership_transfer_credential"].clone();
9034
9035        let subject = verify_ownership_transfer(&cred, kd(&cred, &owner_pub), None, TNOW)
9036            .unwrap()
9037            .expect("the Python ownership-transfer interop vector must verify in Rust");
9038        assert_eq!(subject["toOwner"], json!("did:web:owner-b.example.com"));
9039    }
9040
9041    // Cross-language interop: Rust verifies the Python-signed key rotation under
9042    // the robot key from robot_public_key_jwk.
9043    #[test]
9044    fn verifies_python_key_rotation_interop_vector() {
9045        let vector = load_vector();
9046        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
9047        let cred = vector["key_rotation_credential"].clone();
9048
9049        let subject = verify_key_rotation(&cred, Keys::Bare(&robot_pub), None, TNOW)
9050            .unwrap()
9051            .expect("the Python key-rotation interop vector must verify in Rust");
9052        assert_eq!(
9053            subject["newKey"],
9054            json!("z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
9055        );
9056    }
9057
9058    // Cross-language interop: Rust verifies the Python-signed decommission under
9059    // the authority key from the vector.
9060    #[test]
9061    fn verifies_python_decommission_interop_vector() {
9062        let vector = load_vector();
9063        let authority_pub = jwk_pub(&vector["decommission_authority_key"]);
9064        let cred = vector["decommission_credential"].clone();
9065
9066        let subject = verify_decommission(&cred, kd(&cred, &authority_pub), None, None, TNOW)
9067            .unwrap()
9068            .expect("the Python decommission interop vector must verify in Rust");
9069        assert_eq!(subject["reason"], json!("end of service life"));
9070        assert_eq!(subject["finalDisposition"], json!("recycled"));
9071    }
9072
9073    #[test]
9074    fn ownership_transfer_roundtrip_and_issuer_rule() {
9075        let owner_a_seed = [51u8; 32];
9076        let owner_b_seed = [52u8; 32];
9077        let a = Ed25519KeyPair::from_seed(&owner_a_seed);
9078        let b = Ed25519KeyPair::from_seed(&owner_b_seed);
9079        let owner_a = "did:web:owner-a.example.com";
9080        let owner_b = "did:web:owner-b.example.com";
9081        let robot = "did:web:robot.example.com";
9082
9083        let transfer = build_ownership_transfer(
9084            &owner_a_seed,
9085            &BuildOwnershipTransfer {
9086                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000101".into(),
9087                issuer_did: owner_a.into(),
9088                robot_did: robot.into(),
9089                to_owner: owner_b.into(),
9090                from_owner: None,
9091                prev_transfer_id: None,
9092                valid_from: "2026-01-01T00:00:00Z".into(),
9093            },
9094        )
9095        .unwrap();
9096
9097        let subject =
9098            verify_ownership_transfer(&transfer, kd(&transfer, &a.public_key()), None, TNOW)
9099                .unwrap()
9100                .expect("transfer verifies under the current owner key");
9101        assert_eq!(subject["fromOwner"], json!(owner_a));
9102        assert_eq!(subject["toOwner"], json!(owner_b));
9103
9104        // Wrong type rejected.
9105        let mut wrong = transfer.clone();
9106        wrong["type"] = json!(["VerifiableCredential"]);
9107        assert!(
9108            verify_ownership_transfer(&wrong, kd(&wrong, &a.public_key()), None, TNOW)
9109                .unwrap()
9110                .is_none()
9111        );
9112
9113        // The issuer must equal fromOwner: forge a transfer whose issuer is not the
9114        // declared seller and re-sign it. It must be rejected even with a valid
9115        // proof under the signing key.
9116        let forged = build_ownership_transfer(
9117            &owner_b_seed,
9118            &BuildOwnershipTransfer {
9119                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000102".into(),
9120                issuer_did: owner_b.into(),
9121                robot_did: robot.into(),
9122                to_owner: "did:web:owner-c.example.com".into(),
9123                // Claim the robot was sold by owner A while owner B signs.
9124                from_owner: Some(owner_a.into()),
9125                prev_transfer_id: None,
9126                valid_from: "2026-01-01T00:00:00Z".into(),
9127            },
9128        )
9129        .unwrap();
9130        assert!(
9131            verify_ownership_transfer(&forged, kd(&forged, &b.public_key()), None, TNOW)
9132                .unwrap()
9133                .is_none()
9134        );
9135    }
9136
9137    #[test]
9138    fn custody_chain_links_and_rejects() {
9139        let owner_a_seed = [51u8; 32];
9140        let owner_b_seed = [52u8; 32];
9141        let owner_c_seed = [53u8; 32];
9142        let a = Ed25519KeyPair::from_seed(&owner_a_seed);
9143        let b = Ed25519KeyPair::from_seed(&owner_b_seed);
9144        let c = Ed25519KeyPair::from_seed(&owner_c_seed);
9145        let owner_a = "did:web:owner-a.example.com";
9146        let owner_b = "did:web:owner-b.example.com";
9147        let owner_c = "did:web:owner-c.example.com";
9148        let robot = "did:web:robot.example.com";
9149
9150        let t1 = build_ownership_transfer(
9151            &owner_a_seed,
9152            &BuildOwnershipTransfer {
9153                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000103".into(),
9154                issuer_did: owner_a.into(),
9155                robot_did: robot.into(),
9156                to_owner: owner_b.into(),
9157                from_owner: None,
9158                prev_transfer_id: None,
9159                valid_from: "2026-01-01T00:00:00Z".into(),
9160            },
9161        )
9162        .unwrap();
9163        let t2 = build_ownership_transfer(
9164            &owner_b_seed,
9165            &BuildOwnershipTransfer {
9166                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000104".into(),
9167                issuer_did: owner_b.into(),
9168                robot_did: robot.into(),
9169                to_owner: owner_c.into(),
9170                from_owner: None,
9171                prev_transfer_id: Some("urn:uuid:00000000-0000-4000-8000-000000000103".into()),
9172                valid_from: "2026-02-01T00:00:00Z".into(),
9173            },
9174        )
9175        .unwrap();
9176
9177        let keys = vec![
9178            OwnerKey {
9179                did: owner_a.into(),
9180                public_key: a.public_key().to_vec(),
9181            },
9182            OwnerKey {
9183                did: owner_b.into(),
9184                public_key: b.public_key().to_vec(),
9185            },
9186            OwnerKey {
9187                did: owner_c.into(),
9188                public_key: c.public_key().to_vec(),
9189            },
9190        ];
9191
9192        // A clean two-link chain rooted at owner A ends at owner C.
9193        let (ok, current) = verify_custody_chain(
9194            &[t1.clone(), t2.clone()],
9195            &keys,
9196            "did:web:robot.example.com",
9197            Some(owner_a),
9198            "2026-03-01T00:00:00Z",
9199        )
9200        .unwrap();
9201        assert!(ok);
9202        assert_eq!(current.as_deref(), Some(owner_c));
9203
9204        // A wrong declared origin breaks the first link.
9205        let (bad_origin, _) = verify_custody_chain(
9206            &[t1.clone(), t2.clone()],
9207            &keys,
9208            "did:web:robot.example.com",
9209            Some(owner_c),
9210            "2026-03-01T00:00:00Z",
9211        )
9212        .unwrap();
9213        assert!(!bad_origin);
9214
9215        // A gap (link two without link one) breaks the toOwner -> fromOwner join.
9216        let (gap, _) = verify_custody_chain(
9217            std::slice::from_ref(&t2),
9218            &keys,
9219            "did:web:robot.example.com",
9220            Some(owner_a),
9221            "2026-03-01T00:00:00Z",
9222        )
9223        .unwrap();
9224        assert!(!gap);
9225
9226        // A missing key for an issuer fails the chain.
9227        let partial = vec![OwnerKey {
9228            did: owner_a.into(),
9229            public_key: a.public_key().to_vec(),
9230        }];
9231        let (no_key, _) = verify_custody_chain(
9232            &[t1, t2],
9233            &partial,
9234            "did:web:robot.example.com",
9235            Some(owner_a),
9236            "2026-03-01T00:00:00Z",
9237        )
9238        .unwrap();
9239        assert!(!no_key);
9240    }
9241
9242    #[test]
9243    fn key_rotation_roundtrip_and_history() {
9244        let k1_seed = [61u8; 32];
9245        let k2_seed = [62u8; 32];
9246        let k3_seed = [63u8; 32];
9247        let k1 = Ed25519KeyPair::from_seed(&k1_seed);
9248        let k2 = Ed25519KeyPair::from_seed(&k2_seed);
9249        let k3 = Ed25519KeyPair::from_seed(&k3_seed);
9250        let robot = "did:web:robot.example.com";
9251
9252        // Rotate k1 -> k2, signed by k1.
9253        let r1 = build_key_rotation(
9254            &k1_seed,
9255            &BuildKeyRotation {
9256                robot_did: robot.into(),
9257                new_key_multibase: k2.public_multikey(),
9258                reason: Some("scheduled rotation".into()),
9259                valid_from: "2026-01-01T00:00:00Z".into(),
9260            },
9261        )
9262        .unwrap();
9263
9264        let subject = verify_key_rotation(&r1, Keys::Bare(&k1.public_key()), None, TNOW)
9265            .unwrap()
9266            .expect("rotation verifies under the old key");
9267        assert_eq!(subject["previousKey"], json!(k1.public_multikey()));
9268        assert_eq!(subject["newKey"], json!(k2.public_multikey()));
9269
9270        // The new key cannot verify a rotation that the old key signed.
9271        assert!(
9272            verify_key_rotation(&r1, Keys::Bare(&k2.public_key()), None, TNOW)
9273                .unwrap()
9274                .is_none()
9275        );
9276
9277        // Wrong type rejected.
9278        let mut wrong = r1.clone();
9279        wrong["type"] = json!(["VerifiableCredential"]);
9280        assert!(
9281            verify_key_rotation(&wrong, Keys::Bare(&k1.public_key()), None, TNOW)
9282                .unwrap()
9283                .is_none()
9284        );
9285
9286        // Rotate k2 -> k3, signed by k2, forming a history.
9287        let r2 = build_key_rotation(
9288            &k2_seed,
9289            &BuildKeyRotation {
9290                robot_did: robot.into(),
9291                new_key_multibase: k3.public_multikey(),
9292                reason: None,
9293                valid_from: "2026-02-01T00:00:00Z".into(),
9294            },
9295        )
9296        .unwrap();
9297
9298        let (ok, current) = verify_key_history(
9299            &[r1.clone(), r2.clone()],
9300            &k1.public_multikey(),
9301            None,
9302            "2026-03-01T00:00:00Z",
9303        )
9304        .unwrap();
9305        assert!(ok);
9306        assert_eq!(current.as_deref(), Some(k3.public_multikey().as_str()));
9307
9308        // A wrong origin key breaks the first previousKey match.
9309        let (bad_origin, _) = verify_key_history(
9310            &[r1, r2],
9311            &k3.public_multikey(),
9312            None,
9313            "2026-03-01T00:00:00Z",
9314        )
9315        .unwrap();
9316        assert!(!bad_origin);
9317    }
9318
9319    #[test]
9320    fn decommission_roundtrip_and_trusted_authority() {
9321        let seed = [71u8; 32];
9322        let kp = Ed25519KeyPair::from_seed(&seed);
9323        let authority = "did:web:authority.example.com";
9324        let robot = "did:web:robot.example.com";
9325
9326        let cred = build_decommission(
9327            &seed,
9328            &BuildDecommission {
9329                issuer_did: authority.into(),
9330                robot_did: robot.into(),
9331                reason: "end of service life".into(),
9332                final_disposition: Some("recycled".into()),
9333                valid_from: "2026-01-01T00:00:00Z".into(),
9334                valid_until: None,
9335            },
9336        )
9337        .unwrap();
9338
9339        let mut trusted = HashSet::new();
9340        trusted.insert(authority.to_string());
9341        let subject = verify_decommission(
9342            &cred,
9343            kd(&cred, &kp.public_key()),
9344            Some(&trusted),
9345            None,
9346            TNOW,
9347        )
9348        .unwrap()
9349        .expect("a trusted authority decommission verifies");
9350        assert_eq!(subject["decommissionedBy"], json!(authority));
9351
9352        // An untrusted issuer is rejected even with a valid proof.
9353        let mut other = HashSet::new();
9354        other.insert("did:web:someone-else.example.com".to_string());
9355        assert!(
9356            verify_decommission(&cred, kd(&cred, &kp.public_key()), Some(&other), None, TNOW)
9357                .unwrap()
9358                .is_none()
9359        );
9360
9361        // No trusted-authority set: a valid proof verifies.
9362        assert!(
9363            verify_decommission(&cred, kd(&cred, &kp.public_key()), None, None, TNOW)
9364                .unwrap()
9365                .is_some()
9366        );
9367
9368        // Wrong type rejected.
9369        let mut wrong = cred.clone();
9370        wrong["type"] = json!(["VerifiableCredential"]);
9371        assert!(
9372            verify_decommission(&wrong, kd(&wrong, &kp.public_key()), None, None, TNOW)
9373                .unwrap()
9374                .is_none()
9375        );
9376
9377        // reason is required at build time.
9378        assert!(build_decommission(
9379            &seed,
9380            &BuildDecommission {
9381                issuer_did: authority.into(),
9382                robot_did: robot.into(),
9383                reason: String::new(),
9384                final_disposition: None,
9385                valid_from: "2026-01-01T00:00:00Z".into(),
9386                valid_until: None,
9387            },
9388        )
9389        .is_err());
9390    }
9391
9392    // Cross-language interop: Rust reproduces the exact conformance report and
9393    // digest Python pinned, from the same credential set and profile.
9394    #[test]
9395    fn conformance_matches_interop_vector() {
9396        let vector = load_vector();
9397        let credentials: Vec<Value> = vector["conformance_credentials"]
9398            .as_array()
9399            .expect("conformance_credentials present")
9400            .clone();
9401        let profile_id = vector["conformance_profile_id"].as_str().unwrap();
9402
9403        let report = check_conformance(&credentials, profile_id).unwrap();
9404        assert_eq!(report, vector["expected_conformance_report"]);
9405
9406        let digest = report_digest(&report);
9407        assert_eq!(
9408            digest,
9409            vector["expected_conformance_report_digest"]
9410                .as_str()
9411                .unwrap()
9412        );
9413    }
9414
9415    // Presence alone is not evidence. A heartbeat that reports an envelope
9416    // breach must not satisfy the continuous-monitoring requirement just by
9417    // carrying a motionDigest.
9418    #[test]
9419    fn a_breaching_heartbeat_does_not_evidence_monitoring() {
9420        let breaching = json!({
9421            "type": ["VerifiableCredential", "RobotHeartbeatCredential"],
9422            "credentialSubject": {
9423                "motionDigest": {"withinEnvelope": false, "samples": 120}
9424            }
9425        });
9426        let report = check_conformance(std::slice::from_ref(&breaching), "iso-ts-15066").unwrap();
9427        let monitoring = report["requirements"]
9428            .as_array()
9429            .unwrap()
9430            .iter()
9431            .find(|r| r["id"] == json!("iso15066-monitoring"))
9432            .expect("monitoring requirement present");
9433        assert_eq!(monitoring["satisfied"], json!(false));
9434
9435        // The same heartbeat reporting no breach does satisfy it.
9436        let mut clean = breaching;
9437        clean["credentialSubject"]["motionDigest"]["withinEnvelope"] = json!(true);
9438        let report = check_conformance(&[clean], "iso-ts-15066").unwrap();
9439        let monitoring = report["requirements"]
9440            .as_array()
9441            .unwrap()
9442            .iter()
9443            .find(|r| r["id"] == json!("iso15066-monitoring"))
9444            .unwrap();
9445        assert_eq!(monitoring["satisfied"], json!(true));
9446    }
9447
9448    // Every requirement declares where its clause number came from, and the
9449    // report totals them, so CONFORMS never reads as more authoritative about
9450    // the regulation than its sources are.
9451    #[test]
9452    fn conformance_report_carries_citation_provenance() {
9453        for profile_id in [
9454            "iso-10218",
9455            "iso-ts-15066",
9456            "eu-machinery-2023-1230",
9457            "eu-ai-act-high-risk",
9458            "ul-3300",
9459        ] {
9460            let report = check_conformance(&[], profile_id).unwrap();
9461            let citations = report["citations"].as_object().unwrap();
9462            assert_eq!(citations.len(), CITATION_STATUSES.len());
9463            let counted: i64 = citations.values().map(|v| v.as_i64().unwrap()).sum();
9464            assert_eq!(counted, report["totalCount"].as_i64().unwrap());
9465            for result in report["requirements"].as_array().unwrap() {
9466                let citation = result["citation"].as_str().unwrap();
9467                assert!(CITATION_STATUSES.contains(&citation));
9468            }
9469        }
9470
9471        // UL 3300 is paywalled with no clause numbering available, so none of
9472        // its "clauses" are citable.
9473        let ul = check_conformance(&[], "ul-3300").unwrap();
9474        assert_eq!(ul["citations"][CITATION_DESCRIPTIVE], ul["totalCount"]);
9475        assert_eq!(ul["citations"][CITATION_VERIFIED_PRIMARY], json!(0));
9476    }
9477
9478    #[test]
9479    fn conformance_unknown_profile_and_missing_field() {
9480        assert!(check_conformance(&[], "no-such-profile").is_err());
9481
9482        // An empty credential set satisfies nothing.
9483        let empty = check_conformance(&[], "eu-ai-act-high-risk").unwrap();
9484        assert_eq!(empty["conforms"], json!(false));
9485        assert_eq!(empty["satisfiedCount"], json!(0));
9486        assert_eq!(empty["totalCount"], json!(4));
9487
9488        // A safety record with no logHead does not satisfy the record-keeping
9489        // requirement (a missing field counts as unsatisfied).
9490        let creds = vec![json!({
9491            "type": ["VerifiableCredential", "RobotSafetyRecordCredential"],
9492            "credentialSubject": { "id": "did:web:robot.example.com", "totalEvents": 2 }
9493        })];
9494        let report = check_conformance(&creds, "eu-ai-act-high-risk").unwrap();
9495        let record_keeping = report["requirements"]
9496            .as_array()
9497            .unwrap()
9498            .iter()
9499            .find(|r| r["id"] == json!("eu-aia-record-keeping"))
9500            .unwrap();
9501        assert_eq!(record_keeping["satisfied"], json!(false));
9502
9503        // An empty allowedZones array is also unsatisfied.
9504        let zone_creds = vec![json!({
9505            "type": ["VerifiableCredential", "PhysicalCapabilityScope"],
9506            "credentialSubject": {
9507                "id": "did:web:robot.example.com",
9508                "physicalScope": { "maxSpeedMps": 1.5, "allowedZones": [] }
9509            }
9510        })];
9511        let ul = check_conformance(&zone_creds, "ul-3300").unwrap();
9512        let limits = ul["requirements"]
9513            .as_array()
9514            .unwrap()
9515            .iter()
9516            .find(|r| r["id"] == json!("ul3300-operating-limits"))
9517            .unwrap();
9518        assert_eq!(limits["satisfied"], json!(false));
9519    }
9520
9521    #[test]
9522    fn conformance_attestation_roundtrip_and_rejections() {
9523        let seed = [77u8; 32];
9524        let kp = Ed25519KeyPair::from_seed(&seed);
9525        let vector = load_vector();
9526        let credentials: Vec<Value> = vector["conformance_credentials"]
9527            .as_array()
9528            .unwrap()
9529            .clone();
9530        let report = check_conformance(&credentials, "eu-ai-act-high-risk").unwrap();
9531
9532        let att = build_conformance_attestation(
9533            &seed,
9534            &BuildConformanceAttestation {
9535                issuer_did: "did:web:authority.example.com".into(),
9536                robot_did: "did:web:robot.example.com".into(),
9537                report: report.clone(),
9538                valid_from: "2026-01-01T00:00:00Z".into(),
9539                valid_until: Some("2027-01-01T00:00:00Z".into()),
9540            },
9541        )
9542        .unwrap();
9543
9544        // Round-trip: a well-formed attestation verifies and surfaces the subject.
9545        let subject =
9546            verify_conformance_attestation(&att, kd(&att, &kp.public_key()), None, None, TNOW)
9547                .unwrap()
9548                .expect("a valid conformance attestation verifies");
9549        assert_eq!(subject["profileId"], json!("eu-ai-act-high-risk"));
9550        assert_eq!(subject["conforms"], json!(true));
9551        assert_eq!(
9552            subject["reportDigest"],
9553            vector["expected_conformance_report_digest"]
9554        );
9555
9556        // Wrong key is rejected.
9557        let wrong_kp = Ed25519KeyPair::from_seed(&[88u8; 32]);
9558        assert!(verify_conformance_attestation(
9559            &att,
9560            kd(&att, &wrong_kp.public_key()),
9561            None,
9562            None,
9563            TNOW
9564        )
9565        .unwrap()
9566        .is_none());
9567
9568        // A tampered embedded report no longer matches the bound digest.
9569        let mut tampered = att.clone();
9570        tampered["credentialSubject"]["report"]["conforms"] = json!(false);
9571        assert!(verify_conformance_attestation(
9572            &tampered,
9573            kd(&tampered, &kp.public_key()),
9574            None,
9575            None,
9576            TNOW
9577        )
9578        .unwrap()
9579        .is_none());
9580
9581        // Wrong type is rejected.
9582        let mut wrong_type = att.clone();
9583        wrong_type["type"] = json!(["VerifiableCredential"]);
9584        assert!(verify_conformance_attestation(
9585            &wrong_type,
9586            kd(&wrong_type, &kp.public_key()),
9587            None,
9588            None,
9589            TNOW
9590        )
9591        .unwrap()
9592        .is_none());
9593
9594        // robot_did is required at build time.
9595        assert!(build_conformance_attestation(
9596            &seed,
9597            &BuildConformanceAttestation {
9598                issuer_did: "did:web:authority.example.com".into(),
9599                robot_did: String::new(),
9600                report,
9601                valid_from: "2026-01-01T00:00:00Z".into(),
9602                valid_until: None,
9603            },
9604        )
9605        .is_err());
9606    }
9607
9608    // -- post-quantum robot credentials ------------------------------------
9609
9610    fn classical_robot_credential(issuer: &str, seed: &[u8]) -> Value {
9611        let cred = json!({
9612            "@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
9613            "type": ["VerifiableCredential", ROBOT_IDENTITY_TYPE],
9614            "issuer": issuer,
9615            "validFrom": "2026-01-01T00:00:00Z",
9616            "credentialSubject": {
9617                "id": issuer,
9618                "make": "Acme Robotics",
9619                "model": "AR-7",
9620                "serial": "SN-000123"
9621            }
9622        });
9623        let opts = BuildProofOptions::new(format!("{issuer}#key-1"), "2026-01-01T00:00:00Z");
9624        data_integrity::sign(&cred, seed, &opts).unwrap()
9625    }
9626
9627    // Cross-language interop: Rust verifies the Python-signed hybrid PQ robot
9628    // identity under the Ed25519 key and the ML-DSA-44 multikey from the vector.
9629    #[test]
9630    fn verifies_python_pq_robot_identity_interop_vector() {
9631        let vector = load_vector();
9632        let ed_pub = jwk_pub(&vector["robot_public_key_jwk"]);
9633        let ml_multikey = vector["robot_mldsa44_public_multikey"].as_str().unwrap();
9634        let cred = vector["pq_robot_identity_credential"].clone();
9635
9636        // (b) the credential is detected as post-quantum.
9637        assert!(is_pq(&cred));
9638
9639        // (a) dual verify auto-detected from the proof, with the ML-DSA multikey.
9640        let ok = verify_robot_credential(
9641            &cred,
9642            kd(&cred, &ed_pub),
9643            Some(ml_multikey.as_bytes()),
9644            None,
9645            TNOW,
9646        )
9647        .expect("the Python hybrid PQ interop vector must verify in Rust");
9648        assert!(ok);
9649
9650        // verify_pq accepts the multikey string form directly.
9651        let resolved = mldsa44_public_from_multikey(ml_multikey).unwrap();
9652        assert!(verify_pq(&cred, &ed_pub, &resolved).unwrap());
9653    }
9654
9655    #[test]
9656    fn pq_sign_verify_roundtrip_and_rejects() {
9657        let issuer = "did:web:robot.example.com";
9658        let seed = [21u8; 32];
9659        let kp = Ed25519KeyPair::from_seed(&seed);
9660        let ml = MlDsa44KeyPair::generate().unwrap();
9661
9662        let classical = classical_robot_credential(issuer, &seed);
9663        assert!(!is_pq(&classical));
9664
9665        // Sign post-quantum; any prior proof is replaced by a proof set holding
9666        // one classical and one ML-DSA-44 proof.
9667        let signed = sign_pq(&classical, &seed, &ml, "2026-02-01T00:00:00Z").unwrap();
9668        assert!(is_pq(&signed));
9669        let proofs = signed["proof"].as_array().expect("proof set");
9670        assert_eq!(proofs.len(), 2);
9671        assert_eq!(
9672            proofs[0]["cryptosuite"],
9673            json!(hybrid::EDDSA_CRYPTOSUITE_ID)
9674        );
9675        assert_eq!(
9676            proofs[1]["cryptosuite"],
9677            json!(hybrid::MLDSA44_CRYPTOSUITE_ID)
9678        );
9679        // Each proof carries the Multibase encoding its cryptosuite specifies.
9680        assert!(proofs[0]["proofValue"].as_str().unwrap().starts_with('z'));
9681        assert!(proofs[1]["proofValue"].as_str().unwrap().starts_with('u'));
9682
9683        // Round-trip: both signatures validate under the correct keys.
9684        assert!(verify_pq(&signed, &kp.public_key(), &ml.public_key()).unwrap());
9685        assert!(verify_robot_credential(
9686            &signed,
9687            kd(&signed, &kp.public_key()),
9688            Some(&ml.public_key()),
9689            None,
9690            TNOW
9691        )
9692        .unwrap());
9693
9694        // The multikey string form is accepted too (as UTF-8 bytes).
9695        let ml_mk = multikey::encode_mldsa44_public(&ml.public_key()).unwrap();
9696        assert!(verify_robot_credential(
9697            &signed,
9698            kd(&signed, &kp.public_key()),
9699            Some(ml_mk.as_bytes()),
9700            None,
9701            TNOW
9702        )
9703        .unwrap());
9704
9705        // Tampering the body breaks verification.
9706        let mut tampered = signed.clone();
9707        tampered["credentialSubject"]["model"] = json!("AR-9");
9708        assert!(!verify_pq(&tampered, &kp.public_key(), &ml.public_key()).unwrap());
9709
9710        // Wrong Ed25519 key is rejected.
9711        let other_ed = Ed25519KeyPair::from_seed(&[99u8; 32]);
9712        assert!(!verify_pq(&signed, &other_ed.public_key(), &ml.public_key()).unwrap());
9713
9714        // Wrong ML-DSA-44 key is rejected.
9715        let other_ml = MlDsa44KeyPair::generate().unwrap();
9716        assert!(!verify_pq(&signed, &kp.public_key(), &other_ml.public_key()).unwrap());
9717
9718        // A hybrid credential without the ML-DSA key returns false, not true.
9719        assert!(
9720            !verify_robot_credential(&signed, kd(&signed, &kp.public_key()), None, None, TNOW)
9721                .unwrap()
9722        );
9723
9724        // Downgrade by extraction: an attacker strips the proof set to the lone
9725        // standalone classical proof. A verifier that supplies the ML-DSA key
9726        // (so requires post-quantum) must reject it, not accept it as classical.
9727        let proofs = signed["proof"].as_array().unwrap();
9728        let classical_proof = proofs
9729            .iter()
9730            .find(|p| p["cryptosuite"] == json!(hybrid::EDDSA_CRYPTOSUITE_ID))
9731            .unwrap()
9732            .clone();
9733        let mut stripped = signed.clone();
9734        stripped["proof"] = classical_proof;
9735        assert!(!is_pq(&stripped));
9736        assert!(
9737            !verify_robot_credential(
9738                &stripped,
9739                kd(&stripped, &kp.public_key()),
9740                Some(&ml.public_key()),
9741                None,
9742                TNOW
9743            )
9744            .unwrap(),
9745            "a stripped proof set must not verify when the caller requires post-quantum"
9746        );
9747        // The extracted classical proof is genuine, so a caller that only does
9748        // classical verification (no ML-DSA key) still accepts it.
9749        assert!(verify_robot_credential(
9750            &stripped,
9751            kd(&stripped, &kp.public_key()),
9752            None,
9753            None,
9754            TNOW
9755        )
9756        .unwrap());
9757    }
9758
9759    #[test]
9760    fn classical_credential_passes_dual_verify_without_pq_key() {
9761        let issuer = "did:web:robot.example.com";
9762        let seed = [22u8; 32];
9763        let kp = Ed25519KeyPair::from_seed(&seed);
9764        let classical = classical_robot_credential(issuer, &seed);
9765
9766        assert!(!is_pq(&classical));
9767        // A classical credential verifies through the dual path with no ML-DSA key.
9768        assert!(verify_robot_credential(
9769            &classical,
9770            kd(&classical, &kp.public_key()),
9771            None,
9772            None,
9773            TNOW
9774        )
9775        .unwrap());
9776
9777        // A wrong key still fails.
9778        let other = Ed25519KeyPair::from_seed(&[7u8; 32]);
9779        assert!(!verify_robot_credential(
9780            &classical,
9781            kd(&classical, &other.public_key()),
9782            None,
9783            None,
9784            TNOW
9785        )
9786        .unwrap());
9787    }
9788
9789    #[test]
9790    fn migrate_to_pq_resigns_classical_credential() {
9791        let issuer = "did:web:robot.example.com";
9792        let seed = [23u8; 32];
9793        let kp = Ed25519KeyPair::from_seed(&seed);
9794        let ml = MlDsa44KeyPair::generate().unwrap();
9795
9796        let classical = classical_robot_credential(issuer, &seed);
9797        assert!(verify_robot_credential(
9798            &classical,
9799            kd(&classical, &kp.public_key()),
9800            None,
9801            None,
9802            TNOW
9803        )
9804        .unwrap());
9805
9806        let migrated = migrate_to_pq(&classical, &seed, &ml, "2026-03-01T00:00:00Z").unwrap();
9807        assert!(is_pq(&migrated));
9808        // The body is preserved across migration.
9809        assert_eq!(
9810            migrated["credentialSubject"],
9811            classical["credentialSubject"]
9812        );
9813        assert!(verify_robot_credential(
9814            &migrated,
9815            kd(&migrated, &kp.public_key()),
9816            Some(&ml.public_key()),
9817            None,
9818            TNOW
9819        )
9820        .unwrap());
9821    }
9822
9823    // Cross-language interop: Rust verifies the Python-signed embodiment continuity
9824    // chain under the one agent key from the vector, ending on body-b, with no fork.
9825    #[test]
9826    fn verifies_python_embodiment_interop_vector() {
9827        let vector = load_vector();
9828        let agent_pub = jwk_pub(&vector["embodiment_agent_key"]);
9829        let chain: Vec<Value> = vector["embodiment_chain"]
9830            .as_array()
9831            .expect("embodiment_chain array")
9832            .clone();
9833
9834        let (ok, current) = verify_continuity_chain(
9835            &chain,
9836            Keys::Resolver(&any_did(&agent_pub)),
9837            None,
9838            None,
9839            "2026-06-01T00:00:00Z",
9840        )
9841        .unwrap();
9842        assert!(ok, "the Python embodiment chain must verify in Rust");
9843        assert_eq!(
9844            current.as_deref(),
9845            Some("did:web:body-b.example.com"),
9846            "the chain ends on body-b"
9847        );
9848
9849        let (no_fork, conflict) = check_no_fork(&chain).unwrap();
9850        assert!(no_fork, "the Python embodiment chain has no fork");
9851        assert!(conflict.is_none());
9852    }
9853
9854    #[test]
9855    fn embodiment_roundtrip_and_issuer_rule() {
9856        let agent_seed = [61u8; 32];
9857        let other_seed = [62u8; 32];
9858        let agent = Ed25519KeyPair::from_seed(&agent_seed);
9859        let other = Ed25519KeyPair::from_seed(&other_seed);
9860        let agent_did = "did:web:agent.example.com";
9861        let body_a = "did:web:body-a.example.com";
9862
9863        let cred = build_embodiment(
9864            &agent_seed,
9865            &BuildEmbodiment {
9866                agent_did: agent_did.into(),
9867                body_did: body_a.into(),
9868                body_hardware_root: "uROOTA".into(),
9869                from_body: None,
9870                embodied_at: "2026-01-01T00:00:00Z".into(),
9871                valid_until: None,
9872            },
9873        )
9874        .unwrap();
9875
9876        let subject = verify_embodiment(&cred, kd(&cred, &agent.public_key()), None, TNOW)
9877            .unwrap()
9878            .expect("embodiment verifies under the agent key");
9879        assert_eq!(subject["body"], json!(body_a));
9880        assert_eq!(subject["bodyHardwareRoot"], json!("uROOTA"));
9881
9882        // The issuer must equal the subject id: forge a credential issued by an
9883        // impostor over an unchanged subject (still the agent) and re-sign it. It
9884        // must be rejected even with a valid proof under the signing key, because a
9885        // mind only authorizes its own embodiment.
9886        let forged = {
9887            let mut bare = cred.clone();
9888            bare.as_object_mut().unwrap().remove("proof");
9889            bare["issuer"] = json!("did:web:impostor.example.com");
9890            let opts = BuildProofOptions::new(
9891                "did:web:impostor.example.com#key-1".to_string(),
9892                "2026-01-01T00:00:00Z",
9893            );
9894            data_integrity::sign(&bare, &other_seed, &opts).unwrap()
9895        };
9896        assert!(
9897            verify_embodiment(&forged, kd(&forged, &other.public_key()), None, TNOW)
9898                .unwrap()
9899                .is_none()
9900        );
9901    }
9902
9903    #[test]
9904    fn continuity_chain_links_and_rejects() {
9905        let agent_seed = [61u8; 32];
9906        let stranger_seed = [63u8; 32];
9907        let agent = Ed25519KeyPair::from_seed(&agent_seed);
9908        let stranger = Ed25519KeyPair::from_seed(&stranger_seed);
9909        let agent_did = "did:web:agent.example.com";
9910        let body_a = "did:web:body-a.example.com";
9911        let body_b = "did:web:body-b.example.com";
9912
9913        let e1 = build_embodiment(
9914            &agent_seed,
9915            &BuildEmbodiment {
9916                agent_did: agent_did.into(),
9917                body_did: body_a.into(),
9918                body_hardware_root: "uROOTA".into(),
9919                from_body: None,
9920                embodied_at: "2026-01-01T00:00:00Z".into(),
9921                valid_until: Some("2026-01-01T01:00:00Z".into()),
9922            },
9923        )
9924        .unwrap();
9925        let e2 = build_embodiment(
9926            &agent_seed,
9927            &BuildEmbodiment {
9928                agent_did: agent_did.into(),
9929                body_did: body_b.into(),
9930                body_hardware_root: "uROOTB".into(),
9931                from_body: Some(body_a.into()),
9932                embodied_at: "2026-01-01T01:00:00Z".into(),
9933                valid_until: None,
9934            },
9935        )
9936        .unwrap();
9937
9938        // A clean two-link chain ends at body-b: the first link opens on body-a
9939        // and the second link's fromBody re-binds to it.
9940        let (ok, current) = verify_continuity_chain(
9941            &[e1.clone(), e2.clone()],
9942            Keys::Resolver(&any_did(&agent.public_key())),
9943            None,
9944            None,
9945            "2026-06-01T00:00:00Z",
9946        )
9947        .unwrap();
9948        assert!(ok);
9949        assert_eq!(current.as_deref(), Some(body_b));
9950
9951        // Declaring the wrong origin body breaks the first link, since the first
9952        // link's fromBody must match the origin when given.
9953        let (bad_origin, _) = verify_continuity_chain(
9954            &[e1.clone(), e2.clone()],
9955            Keys::Resolver(&any_did(&agent.public_key())),
9956            Some(body_b),
9957            None,
9958            "2026-06-01T00:00:00Z",
9959        )
9960        .unwrap();
9961        assert!(!bad_origin);
9962
9963        // A broken link (second link's fromBody does not match the first's body)
9964        // fails the chain.
9965        let broken = build_embodiment(
9966            &agent_seed,
9967            &BuildEmbodiment {
9968                agent_did: agent_did.into(),
9969                body_did: body_b.into(),
9970                body_hardware_root: "uROOTB".into(),
9971                from_body: Some("did:web:body-x.example.com".into()),
9972                embodied_at: "2026-01-01T01:00:00Z".into(),
9973                valid_until: None,
9974            },
9975        )
9976        .unwrap();
9977        let (bad_link, _) = verify_continuity_chain(
9978            &[e1.clone(), broken],
9979            Keys::Resolver(&any_did(&agent.public_key())),
9980            None,
9981            None,
9982            "2026-06-01T00:00:00Z",
9983        )
9984        .unwrap();
9985        assert!(!bad_link);
9986
9987        // Every link must verify under the SAME agent key: a link signed by a
9988        // different key breaks the chain (a mind is one persistent identity).
9989        let e2_stranger = build_embodiment(
9990            &stranger_seed,
9991            &BuildEmbodiment {
9992                agent_did: agent_did.into(),
9993                body_did: body_b.into(),
9994                body_hardware_root: "uROOTB".into(),
9995                from_body: Some(body_a.into()),
9996                embodied_at: "2026-01-01T01:00:00Z".into(),
9997                valid_until: None,
9998            },
9999        )
10000        .unwrap();
10001        assert!(verify_embodiment(
10002            &e2_stranger,
10003            kd(&e2_stranger, &stranger.public_key()),
10004            None,
10005            "2026-06-01T00:00:00Z"
10006        )
10007        .unwrap()
10008        .is_some());
10009        let (mixed_keys, _) = verify_continuity_chain(
10010            &[e1, e2_stranger],
10011            Keys::Resolver(&any_did(&agent.public_key())),
10012            None,
10013            None,
10014            "2026-06-01T00:00:00Z",
10015        )
10016        .unwrap();
10017        assert!(!mixed_keys);
10018    }
10019
10020    #[test]
10021    fn fork_detection_flags_overlapping_bodies() {
10022        let agent_seed = [61u8; 32];
10023        let agent_did = "did:web:agent.example.com";
10024        let body_a = "did:web:body-a.example.com";
10025        let body_b = "did:web:body-b.example.com";
10026
10027        let build = |body: &str, root: &str, from: &str, until: &str| {
10028            build_embodiment(
10029                &agent_seed,
10030                &BuildEmbodiment {
10031                    agent_did: agent_did.into(),
10032                    body_did: body.into(),
10033                    body_hardware_root: root.into(),
10034                    from_body: None,
10035                    embodied_at: from.into(),
10036                    valid_until: Some(until.into()),
10037                },
10038            )
10039            .unwrap()
10040        };
10041
10042        // A clean handover: body-a's window ends exactly where body-b's begins.
10043        // Half-open intervals do not overlap, so this is not a fork.
10044        let clean_a = build(
10045            body_a,
10046            "uROOTA",
10047            "2026-01-01T00:00:00Z",
10048            "2026-01-01T01:00:00Z",
10049        );
10050        let clean_b = build(
10051            body_b,
10052            "uROOTB",
10053            "2026-01-01T01:00:00Z",
10054            "2026-01-01T02:00:00Z",
10055        );
10056        let (clean, conflict) = check_no_fork(&[clean_a, clean_b]).unwrap();
10057        assert!(clean);
10058        assert!(conflict.is_none());
10059
10060        // Overlapping windows on different bodies are a fork; the conflict names
10061        // both bodies.
10062        let fork_a = build(
10063            body_a,
10064            "uROOTA",
10065            "2026-01-01T00:00:00Z",
10066            "2026-01-01T02:00:00Z",
10067        );
10068        let fork_b = build(
10069            body_b,
10070            "uROOTB",
10071            "2026-01-01T01:00:00Z",
10072            "2026-01-01T03:00:00Z",
10073        );
10074        let (forked, conflict) = check_no_fork(&[fork_a, fork_b]).unwrap();
10075        assert!(!forked);
10076        let conflict = conflict.expect("a fork names the two conflicting bodies");
10077        assert_eq!(conflict.body_a, body_a);
10078        assert_eq!(conflict.body_b, body_b);
10079    }
10080
10081    // Custody handoff (Phase 5.16) -----------------------------------------
10082
10083    fn actor_keys_from_vector(map: &Value) -> Vec<ActorKey> {
10084        map.as_object()
10085            .expect("custody_actor_keys object")
10086            .iter()
10087            .map(|(did, jwk)| ActorKey {
10088                did: did.clone(),
10089                public_key: jwk_pub(jwk),
10090            })
10091            .collect()
10092    }
10093
10094    // Cross-language interop: Rust verifies the Python-signed custody chain under
10095    // the actor keys from the vector, ending on robot-b, and localizes the
10096    // condition change to the hop robot-a was responsible for.
10097    #[test]
10098    fn verifies_python_custody_interop_vector() {
10099        let vector = load_vector();
10100        let chain: Vec<Value> = vector["custody_chain"]
10101            .as_array()
10102            .expect("custody_chain array")
10103            .clone();
10104        let keys = actor_keys_from_vector(&vector["custody_actor_keys"]);
10105        let origin = vector["custody_origin_actor"].as_str().unwrap();
10106
10107        let (ok, current) =
10108            verify_handoff_chain(&chain, &keys, "tote-42", Some(origin), false, TNOW).unwrap();
10109        assert!(ok, "the Python custody chain must verify in Rust");
10110        assert_eq!(
10111            current.as_deref(),
10112            Some("did:web:robot-b.example.com"),
10113            "the chain ends holding at robot-b"
10114        );
10115
10116        let change = locate_condition_change(&chain).expect("the condition changed");
10117        assert_eq!(
10118            change.responsible_holder.as_deref(),
10119            Some("did:web:robot-a.example.com"),
10120            "robot-a held the task while its condition changed"
10121        );
10122        assert_eq!(change.from_condition, "intact");
10123        assert_eq!(change.to_condition, "damaged");
10124    }
10125
10126    #[test]
10127    fn handoff_roundtrip_and_receiver_rule() {
10128        let robot_seed = [71u8; 32];
10129        let other_seed = [72u8; 32];
10130        let robot = Ed25519KeyPair::from_seed(&robot_seed);
10131        let other = Ed25519KeyPair::from_seed(&other_seed);
10132        let worker = "did:web:worker-jane.example.com";
10133        let robot_a = "did:web:robot-a.example.com";
10134
10135        let cred = build_handoff(
10136            &robot_seed,
10137            &BuildHandoff {
10138                release: None,
10139                prev_handoff_id: None,
10140                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000105".into(),
10141                task_id: "tote-42".into(),
10142                from_actor: worker.into(),
10143                to_actor: robot_a.into(),
10144                condition: Some("intact".into()),
10145                handoff_at: "2026-01-01T00:00:00Z".into(),
10146                valid_until: None,
10147            },
10148        )
10149        .unwrap();
10150
10151        let subject = verify_handoff(
10152            &cred,
10153            kd(&cred, &robot.public_key()),
10154            HandoffCheck::default(),
10155            TNOW,
10156        )
10157        .unwrap()
10158        .expect("handoff verifies under the receiver key");
10159        assert_eq!(subject["fromActor"], json!(worker));
10160        assert_eq!(subject["toActor"], json!(robot_a));
10161
10162        // The issuer must be the receiver: forge a handoff issued by a different
10163        // party over the same subject and re-sign it. It must be rejected even with
10164        // a valid proof under the signing key, because a party attests its own
10165        // acceptance of custody.
10166        let forged = {
10167            let mut bare = cred.clone();
10168            bare.as_object_mut().unwrap().remove("proof");
10169            bare["issuer"] = json!("did:web:impostor.example.com");
10170            let opts = BuildProofOptions::new(
10171                "did:web:impostor.example.com#key-1".to_string(),
10172                "2026-01-01T00:00:00Z",
10173            );
10174            data_integrity::sign(&bare, &other_seed, &opts).unwrap()
10175        };
10176        assert!(verify_handoff(
10177            &forged,
10178            kd(&forged, &other.public_key()),
10179            HandoffCheck::default(),
10180            TNOW
10181        )
10182        .unwrap()
10183        .is_none());
10184    }
10185
10186    #[test]
10187    fn handoff_chain_links_and_rejects() {
10188        let a_seed = [73u8; 32];
10189        let b_seed = [74u8; 32];
10190        let a = Ed25519KeyPair::from_seed(&a_seed);
10191        let b = Ed25519KeyPair::from_seed(&b_seed);
10192        let worker = "did:web:worker-jane.example.com";
10193        let robot_a = "did:web:robot-a.example.com";
10194        let robot_b = "did:web:robot-b.example.com";
10195
10196        let h1 = build_handoff(
10197            &a_seed,
10198            &BuildHandoff {
10199                release: None,
10200                prev_handoff_id: None,
10201                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000106".into(),
10202                task_id: "tote-42".into(),
10203                from_actor: worker.into(),
10204                to_actor: robot_a.into(),
10205                condition: Some("intact".into()),
10206                handoff_at: "2026-01-01T00:00:00Z".into(),
10207                valid_until: None,
10208            },
10209        )
10210        .unwrap();
10211        let h2 = build_handoff(
10212            &b_seed,
10213            &BuildHandoff {
10214                release: None,
10215                prev_handoff_id: Some("urn:uuid:00000000-0000-4000-8000-000000000106".into()),
10216                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000107".into(),
10217                task_id: "tote-42".into(),
10218                from_actor: robot_a.into(),
10219                to_actor: robot_b.into(),
10220                condition: Some("damaged".into()),
10221                handoff_at: "2026-01-01T00:10:00Z".into(),
10222                valid_until: None,
10223            },
10224        )
10225        .unwrap();
10226
10227        let keys = vec![
10228            ActorKey {
10229                did: robot_a.into(),
10230                public_key: a.public_key().to_vec(),
10231            },
10232            ActorKey {
10233                did: robot_b.into(),
10234                public_key: b.public_key().to_vec(),
10235            },
10236        ];
10237
10238        // A clean two-link chain ends holding at robot-b: the first link's
10239        // fromActor is the origin worker and the second link re-binds to robot-a.
10240        let (ok, current) = verify_handoff_chain(
10241            &[h1.clone(), h2.clone()],
10242            &keys,
10243            "tote-42",
10244            Some(worker),
10245            false,
10246            TNOW,
10247        )
10248        .unwrap();
10249        assert!(ok);
10250        assert_eq!(current.as_deref(), Some(robot_b));
10251
10252        // Declaring the wrong origin actor breaks the first link.
10253        let (bad_origin, _) = verify_handoff_chain(
10254            &[h1.clone(), h2.clone()],
10255            &keys,
10256            "tote-42",
10257            Some(robot_b),
10258            false,
10259            TNOW,
10260        )
10261        .unwrap();
10262        assert!(!bad_origin);
10263
10264        // A broken link (second link's fromActor does not match the first's
10265        // toActor) fails the chain.
10266        let broken = build_handoff(
10267            &b_seed,
10268            &BuildHandoff {
10269                release: None,
10270                prev_handoff_id: Some("urn:uuid:00000000-0000-4000-8000-000000000106".into()),
10271                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000108".into(),
10272                task_id: "tote-42".into(),
10273                from_actor: "did:web:robot-x.example.com".into(),
10274                to_actor: robot_b.into(),
10275                condition: Some("damaged".into()),
10276                handoff_at: "2026-01-01T00:10:00Z".into(),
10277                valid_until: None,
10278            },
10279        )
10280        .unwrap();
10281        let (bad_link, _) = verify_handoff_chain(
10282            &[h1.clone(), broken],
10283            &keys,
10284            "tote-42",
10285            Some(worker),
10286            false,
10287            TNOW,
10288        )
10289        .unwrap();
10290        assert!(!bad_link);
10291
10292        // A missing receiver key for a link fails the chain.
10293        let partial = vec![ActorKey {
10294            did: robot_a.into(),
10295            public_key: a.public_key().to_vec(),
10296        }];
10297        let (no_key, _) = verify_handoff_chain(
10298            &[h1.clone(), h2.clone()],
10299            &partial,
10300            "tote-42",
10301            Some(worker),
10302            false,
10303            TNOW,
10304        )
10305        .unwrap();
10306        assert!(!no_key);
10307
10308        // holder_at reports who held the task at a moment: robot-a right after the
10309        // first handoff, robot-b right after the second.
10310        assert_eq!(
10311            holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:05:00Z").as_deref(),
10312            Some(robot_a)
10313        );
10314        assert_eq!(
10315            holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:15:00Z").as_deref(),
10316            Some(robot_b)
10317        );
10318
10319        // A chain whose condition never changes localizes nothing.
10320        let steady = build_handoff(
10321            &b_seed,
10322            &BuildHandoff {
10323                release: None,
10324                prev_handoff_id: None,
10325                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000109".into(),
10326                task_id: "tote-42".into(),
10327                from_actor: robot_a.into(),
10328                to_actor: robot_b.into(),
10329                condition: Some("intact".into()),
10330                handoff_at: "2026-01-01T00:10:00Z".into(),
10331                valid_until: None,
10332            },
10333        )
10334        .unwrap();
10335        assert!(locate_condition_change(&[h1, steady]).is_none());
10336    }
10337
10338    // Robot-to-infrastructure bounded access (Phase 5.17) ------------------
10339
10340    // Cross-language interop: Rust authorizes the Python-signed grant and request
10341    // from the vector under the operator and robot keys, offline.
10342    #[test]
10343    fn authorizes_python_access_interop_vector() {
10344        let vector = load_vector();
10345        let grant = vector["access_grant_credential"].clone();
10346        let request = vector["access_request_credential"].clone();
10347        let operator_pub = jwk_pub(&vector["access_operator_key"]);
10348        let robot_pub = jwk_pub(&vector["access_robot_key"]);
10349
10350        // The request was made at VALID_FROM; a resource checks it within the
10351        // 60 s age limit and remembers its nonce.
10352        let mut seen = HashSet::new();
10353        let res = authorize_access(
10354            &grant,
10355            &request,
10356            kd(&grant, &operator_pub),
10357            kd(&request, &robot_pub),
10358            RequestReplay::new(&mut seen),
10359            "2026-01-01T00:00:30Z",
10360        )
10361        .unwrap();
10362        assert!(
10363            res.ok,
10364            "the Python grant and request must authorize in Rust: {:?}",
10365            res.reasons
10366        );
10367        assert!(res.reasons.is_empty());
10368        // A replay of the same request is refused, and so is a stale one.
10369        let again = authorize_access(
10370            &grant,
10371            &request,
10372            kd(&grant, &operator_pub),
10373            kd(&request, &robot_pub),
10374            RequestReplay::new(&mut seen),
10375            "2026-01-01T00:00:30Z",
10376        )
10377        .unwrap();
10378        assert!(!again.ok);
10379        let mut fresh = HashSet::new();
10380        let stale = authorize_access(
10381            &grant,
10382            &request,
10383            kd(&grant, &operator_pub),
10384            kd(&request, &robot_pub),
10385            RequestReplay::new(&mut fresh),
10386            "2026-01-01T00:05:00Z",
10387        )
10388        .unwrap();
10389        assert!(!stale.ok);
10390    }
10391
10392    // Fused-sensor provenance (Phase 5.18) ---------------------------------
10393
10394    // Cross-language interop: Rust reproduces the exact inputs digest and fused
10395    // output hash Python pinned, and verifies the Python-signed attestation.
10396    #[test]
10397    fn verifies_python_fused_interop_vector() {
10398        let vector = load_vector();
10399        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
10400
10401        let inputs: Vec<String> = vector["fused_input_frame_hashes"]
10402            .as_array()
10403            .unwrap()
10404            .iter()
10405            .map(|v| v.as_str().unwrap().to_string())
10406            .collect();
10407        assert_eq!(
10408            fusion_inputs_digest_version(&inputs, INPUTS_DIGEST_V1).unwrap(),
10409            vector["expected_fusion_inputs_digest"].as_str().unwrap()
10410        );
10411        assert_eq!(
10412            fusion_inputs_digest(&inputs).unwrap(),
10413            vector["expected_fusion_inputs_digest_v2"].as_str().unwrap()
10414        );
10415
10416        assert_eq!(
10417            hash_fused_output(b"world-model-0"),
10418            vector["expected_fused_output_hash"].as_str().unwrap()
10419        );
10420
10421        let cred = vector["fused_perception_attestation"].clone();
10422        let subject = verify_fused_attestation(&cred, kd(&cred, &robot_pub), None, TNOW)
10423            .unwrap()
10424            .expect("fused attestation verifies");
10425        assert_eq!(subject["fusionMethod"], "occupancy-grid-v1");
10426        assert_eq!(
10427            subject["inputsDigest"].as_str().unwrap(),
10428            vector["expected_fusion_inputs_digest_v2"].as_str().unwrap()
10429        );
10430    }
10431
10432    // Wear and degradation attestation (Phase 5.19) ------------------------
10433
10434    // Cross-language interop: Rust verifies the Python-signed wear history and
10435    // reproduces the physical scope narrowed for the pinned wear level.
10436    #[test]
10437    fn verifies_python_wear_interop_vector() {
10438        let vector = load_vector();
10439        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
10440
10441        let chain: Vec<Value> = vector["wear_chain"].as_array().unwrap().clone();
10442        let latest = verify_wear_chain(&chain, Keys::Resolver(&any_did(&robot_pub)), TNOW)
10443            .unwrap()
10444            .expect("wear chain verifies");
10445        assert_eq!(latest["wearLevel"].as_f64().unwrap(), 0.3);
10446
10447        let scope = vector["wear_input_scope"].clone();
10448        let level = vector["wear_attenuation_level"].as_f64().unwrap();
10449        let narrowed = attenuate_for_wear(&scope, level).unwrap();
10450        assert_eq!(narrowed, vector["expected_attenuated_scope"]);
10451        assert_eq!(narrowed["maxForceN"].as_f64().unwrap(), 60.0);
10452        assert_eq!(narrowed["maxSpeedMps"].as_f64().unwrap(), 1.125);
10453        assert_eq!(narrowed["maxSpeedNearHumansMps"].as_f64().unwrap(), 0.1875);
10454        assert!(attenuates(&scope, &narrowed));
10455    }
10456
10457    // Bystander-consent evidence (Phase 5.20) ------------------------------
10458
10459    // Cross-language interop: Rust reproduces the capture hash Python pinned,
10460    // verifies the bystander-signed token is bound to that capture, and verifies
10461    // the robot-signed evidence with the token and the bystander key.
10462    #[test]
10463    fn verifies_python_consent_interop_vector() {
10464        let vector = load_vector();
10465        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
10466        let bystander_pub = jwk_pub(&vector["consent_bystander_key"]);
10467
10468        let capture = b"bystander-frame-0";
10469        let capture_hash = hash_capture(capture);
10470        assert_eq!(
10471            capture_hash,
10472            vector["expected_consent_capture_hash"].as_str().unwrap()
10473        );
10474
10475        let token = vector["consent_token_credential"].clone();
10476        let robot_did = token["credentialSubject"]["robotDid"].as_str().unwrap();
10477        let tok_subject = verify_consent_token(
10478            &token,
10479            kd(&token, &bystander_pub),
10480            &capture_hash,
10481            robot_did,
10482            "2026-01-01T00:05:00Z",
10483        )
10484        .unwrap()
10485        .expect("consent token verifies bound to the capture");
10486        assert_eq!(tok_subject["captureHash"].as_str().unwrap(), capture_hash);
10487
10488        let evidence = vector["consent_evidence_credential"].clone();
10489        let bystander_did = token["issuer"].as_str().unwrap();
10490        let keys = [BystanderKey {
10491            did: bystander_did.to_string(),
10492            public_key: bystander_pub.clone(),
10493        }];
10494        let ev_subject = verify_consent_evidence(
10495            &evidence,
10496            kd(&evidence, &robot_pub),
10497            Some(capture),
10498            Some(std::slice::from_ref(&token)),
10499            Some(&keys),
10500            "2026-01-01T00:05:00Z",
10501        )
10502        .unwrap()
10503        .expect("consent evidence verifies with token and bystander key");
10504        assert_eq!(ev_subject["basis"].as_str().unwrap(), "explicit-consent");
10505    }
10506}
10507
10508#[cfg(test)]
10509mod robot_root_identity_tests {
10510    use super::*;
10511    use crate::keys::Ed25519KeyPair;
10512    #[allow(unused_imports)]
10513    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
10514    #[allow(unused_imports)]
10515    use crate::robotics_verify::Keys;
10516    use std::path::PathBuf;
10517
10518    const NOW: &str = "2026-07-01T00:00:00Z";
10519    const VALID_FROM: &str = "2026-01-01T00:00:00Z";
10520    const CREATED: &str = "2026-01-01T00:00:00Z";
10521    const VALID_SECONDS: i64 = 100 * 365 * 24 * 3600;
10522    // Matches the manufacturer seed recorded in the interop vector (0x04 x32).
10523    const MANUFACTURER_SEED: [u8; 32] = [0x04; 32];
10524    const FORGED_ID: &str = "urn:uuid:66666666-6666-6666-6666-666666666666";
10525
10526    fn load_vector() -> Value {
10527        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10528            .join("../../test-vectors/root-of-trust/vector.json");
10529        let text = std::fs::read_to_string(&path)
10530            .unwrap_or_else(|e| panic!("read vector {}: {e}", path.display()));
10531        serde_json::from_str(&text).expect("vector is valid JSON")
10532    }
10533
10534    fn robot_pub(vector: &Value) -> Vec<u8> {
10535        let x = vector["robotPublicKey"]["x"].as_str().unwrap();
10536        URL_SAFE_NO_PAD.decode(x).unwrap()
10537    }
10538
10539    fn stray_multikey(seed: &[u8]) -> String {
10540        let kp = Ed25519KeyPair::from_seed_slice(seed).unwrap();
10541        multikey::encode_ed25519_public(&kp.public_key()).unwrap()
10542    }
10543
10544    fn stray_did(seed: &[u8]) -> String {
10545        Ed25519KeyPair::from_seed_slice(seed).unwrap().did_key()
10546    }
10547
10548    fn robot_attributes() -> Value {
10549        json!({ "make": "Acme Robotics", "model": "AR-7", "serial": "SN-000123" })
10550    }
10551
10552    // The committed Python-minted robot chain must verify in Rust: recognized
10553    // manufacturer provenance plus hardware-rooting.
10554    #[test]
10555    fn verifies_python_robot_identity_interop_vector() {
10556        let v = load_vector();
10557        let root = v["trustedRoot"].as_str().unwrap();
10558        let r = verify_robot_identity_chain(
10559            &v["robotAuthorityIdentity"],
10560            &v["robotRecognizedIssuer"],
10561            &v["robotHardwareCredential"],
10562            root,
10563            &robot_pub(&v),
10564            Some(&v["rootOfTrust"]),
10565            NOW,
10566            30,
10567        );
10568        assert!(r.ok, "robot chain must verify: {:?}", r.reason);
10569        assert_eq!(
10570            Some(r.hardware_rooted),
10571            v["expected"]["hardwareRooted"].as_bool(),
10572            "the manufacturer pinned the hardware-root key"
10573        );
10574        assert_eq!(r.robot_did.as_deref(), v["expected"]["robotDid"].as_str());
10575        assert_eq!(
10576            r.issuer_did.as_deref(),
10577            v["expected"]["robotIssuerDid"].as_str()
10578        );
10579        assert_eq!(r.root_did.as_deref(), Some(root));
10580        assert_eq!(
10581            v["expected"]["verifyRobotIdentityChain"].as_bool(),
10582            Some(true)
10583        );
10584    }
10585
10586    // Adversarial: pinning a different root breaks the recognition anchor.
10587    #[test]
10588    fn wrong_pinned_root_rejected() {
10589        let v = load_vector();
10590        let other_root = stray_did(&[0x09; 32]);
10591        let r = verify_robot_identity_chain(
10592            &v["robotAuthorityIdentity"],
10593            &v["robotRecognizedIssuer"],
10594            &v["robotHardwareCredential"],
10595            &other_root,
10596            &robot_pub(&v),
10597            None,
10598            NOW,
10599            30,
10600        );
10601        assert!(!r.ok);
10602        assert_eq!(r.reason.as_deref(), Some("recognized_issuer_not_from_root"));
10603    }
10604
10605    // Adversarial: the manufacturer vouched a key that is not the robot's real
10606    // key. Provenance holds but the hardware key does not match.
10607    #[test]
10608    fn manufacturer_vouched_a_different_key() {
10609        let v = load_vector();
10610        let root = v["trustedRoot"].as_str().unwrap();
10611        let robot_did = v["expected"]["robotDid"].as_str().unwrap();
10612        let forged = build_robot_identity(
10613            &MANUFACTURER_SEED,
10614            robot_did,
10615            &stray_multikey(&[0x09; 32]),
10616            &robot_attributes(),
10617            VALID_SECONDS,
10618            VALID_FROM,
10619            CREATED,
10620            None,
10621            FORGED_ID,
10622            None,
10623        )
10624        .unwrap();
10625        let r = verify_robot_identity_chain(
10626            &forged,
10627            &v["robotRecognizedIssuer"],
10628            &v["robotHardwareCredential"],
10629            root,
10630            &robot_pub(&v),
10631            Some(&v["rootOfTrust"]),
10632            NOW,
10633            30,
10634        );
10635        assert!(!r.ok);
10636        assert_eq!(r.reason.as_deref(), Some("hardware_key_mismatch"));
10637    }
10638
10639    // Adversarial: an impostor key is presented for the hardware credential, so
10640    // the secure-element attestation no longer verifies.
10641    #[test]
10642    fn impostor_key_fails_hardware_root() {
10643        let v = load_vector();
10644        let root = v["trustedRoot"].as_str().unwrap();
10645        let impostor = Ed25519KeyPair::from_seed(&[0x09; 32]).public_key();
10646        let r = verify_robot_identity_chain(
10647            &v["robotAuthorityIdentity"],
10648            &v["robotRecognizedIssuer"],
10649            &v["robotHardwareCredential"],
10650            root,
10651            &impostor,
10652            Some(&v["rootOfTrust"]),
10653            NOW,
10654            30,
10655        );
10656        assert!(!r.ok);
10657        assert_eq!(r.reason.as_deref(), Some("hardware_root_invalid"));
10658    }
10659}
10660
10661#[cfg(test)]
10662mod port_hardening_tests {
10663    use super::*;
10664    use crate::keys::Ed25519KeyPair;
10665    #[allow(unused_imports)]
10666    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
10667    #[allow(unused_imports)]
10668    use crate::robotics_verify::Keys;
10669    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
10670    use base64::Engine;
10671
10672    // A missing or empty input list is malformed: the log check fails closed
10673    // instead of reporting "every input was logged".
10674    #[test]
10675    fn fusion_inputs_check_fails_closed_on_an_empty_list() {
10676        let empty = json!({"credentialSubject": {"inputFrameHashes": []}});
10677        assert!(!verify_fusion_inputs(&empty, &[]).ok);
10678        let missing = json!({"credentialSubject": {}});
10679        assert!(!verify_fusion_inputs(&missing, &[]).ok);
10680        let odd = json!({"credentialSubject": {"inputFrameHashes": ["ua", 5]}});
10681        let res = verify_fusion_inputs(&odd, &[json!({"frameHash": "ua"})]);
10682        assert!(!res.ok);
10683        assert_eq!(res.missing, vec!["5".to_string()]);
10684    }
10685
10686    fn load_vector() -> Value {
10687        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10688            .join("../../test-vectors/robotics/vector.json");
10689        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
10690    }
10691
10692    fn jwk_pub(jwk: &Value) -> Vec<u8> {
10693        URL_SAFE_NO_PAD.decode(jwk["x"].as_str().unwrap()).unwrap()
10694    }
10695
10696    fn lease(valid_until: &str) -> (Value, Vec<u8>) {
10697        let seed = [51u8; 32];
10698        let kp = Ed25519KeyPair::from_seed(&seed);
10699        let cred = build_delegation_lease(
10700            &seed,
10701            &BuildDelegationLease {
10702                issuer_did: "did:web:robot.example.com".into(),
10703                robot_did: "did:web:robot.example.com".into(),
10704                lease_id: "lease-h".into(),
10705                scope: json!({"maxForceN": 80.0}),
10706                parent_lease_id: None,
10707                valid_from: "2026-01-01T00:00:00Z".into(),
10708                valid_until: valid_until.into(),
10709            },
10710        )
10711        .unwrap();
10712        (cred, kp.public_key().to_vec())
10713    }
10714
10715    // The core needs a clock: an empty or malformed `now` is an error, never a
10716    // skipped window check, in every verifier that checks a window.
10717    #[test]
10718    fn a_missing_or_malformed_clock_is_an_error() {
10719        let (cred, key) = lease("2026-01-01T01:00:00Z");
10720        for bad in ["", "null", "not-a-date", "2026-01-01"] {
10721            assert!(
10722                verify_delegation_lease(
10723                    &cred,
10724                    kd(&cred, &key),
10725                    "did:web:robot.example.com",
10726                    None,
10727                    None,
10728                    bad
10729                )
10730                .is_err(),
10731                "{bad:?}"
10732            );
10733            assert!(
10734                lease_permits(
10735                    &json!({}),
10736                    &PhysicalAction::default(),
10737                    Some(&cred),
10738                    kd(&cred, &key),
10739                    None,
10740                    bad
10741                )
10742                .is_err(),
10743                "{bad:?}"
10744            );
10745            assert!(verify_action_authorization(&[], "a", "r", &[], 1, None, bad).is_err());
10746            assert!(verify_access_grant(&cred, kd(&cred, &key), None, bad).is_err());
10747            assert!(authorize_access(
10748                &cred,
10749                &cred,
10750                kd(&cred, &key),
10751                kd(&cred, &key),
10752                RequestReplay::new(&mut HashSet::new()),
10753                bad
10754            )
10755            .is_err());
10756            assert!(verify_consent_token(&cred, kd(&cred, &key), "h", "r", bad).is_err());
10757            assert!(
10758                verify_consent_evidence(&cred, kd(&cred, &key), None, None, None, bad).is_err()
10759            );
10760        }
10761    }
10762
10763    // The shared vector's expired lease is refused at any time after its window,
10764    // and accepted inside it.
10765    #[test]
10766    fn expired_vector_lease_refused_after_its_window() {
10767        let v = load_vector();
10768        let key = jwk_pub(&v["robot_public_key_jwk"]);
10769        let cred = &v["delegation_lease_expired_credential"];
10770        assert!(verify_delegation_lease(
10771            cred,
10772            kd(cred, &key),
10773            "did:web:robot.example.com",
10774            None,
10775            None,
10776            "2026-01-01T00:30:00Z"
10777        )
10778        .unwrap()
10779        .is_some());
10780        assert!(verify_delegation_lease(
10781            cred,
10782            kd(cred, &key),
10783            "did:web:robot.example.com",
10784            None,
10785            None,
10786            "2026-06-01T00:00:00Z"
10787        )
10788        .unwrap()
10789        .is_none());
10790    }
10791
10792    // A validity bound that is present must be a string that parses.
10793    #[test]
10794    fn non_string_window_bounds_are_invalid() {
10795        for (key, bad) in [
10796            ("validFrom", json!(5)),
10797            ("validFrom", json!(null)),
10798            ("validUntil", json!(["2099-01-01T00:00:00Z"])),
10799            ("validUntil", json!(4102444800i64)),
10800            ("validUntil", json!("")),
10801        ] {
10802            let mut cred = json!({
10803                "validFrom": "2026-01-01T00:00:00Z",
10804                "validUntil": "2026-01-01T01:00:00Z"
10805            });
10806            cred[key] = bad.clone();
10807            assert!(
10808                rv::window_reason(&cred, Window::IfPresent, 1_767_225_660 * 1_000_000_000, 0)
10809                    .is_some(),
10810                "{key}={bad}"
10811            );
10812        }
10813    }
10814
10815    // One malformed approval from a listed approver is skipped; it does not fail
10816    // the whole authorization (shared vector).
10817    #[test]
10818    fn malformed_approvals_are_skipped_not_fatal() {
10819        let v = load_vector();
10820        let approvals = v["quorum_approvals_with_malformed"]
10821            .as_array()
10822            .unwrap()
10823            .clone();
10824        let keys: Vec<ApproverKey> = v["quorum_approver_keys"]
10825            .as_object()
10826            .unwrap()
10827            .iter()
10828            .map(|(did, jwk)| ApproverKey {
10829                did: did.clone(),
10830                public_key: jwk_pub(jwk),
10831            })
10832            .collect();
10833        let (ok, approvers) = verify_action_authorization(
10834            &approvals,
10835            v["quorum_action_id"].as_str().unwrap(),
10836            "did:web:robot.example.com",
10837            &keys,
10838            2,
10839            None,
10840            v["quorum_now"].as_str().unwrap(),
10841        )
10842        .unwrap();
10843        let expected = &v["expected_quorum_with_malformed"];
10844        assert_eq!(json!(ok), expected["authorized"]);
10845        assert_eq!(json!(approvers), expected["approvers"]);
10846    }
10847
10848    // A malformed scope field the action is checked against is a violation.
10849    #[test]
10850    fn malformed_scope_fields_are_violations() {
10851        let force = PhysicalAction {
10852            force_n: Some(5000.0),
10853            ..Default::default()
10854        };
10855        for cap in [json!("100"), json!(null), json!(true), json!([100])] {
10856            let r = check_physical_action(&json!({"maxForceN": cap}), &force);
10857            assert!(!r.ok, "maxForceN={cap}");
10858        }
10859        let speed = PhysicalAction {
10860            speed_mps: Some(9.0),
10861            near_humans: true,
10862            ..Default::default()
10863        };
10864        let r = check_physical_action(
10865            &json!({"maxSpeedMps": 1.0, "maxSpeedNearHumansMps": null}),
10866            &speed,
10867        );
10868        assert!(!r.ok);
10869        let zone = PhysicalAction {
10870            zone: Some("A".into()),
10871            ..Default::default()
10872        };
10873        for zones in [json!("A"), json!({"A": true}), json!(7)] {
10874            assert!(!check_physical_action(&json!({"allowedZones": zones}), &zone).ok);
10875        }
10876        let late = PhysicalAction {
10877            time_hm: Some("23:00".into()),
10878            ..Default::default()
10879        };
10880        for ws in [
10881            json!("08:00-18:00"),
10882            json!({"start": "08:00", "end": "18:00"}),
10883            json!(["08:00"]),
10884            json!([{"start": 800, "end": "18:00"}]),
10885        ] {
10886            assert!(
10887                !check_physical_action(&json!({"shiftWindows": ws}), &late).ok,
10888                "{ws}"
10889            );
10890        }
10891        // Native NaN in an action never passes a cap.
10892        let nan = PhysicalAction {
10893            force_n: Some(f64::NAN),
10894            ..Default::default()
10895        };
10896        assert!(!check_physical_action(&json!({"maxForceN": 10.0}), &nan).ok);
10897    }
10898
10899    #[test]
10900    fn malformed_child_fields_never_attenuate() {
10901        let parent = json!({
10902            "maxForceN": 80.0,
10903            "allowedZones": ["A", "B"],
10904            "shiftWindows": [{"start": "08:00", "end": "18:00"}]
10905        });
10906        let good = json!({
10907            "maxForceN": 50.0,
10908            "allowedZones": ["A"],
10909            "shiftWindows": [{"start": "09:00", "end": "17:00"}]
10910        });
10911        assert!(attenuates(&parent, &good));
10912        for (k, bad) in [
10913            ("shiftWindows", json!("00:00-23:59")),
10914            ("shiftWindows", json!({"start": "00:00"})),
10915            ("shiftWindows", json!([{"start": 0, "end": "23:59"}])),
10916            ("maxForceN", json!("50")),
10917            ("maxForceN", json!(null)),
10918            ("allowedZones", json!("A")),
10919            ("allowedZones", json!(["A", 7])),
10920            ("maxSpeedMps", json!("unlimited")),
10921        ] {
10922            let mut child = good.clone();
10923            child[k] = bad.clone();
10924            assert!(!attenuates(&parent, &child), "{k}={bad}");
10925        }
10926        // A malformed parent cap refuses rather than being skipped.
10927        assert!(!attenuates(&json!({"maxForceN": "80"}), &good));
10928    }
10929
10930    #[test]
10931    fn nan_wear_level_is_refused() {
10932        assert!(attenuate_for_wear(&json!({"maxForceN": 80.0}), f64::NAN).is_err());
10933        assert!(attenuate_for_wear(&json!({"maxForceN": 80.0}), 0.5).is_ok());
10934    }
10935}
10936
10937#[cfg(test)]
10938mod fork_check_tests {
10939    use super::*;
10940
10941    fn iso(offset: i64) -> String {
10942        // 2026-01-01T00:00:00Z plus offset seconds, offsets kept within one day.
10943        let s = offset.rem_euclid(86_400);
10944        let day = if offset < 0 { 31 } else { 1 };
10945        let month = if offset < 0 { "2025-12" } else { "2026-01" };
10946        format!(
10947            "{month}-{day:02}T{:02}:{:02}:{:02}Z",
10948            s / 3600,
10949            (s / 60) % 60,
10950            s % 60
10951        )
10952    }
10953
10954    fn emb(body: &str, start: i64, end: Option<i64>) -> Value {
10955        let mut e = json!({"credentialSubject": {"body": body}, "validFrom": iso(start)});
10956        if let Some(end) = end {
10957            e["validUntil"] = json!(iso(end));
10958        }
10959        e
10960    }
10961
10962    fn pairwise(windows: &[(String, i64, Option<i64>)]) -> (bool, Option<(String, String)>) {
10963        for (i, (bi, si, ei)) in windows.iter().enumerate() {
10964            for (bj, sj, ej) in &windows[i + 1..] {
10965                if bi == bj {
10966                    continue;
10967                }
10968                let a_before_b = ei.is_some_and(|e| e <= *sj);
10969                let b_before_a = ej.is_some_and(|e| e <= *si);
10970                if !(a_before_b || b_before_a) {
10971                    return (false, Some((bi.clone(), bj.clone())));
10972                }
10973            }
10974        }
10975        (true, None)
10976    }
10977
10978    fn run(list: &[Value]) -> (bool, Option<(String, String)>) {
10979        let (ok, conflict) = check_no_fork(list).unwrap();
10980        (ok, conflict.map(|c| (c.body_a, c.body_b)))
10981    }
10982
10983    #[test]
10984    fn fork_check_matches_the_shared_vector() {
10985        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10986            .join("../../test-vectors/robotics/fork_vector.json");
10987        let vector: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
10988        let cases = vector["cases"].as_array().unwrap();
10989        assert!(cases.len() > 40);
10990        for case in cases {
10991            let list = case["embodiments"].as_array().unwrap();
10992            let (ok, conflict) = check_no_fork(list).unwrap();
10993            let expected = &case["expected"];
10994            assert_eq!(ok, expected["ok"].as_bool().unwrap(), "{}", case["name"]);
10995            let got = conflict.map(|c| json!({"bodyA": c.body_a, "bodyB": c.body_b}));
10996            assert_eq!(got.as_ref(), expected.get("conflict"), "{}", case["name"]);
10997        }
10998    }
10999
11000    #[test]
11001    fn fork_check_matches_the_pairwise_scan_on_random_lists() {
11002        // A small fixed-seed generator keeps this free of extra dependencies.
11003        let mut state: u64 = 0x5eed_2026_1204;
11004        let mut next = |n: u64| {
11005            state = state
11006                .wrapping_mul(6364136223846793005)
11007                .wrapping_add(1442695040888963407);
11008            (state >> 33) % n
11009        };
11010        for _ in 0..3000 {
11011            let bodies = 1 + next(5);
11012            let len = next(15);
11013            let windows: Vec<(String, i64, Option<i64>)> = (0..len)
11014                .map(|_| {
11015                    let body = ((b'a' + next(bodies) as u8) as char).to_string();
11016                    let start = next(41) as i64;
11017                    let end = if next(100) < 15 {
11018                        None
11019                    } else {
11020                        Some(start + next(25) as i64 - 4)
11021                    };
11022                    (body, start, end)
11023                })
11024                .collect();
11025            let list: Vec<Value> = windows.iter().map(|(b, s, e)| emb(b, *s, *e)).collect();
11026            assert_eq!(run(&list), pairwise(&windows), "{windows:?}");
11027        }
11028    }
11029
11030    #[test]
11031    fn fork_check_handles_a_large_list_with_a_late_fork() {
11032        // Many overlapping windows on one body, then one other body overlapping
11033        // only the last of them: the pairwise scan needs about 2e8 steps here.
11034        let n = 20_000i64;
11035        let mut list: Vec<Value> = (0..n).map(|i| emb("body-a", i, Some(n + 5))).collect();
11036        list.push(emb("body-b", n + 4, Some(n + 6)));
11037        let began = std::time::Instant::now();
11038        assert_eq!(
11039            run(&list),
11040            (false, Some(("body-a".into(), "body-b".into())))
11041        );
11042        assert!(began.elapsed() < std::time::Duration::from_secs(10));
11043
11044        let clean: Vec<Value> = (0..n)
11045            .map(|i| {
11046                emb(
11047                    &format!("body-{i}"),
11048                    i,
11049                    if i + 1 < n { Some(i + 1) } else { None },
11050                )
11051            })
11052            .collect();
11053        let began = std::time::Instant::now();
11054        assert_eq!(run(&clean), (true, None));
11055        assert!(began.elapsed() < std::time::Duration::from_secs(10));
11056    }
11057
11058    #[test]
11059    fn fork_check_still_refuses_malformed_entries() {
11060        let good = emb("a", 0, Some(10));
11061        assert_eq!(
11062            run(&[good.clone(), json!({"validFrom": iso(0)})]),
11063            (false, None)
11064        );
11065        assert_eq!(
11066            run(&[good.clone(), json!({"credentialSubject": {"body": "b"}})]),
11067            (false, None)
11068        );
11069        let mut bad_end = emb("b", 0, None);
11070        bad_end["validUntil"] = json!("not a time");
11071        assert_eq!(run(&[good, bad_end]), (false, None));
11072    }
11073}