Skip to main content

vouch_core/
reasoning.rs

1//! Reasoned Action Proofs and event-triggered intent recheck.
2//!
3//! A standard credential answers *who* acted and *under what authority*. It says
4//! nothing about *why*. This module adds the missing "why" layer: before acting,
5//! an agent states a structured **justification** (an intent plus a set of
6//! **evidence anchors**, each a claim tied to a real artifact by that artifact's
7//! hash). The justification is committed by digest, optionally deposited with a
8//! neutral **escrow** that timestamps it, and the executed action credential
9//! carries the commitment. Three properties then hold: no fabrication (each
10//! reason names an artifact a verifier re-resolves and hashes), no post-hoc
11//! rewrite (the credential carries the digest), and, with escrow, committed
12//! before execution (the deposit time is not after execution).
13//!
14//! This is the canonical port of the Python reference `vouch/reasoning.py`. The
15//! digest algorithm and every stable reason string match byte for byte, so a
16//! seal built in one language verifies in another. Everything here is an ordinary
17//! `eddsa-jcs-2022` Verifiable Credential.
18//!
19//! ## Intent recheck (event-triggered)
20//!
21//! A heartbeat proves the agent is alive across an interval; it does not prove the
22//! agent's intent is current at the moment of a sensitive action. A justification
23//! sealed early in an interval still passes for an action executed much later in
24//! the same interval, so a sophisticated actor can time a sensitive action to land
25//! after a pulse boundary while reusing an intent sealed before it. The intent
26//! recheck binds seal freshness to the action: for a sensitive consequence tier
27//! the seal must post-date the last pulse boundary and be within a configurable
28//! max age, not merely predate execution. See [`verify_intent_freshness`] and
29//! [`reseal_intent`].
30
31#[allow(unused_imports)]
32use crate::prelude::*;
33
34use serde_json::{Map, Value};
35use sha2::{Digest, Sha256};
36
37use crate::data_integrity::{self, BuildProofOptions};
38use crate::error::{CoreError, Result};
39use crate::jcs;
40use crate::time::{check_clock_skew, parse_protocol_time_ns, seconds_to_ns};
41
42pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
43pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
44
45pub const REASONED_ACTION_TYPE: &str = "ReasonedActionCredential";
46pub const ESCROW_RECEIPT_TYPE: &str = "JustificationEscrowReceipt";
47
48pub const JUSTIFICATION_ALGORITHM: &str = "sha-256-jcs";
49
50// Structured verification reasons (stable strings, mirrored by every SDK).
51pub const REASON_INVALID_PROOF: &str = "invalid_proof";
52pub const REASON_NOT_REASONED_ACTION: &str = "not_reasoned_action";
53pub const REASON_MISSING_COMMITMENT: &str = "missing_commitment";
54pub const REASON_MISSING_ESCROW: &str = "missing_escrow";
55pub const REASON_ESCROW_INVALID: &str = "escrow_receipt_invalid";
56pub const REASON_ESCROW_DIGEST_MISMATCH: &str = "escrow_digest_mismatch";
57pub const REASON_ESCROW_AFTER_EXECUTION: &str = "escrow_after_execution";
58pub const REASON_JUSTIFICATION_DIGEST_MISMATCH: &str = "justification_digest_mismatch";
59pub const REASON_EVIDENCE_UNRESOLVED: &str = "evidence_unresolved";
60pub const REASON_EVIDENCE_HASH_MISMATCH: &str = "evidence_hash_mismatch";
61pub const REASON_UNANCHORED_CLAIM: &str = "unanchored_claim";
62
63// Intent-recheck reasons (stable prefixes; carry a structured suffix).
64pub const REASON_INTENT_SEAL_STALE: &str = "intent_seal_stale";
65pub const REASON_INTENT_SEAL_EXPIRED: &str = "intent_seal_expired";
66pub const REASON_INTENT_SEAL_MISSING: &str = "intent_seal_missing";
67/// The receipt names another agent than the credential's issuer.
68pub const REASON_ESCROW_AGENT_MISMATCH: &str = "escrow_agent_mismatch";
69/// The agent's own `sealedAt` is later than the escrow's `depositedAt`.
70pub const REASON_SEAL_AFTER_DEPOSIT: &str = "seal_after_deposit";
71/// The agent's own `sealedAt` is later than the execution time (`validFrom`).
72pub const REASON_SEAL_AFTER_EXECUTION: &str = "seal_after_execution";
73/// A seal is later than the verifier's clock plus skew.
74pub const REASON_SEAL_IN_FUTURE: &str = "seal_in_future";
75/// `validFrom`, `sealedAt` or `depositedAt` does not follow the time grammar.
76pub const REASON_MALFORMED_TIME: &str = "malformed_time";
77/// Intent recheck: the witnessed seal is later than the verifier's clock plus
78/// skew (carries `:sealed_at=<depositedAt>`).
79pub const REASON_INTENT_SEAL_FUTURE: &str = "intent_seal_future";
80/// Intent recheck: the execution time is not within the verifier's clock +/-
81/// skew (carries `:valid_from=<validFrom>`).
82pub const REASON_INTENT_EXECUTION_NOT_CURRENT: &str = "intent_execution_not_current";
83
84// ---------------------------------------------------------------------------
85// Low-level helpers
86// ---------------------------------------------------------------------------
87
88/// Multibase base64url-no-pad of raw bytes, matching the Python `_mb64` helper
89/// (`"u"` prefix + RFC 4648 base64url without padding).
90fn mb64(bytes: &[u8]) -> String {
91    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
92    use base64::Engine;
93    format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
94}
95
96/// Canonical bytes of an evidence artifact, for content addressing. A JSON string
97/// is hashed as its UTF-8 bytes; a JSON object is JCS-canonicalized. This matches
98/// the `str`/`dict` cases of the Python `_artifact_bytes`. Raw byte artifacts use
99/// [`artifact_digest_bytes`].
100fn artifact_bytes(artifact: &Value) -> Result<Vec<u8>> {
101    match artifact {
102        Value::String(s) => Ok(s.as_bytes().to_vec()),
103        Value::Object(_) => Ok(jcs::canonicalize(artifact)),
104        _ => Err(CoreError::Json(
105            "evidence artifact must be a JSON object or string".into(),
106        )),
107    }
108}
109
110/// Multibase SHA-256 of an evidence artifact (JSON object or string).
111pub fn artifact_digest(artifact: &Value) -> Result<String> {
112    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); artifact);
113    Ok(mb64(&Sha256::digest(&artifact_bytes(artifact)?)))
114}
115
116/// Multibase SHA-256 of a raw-byte evidence artifact.
117pub fn artifact_digest_bytes(artifact: &[u8]) -> String {
118    mb64(&Sha256::digest(artifact))
119}
120
121fn type_list(credential: &Value) -> Vec<String> {
122    match credential.get("type") {
123        Some(Value::String(s)) => vec![s.clone()],
124        Some(Value::Array(a)) => a
125            .iter()
126            .filter_map(|v| v.as_str().map(|s| s.to_string()))
127            .collect(),
128        _ => Vec::new(),
129    }
130}
131
132/// Attach an `eddsa-jcs-2022` proof to `credential` in place, signing with the
133/// raw Ed25519 seed and stamping `created`.
134fn attach_proof(
135    credential: &mut Value,
136    seed: Option<&[u8]>,
137    verification_method: &str,
138    created: &str,
139) -> Result<()> {
140    // No seed: the host signs (it attaches a proof with this
141    // verificationMethod and `created` through the proof rules).
142    let Some(seed) = seed else {
143        return Ok(());
144    };
145    let opts = BuildProofOptions::new(verification_method, created);
146    let proof = data_integrity::build_proof(credential, seed, &opts)?;
147    credential
148        .as_object_mut()
149        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
150        .insert("proof".into(), proof);
151    Ok(())
152}
153
154// ---------------------------------------------------------------------------
155// Justification: the structured "why", anchored to real evidence
156// ---------------------------------------------------------------------------
157
158/// Build one evidence anchor: a claim tied to a verifiable artifact. Supply
159/// `evidence` (its hash is computed) OR a precomputed `evidence_hash`.
160pub fn evidence_anchor(
161    claim: &str,
162    reference: &str,
163    evidence: Option<&Value>,
164    evidence_hash: Option<&str>,
165    anchor_type: &str,
166) -> Result<Value> {
167    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); evidence);
168    if claim.is_empty() || reference.is_empty() {
169        return Err(CoreError::Json(
170            "an evidence anchor needs a claim and a ref".into(),
171        ));
172    }
173    let hash = match evidence_hash {
174        Some(h) => h.to_string(),
175        None => match evidence {
176            Some(e) => artifact_digest(e)?,
177            None => {
178                return Err(CoreError::Json(
179                    "supply evidence or evidence_hash for the anchor".into(),
180                ))
181            }
182        },
183    };
184    let mut anchor = Map::new();
185    anchor.insert("type".into(), Value::String(anchor_type.to_string()));
186    anchor.insert("claim".into(), Value::String(claim.to_string()));
187    anchor.insert("ref".into(), Value::String(reference.to_string()));
188    anchor.insert("evidenceHash".into(), Value::String(hash));
189    Ok(Value::Object(anchor))
190}
191
192/// Assemble a justification: the intent plus its evidence anchors. `intent` must
193/// carry at least `action` and `target`; at least one anchor is required.
194pub fn build_justification(
195    intent: &Value,
196    anchors: &[Value],
197    commitment_level: Option<i64>,
198) -> Result<Value> {
199    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent, anchors);
200    if !intent.is_object()
201        || intent.get("action").and_then(|v| v.as_str()).is_none()
202        || intent.get("target").and_then(|v| v.as_str()).is_none()
203    {
204        return Err(CoreError::Json(
205            "intent must be an object with at least action and target".into(),
206        ));
207    }
208    if anchors.is_empty() {
209        return Err(CoreError::Json(
210            "a justification needs at least one evidence anchor".into(),
211        ));
212    }
213    let mut just = Map::new();
214    just.insert("intent".into(), intent.clone());
215    just.insert("evidenceAnchors".into(), Value::Array(anchors.to_vec()));
216    if let Some(level) = commitment_level {
217        just.insert("commitmentLevel".into(), Value::from(level));
218    }
219    Ok(Value::Object(just))
220}
221
222/// Multibase SHA-256 over the JCS-canonical justification.
223pub fn justification_digest(justification: &Value) -> Result<String> {
224    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); justification);
225    if !justification.is_object() {
226        return Err(CoreError::Json(
227            "justification must be a JSON object".into(),
228        ));
229    }
230    Ok(mb64(&Sha256::digest(jcs::canonicalize(justification))))
231}
232
233// ---------------------------------------------------------------------------
234// Escrow: a neutral timestamp that fixes the commitment before execution
235// ---------------------------------------------------------------------------
236
237/// Issue a signed `JustificationEscrowReceipt` fixing a commitment in time. The
238/// escrow sees only the digest, never the plaintext justification.
239#[allow(clippy::too_many_arguments)]
240pub fn build_escrow_receipt(
241    escrow_seed: &[u8],
242    escrow_did: &str,
243    escrow_verification_method: &str,
244    agent_did: &str,
245    committed_digest: &str,
246    deposited_at: &str,
247    credential_id: &str,
248) -> Result<Value> {
249    build_escrow_receipt_with(
250        Some(escrow_seed),
251        escrow_did,
252        escrow_verification_method,
253        agent_did,
254        committed_digest,
255        deposited_at,
256        credential_id,
257        None,
258    )
259}
260
261/// [`build_escrow_receipt`] with the seed optional (without one the receipt
262/// comes back unsigned, for a host whose key lives elsewhere to sign) and the
263/// proof's `created`, the time of signing (None keeps `deposited_at`).
264#[allow(clippy::too_many_arguments)]
265pub fn build_escrow_receipt_with(
266    escrow_seed: Option<&[u8]>,
267    escrow_did: &str,
268    escrow_verification_method: &str,
269    agent_did: &str,
270    committed_digest: &str,
271    deposited_at: &str,
272    credential_id: &str,
273    created: Option<&str>,
274) -> Result<Value> {
275    let mut subject = Map::new();
276    subject.insert("agent".into(), Value::String(agent_did.to_string()));
277    subject.insert(
278        "committedDigest".into(),
279        Value::String(committed_digest.to_string()),
280    );
281    subject.insert(
282        "depositedAt".into(),
283        Value::String(deposited_at.to_string()),
284    );
285
286    let mut receipt = Map::new();
287    receipt.insert(
288        "@context".into(),
289        Value::Array(vec![
290            Value::String(VC_CONTEXT_V2.into()),
291            Value::String(VOUCH_CONTEXT_V1.into()),
292        ]),
293    );
294    receipt.insert(
295        "type".into(),
296        Value::Array(vec![
297            Value::String("VerifiableCredential".into()),
298            Value::String(ESCROW_RECEIPT_TYPE.into()),
299        ]),
300    );
301    receipt.insert("id".into(), Value::String(credential_id.to_string()));
302    receipt.insert("issuer".into(), Value::String(escrow_did.to_string()));
303    receipt.insert("validFrom".into(), Value::String(deposited_at.to_string()));
304    receipt.insert("credentialSubject".into(), Value::Object(subject));
305
306    let mut receipt = Value::Object(receipt);
307    attach_proof(
308        &mut receipt,
309        escrow_seed,
310        escrow_verification_method,
311        created.unwrap_or(deposited_at),
312    )?;
313    Ok(receipt)
314}
315
316/// Verify an escrow receipt's proof and structure against the escrow's raw
317/// Ed25519 public key. The proof must be bound to the receipt's issuer
318/// (proofPurpose "assertionMethod", a verificationMethod of the escrow's DID),
319/// the subject must name the `agent` and carry the `committedDigest`, and
320/// `depositedAt` must be a protocol time. A proof `@context` must be an exact
321/// copy of the receipt's `@context` (the form an escrow writes); any other
322/// proof `@context` is refused. A receipt whose proof has none (signed before
323/// proofs carried it) is checked as before. Returns `(ok, subject)`.
324pub fn verify_escrow_receipt(receipt: &Value, escrow_public_key: &[u8]) -> (bool, Option<Value>) {
325    crate::nesting::deep_guard!((false, None); receipt);
326    if !type_list(receipt).iter().any(|t| t == ESCROW_RECEIPT_TYPE) {
327        return (false, None);
328    }
329    // The only proof @context accepted is an exact copy of the receipt's own,
330    // the form a signer writes; a receipt signed before proofs carried it has
331    // none.
332    let document_context = receipt.get("@context");
333    let has_context = |item: &Value| {
334        item.as_object()
335            .and_then(|proof| proof.get("@context"))
336            .is_some_and(|ctx| Some(ctx) != document_context)
337    };
338    let proof_carries_context = match receipt.get("proof") {
339        Some(Value::Array(items)) => items.iter().any(has_context),
340        Some(item) => has_context(item),
341        None => false,
342    };
343    if proof_carries_context {
344        return (false, None);
345    }
346    // The receipt's proof must be the escrow's own assertion.
347    let bound = match (
348        crate::credentials::issuer_did(receipt),
349        receipt.get("proof"),
350    ) {
351        (Some(issuer), Some(proof)) => crate::credentials::proof_bound_to_issuer(proof, issuer),
352        _ => false,
353    };
354    if !bound {
355        return (false, None);
356    }
357    match data_integrity::verify_proof(receipt, escrow_public_key) {
358        Ok(true) => {}
359        _ => return (false, None),
360    }
361    let subject = match receipt.get("credentialSubject").and_then(|s| s.as_object()) {
362        Some(s) => s,
363        None => return (false, None),
364    };
365    let has_digest = subject
366        .get("committedDigest")
367        .and_then(|v| v.as_str())
368        .is_some_and(|s| !s.is_empty());
369    let has_agent = subject.get("agent").is_some_and(|v| v.is_string());
370    let has_deposited = subject
371        .get("depositedAt")
372        .and_then(|v| v.as_str())
373        .is_some_and(|s| parse_protocol_time_ns(s).is_ok());
374    if !has_digest || !has_agent || !has_deposited {
375        return (false, None);
376    }
377    (true, Some(Value::Object(subject.clone())))
378}
379
380// ---------------------------------------------------------------------------
381// Reasoned action credential: the executed action, carrying its commitment
382// ---------------------------------------------------------------------------
383
384/// Options for [`sign_reasoned_action`].
385#[derive(Debug, Clone, Default)]
386pub struct SignReasonedActionOptions {
387    /// If false, publish only the digest (private reasoning); reveal anchors out
388    /// of band at audit time. Defaults to true.
389    pub include_reasoning: bool,
390    /// Attach an escrow receipt proving the commitment was fixed before this
391    /// action.
392    pub escrow_receipt: Option<Value>,
393    /// The moment the intent was sealed. Read by the intent recheck. When escrow
394    /// is used this SHOULD equal the receipt's `depositedAt`; without escrow the
395    /// signer stamps it. Absent by default (backward compatible).
396    pub sealed_at: Option<String>,
397    /// The proof's `created`: the time of signing, as the reference stamps
398    /// it. None keeps `valid_from` (this call reads no clock; the JSON entry
399    /// gives the host clock).
400    pub created: Option<String>,
401}
402
403impl SignReasonedActionOptions {
404    pub fn new() -> Self {
405        Self {
406            include_reasoning: true,
407            escrow_receipt: None,
408            sealed_at: None,
409            created: None,
410        }
411    }
412}
413
414/// Issue a `ReasonedActionCredential`: the action bound to its justification.
415/// `valid_from` is the execution time and also the proof `created`.
416#[allow(clippy::too_many_arguments)]
417pub fn sign_reasoned_action(
418    seed: &[u8],
419    issuer_did: &str,
420    verification_method: &str,
421    intent: &Value,
422    justification: &Value,
423    valid_from: &str,
424    credential_id: &str,
425    opts: &SignReasonedActionOptions,
426) -> Result<Value> {
427    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent, justification, opts);
428    sign_reasoned_action_with(
429        Some(seed),
430        issuer_did,
431        verification_method,
432        intent,
433        justification,
434        valid_from,
435        credential_id,
436        opts,
437    )
438}
439
440/// [`sign_reasoned_action`] with the seed optional: without one the
441/// credential comes back unsigned, for a host whose key lives elsewhere to
442/// sign (proof `created` = `valid_from`, verificationMethod as given).
443#[allow(clippy::too_many_arguments)]
444pub fn sign_reasoned_action_with(
445    seed: Option<&[u8]>,
446    issuer_did: &str,
447    verification_method: &str,
448    intent: &Value,
449    justification: &Value,
450    valid_from: &str,
451    credential_id: &str,
452    opts: &SignReasonedActionOptions,
453) -> Result<Value> {
454    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent, justification, opts);
455    if !intent.is_object()
456        || intent.get("action").and_then(|v| v.as_str()).is_none()
457        || intent.get("target").and_then(|v| v.as_str()).is_none()
458    {
459        return Err(CoreError::Json(
460            "intent must be an object with at least action and target".into(),
461        ));
462    }
463    let digest = justification_digest(justification)?;
464
465    let mut commitment = Map::new();
466    commitment.insert(
467        "algorithm".into(),
468        Value::String(JUSTIFICATION_ALGORITHM.into()),
469    );
470    commitment.insert("digest".into(), Value::String(digest));
471
472    let mut jblock = Map::new();
473    jblock.insert("commitment".into(), Value::Object(commitment));
474    if let Some(sealed) = &opts.sealed_at {
475        jblock.insert("sealedAt".into(), Value::String(sealed.clone()));
476    }
477    if let Some(level) = justification.get("commitmentLevel") {
478        jblock.insert("commitmentLevel".into(), level.clone());
479    }
480    if let Some(receipt) = &opts.escrow_receipt {
481        jblock.insert("escrowReceipt".into(), receipt.clone());
482    }
483    if opts.include_reasoning {
484        let anchors = justification
485            .get("evidenceAnchors")
486            .cloned()
487            .unwrap_or_else(|| Value::Array(Vec::new()));
488        jblock.insert("evidenceAnchors".into(), anchors);
489    }
490
491    let mut subject = Map::new();
492    subject.insert("intent".into(), intent.clone());
493    subject.insert("justification".into(), Value::Object(jblock));
494
495    let mut credential = Map::new();
496    credential.insert(
497        "@context".into(),
498        Value::Array(vec![
499            Value::String(VC_CONTEXT_V2.into()),
500            Value::String(VOUCH_CONTEXT_V1.into()),
501        ]),
502    );
503    credential.insert(
504        "type".into(),
505        Value::Array(vec![
506            Value::String("VerifiableCredential".into()),
507            Value::String(REASONED_ACTION_TYPE.into()),
508        ]),
509    );
510    credential.insert("id".into(), Value::String(credential_id.to_string()));
511    credential.insert("issuer".into(), Value::String(issuer_did.to_string()));
512    credential.insert("validFrom".into(), Value::String(valid_from.to_string()));
513    credential.insert("credentialSubject".into(), Value::Object(subject));
514
515    let mut credential = Value::Object(credential);
516    let created = opts.created.as_deref().unwrap_or(valid_from);
517    attach_proof(&mut credential, seed, verification_method, created)?;
518    Ok(credential)
519}
520
521fn time_of(v: Option<&Value>) -> core::result::Result<i128, ()> {
522    match v.and_then(|v| v.as_str()) {
523        Some(s) => parse_protocol_time_ns(s).map_err(|_| ()),
524        None => Err(()),
525    }
526}
527
528/// The checks of [`check_reasoned_action_at`]; `clock` is the verifier's
529/// `(now, skew)` in nanoseconds, or `None` to skip the clock comparisons.
530/// The answer of [`check_reasoned_action`] for a credential the host could
531/// not hand over as it is (a value with no JSON form): not a reasoned action
532/// when its type says so, else `invalid_proof`, the reference's answer when it
533/// cannot compute the signing input. No signature is checked over the copy.
534pub fn check_unreadable_reasoned_action(credential: &Value) -> String {
535    crate::nesting::deep_guard!(crate::nesting::TOO_DEEP.into(); credential);
536    if !type_list(credential)
537        .iter()
538        .any(|t| t == REASONED_ACTION_TYPE)
539    {
540        return REASON_NOT_REASONED_ACTION.into();
541    }
542    REASON_INVALID_PROOF.into()
543}
544
545fn check_reasoned_action_inner(
546    credential: &Value,
547    public_key: &[u8],
548    escrow_public_key: Option<&[u8]>,
549    require_escrow: bool,
550    clock: Option<(i128, i128)>,
551) -> Option<String> {
552    if !type_list(credential)
553        .iter()
554        .any(|t| t == REASONED_ACTION_TYPE)
555    {
556        return Some(REASON_NOT_REASONED_ACTION.into());
557    }
558    let bound = match (
559        crate::credentials::issuer_did(credential),
560        credential.get("proof"),
561    ) {
562        (Some(issuer), Some(proof)) => crate::credentials::proof_bound_to_issuer(proof, issuer),
563        _ => false,
564    };
565    if !bound {
566        return Some(REASON_INVALID_PROOF.into());
567    }
568    match data_integrity::verify_proof(credential, public_key) {
569        Ok(true) => {}
570        _ => return Some(REASON_INVALID_PROOF.into()),
571    }
572
573    let jblock = credential
574        .get("credentialSubject")
575        .and_then(|s| s.get("justification"))
576        .filter(|j| j.is_object());
577    let Some(jblock) = jblock else {
578        return Some(REASON_MISSING_COMMITMENT.into());
579    };
580    let commitment_digest = jblock
581        .get("commitment")
582        .and_then(|c| c.get("digest"))
583        .and_then(|d| d.as_str());
584    let commitment_digest = match commitment_digest {
585        Some(d) if !d.is_empty() => d,
586        _ => return Some(REASON_MISSING_COMMITMENT.into()),
587    };
588
589    let Ok(executed) = time_of(credential.get("validFrom")) else {
590        return Some(REASON_MALFORMED_TIME.into());
591    };
592    let sealed = match jblock.get("sealedAt") {
593        None => None,
594        Some(v) => match time_of(Some(v)) {
595            Ok(t) => Some(t),
596            Err(()) => return Some(REASON_MALFORMED_TIME.into()),
597        },
598    };
599    if let Some(t) = sealed {
600        if t > executed {
601            return Some(REASON_SEAL_AFTER_EXECUTION.into());
602        }
603        if let Some((now, skew)) = clock {
604            if t > now + skew {
605                return Some(REASON_SEAL_IN_FUTURE.into());
606            }
607        }
608    }
609
610    let receipt = match jblock.get("escrowReceipt") {
611        None => {
612            return if require_escrow {
613                Some(REASON_MISSING_ESCROW.into())
614            } else {
615                None
616            };
617        }
618        Some(r) => r,
619    };
620    let escrow_key = match escrow_public_key {
621        Some(k) => k,
622        None => return Some(REASON_ESCROW_INVALID.into()),
623    };
624    let (ok, rsubject) = verify_escrow_receipt(receipt, escrow_key);
625    let Some(rsubject) = rsubject.filter(|_| ok) else {
626        return Some(REASON_ESCROW_INVALID.into());
627    };
628    // The receipt must witness THIS agent's commitment.
629    if rsubject.get("agent").and_then(|v| v.as_str()) != crate::credentials::issuer_did(credential)
630    {
631        return Some(REASON_ESCROW_AGENT_MISMATCH.into());
632    }
633    if rsubject.get("committedDigest").and_then(|v| v.as_str()) != Some(commitment_digest) {
634        return Some(REASON_ESCROW_DIGEST_MISMATCH.into());
635    }
636    let Ok(deposited) = time_of(rsubject.get("depositedAt")) else {
637        return Some(REASON_ESCROW_INVALID.into());
638    };
639    if let Some(t) = sealed {
640        if t > deposited {
641            return Some(REASON_SEAL_AFTER_DEPOSIT.into());
642        }
643    }
644    if deposited > executed {
645        return Some(REASON_ESCROW_AFTER_EXECUTION.into());
646    }
647    if let Some((now, skew)) = clock {
648        if deposited > now + skew {
649            return Some(REASON_SEAL_IN_FUTURE.into());
650        }
651    }
652    None
653}
654
655/// Verify a reasoned-action credential. Returns `None` on success or a
656/// structured reason string on failure. Checks, in order:
657///
658/// 1. The type, and the agent's proof (proofPurpose "assertionMethod", a key
659///    of the issuer's DID, valid under `public_key`): `invalid_proof`.
660/// 2. A commitment digest (`missing_commitment`); `validFrom` and any
661///    `sealedAt` follow the time grammar (`malformed_time`).
662/// 3. `sealedAt`, when present, is no later than `validFrom`
663///    (`seal_after_execution`).
664/// 4. With an escrow receipt: it verifies under `escrow_public_key`
665///    (`escrow_receipt_invalid`), names this credential's issuer as its agent
666///    (`escrow_agent_mismatch`) and its commitment (`escrow_digest_mismatch`);
667///    `sealedAt <= depositedAt` (`seal_after_deposit`) and `depositedAt <=
668///    validFrom` (`escrow_after_execution`).
669///
670/// This form has no clock; [`check_reasoned_action_at`] also refuses a seal
671/// later than the verifier's `now` plus skew (`seal_in_future`).
672pub fn check_reasoned_action(
673    credential: &Value,
674    public_key: &[u8],
675    escrow_public_key: Option<&[u8]>,
676    require_escrow: bool,
677) -> Option<String> {
678    crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
679    check_reasoned_action_inner(
680        credential,
681        public_key,
682        escrow_public_key,
683        require_escrow,
684        None,
685    )
686}
687
688/// [`check_reasoned_action`] with the verifier's clock: a `sealedAt` or a
689/// `depositedAt` later than `now_iso` plus the skew is refused
690/// (`seal_in_future`). Errors on a malformed `now_iso` or a skew outside
691/// 0..120 seconds (a caller error, not a verdict).
692pub fn check_reasoned_action_at(
693    credential: &Value,
694    public_key: &[u8],
695    escrow_public_key: Option<&[u8]>,
696    require_escrow: bool,
697    now_iso: &str,
698    clock_skew_seconds: i64,
699) -> Result<Option<String>> {
700    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
701    let skew = check_clock_skew(clock_skew_seconds)?;
702    let now = parse_protocol_time_ns(now_iso)?;
703    Ok(check_reasoned_action_inner(
704        credential,
705        public_key,
706        escrow_public_key,
707        require_escrow,
708        Some((now, skew)),
709    ))
710}
711
712/// Convenience wrapper over [`check_reasoned_action`] returning
713/// `(ok, credentialSubject)`.
714pub fn verify_reasoned_action(
715    credential: &Value,
716    public_key: &[u8],
717    escrow_public_key: Option<&[u8]>,
718    require_escrow: bool,
719) -> (bool, Option<Value>) {
720    crate::nesting::deep_guard!((false, None); credential);
721    if check_reasoned_action(credential, public_key, escrow_public_key, require_escrow).is_some() {
722        return (false, None);
723    }
724    (true, credential.get("credentialSubject").cloned())
725}
726
727/// Check a revealed justification against a verified credential's commitment: the
728/// justification must recompute to the committed digest, and every anchor must
729/// resolve (via `resolver`) to an artifact whose hash matches. Returns
730/// `(true, None)` on success, else `(false, Some(reason))`.
731pub fn verify_justification<F>(
732    presented_justification: &Value,
733    credential_subject: &Value,
734    resolver: F,
735) -> (bool, Option<String>)
736where
737    F: Fn(&str) -> Option<Value>,
738{
739    crate::nesting::deep_guard!((false, Some(crate::nesting::TOO_DEEP.into())); presented_justification, credential_subject);
740    let committed = credential_subject
741        .get("justification")
742        .and_then(|j| j.get("commitment"))
743        .and_then(|c| c.get("digest"))
744        .and_then(|d| d.as_str());
745    let committed = match committed {
746        Some(d) if !d.is_empty() => d,
747        _ => return (false, Some(REASON_MISSING_COMMITMENT.into())),
748    };
749
750    match justification_digest(presented_justification) {
751        Ok(d) if d == committed => {}
752        _ => return (false, Some(REASON_JUSTIFICATION_DIGEST_MISMATCH.into())),
753    }
754
755    let anchors = presented_justification
756        .get("evidenceAnchors")
757        .and_then(|a| a.as_array());
758    let anchors = match anchors {
759        Some(a) if !a.is_empty() => a,
760        _ => return (false, Some(REASON_UNANCHORED_CLAIM.into())),
761    };
762    for anchor in anchors {
763        let reference = anchor.get("ref").and_then(|v| v.as_str());
764        let artifact = reference.and_then(&resolver);
765        let artifact = match artifact {
766            Some(a) => a,
767            None => return (false, Some(REASON_EVIDENCE_UNRESOLVED.into())),
768        };
769        let expected = anchor.get("evidenceHash").and_then(|v| v.as_str());
770        match artifact_digest(&artifact) {
771            Ok(actual) if Some(actual.as_str()) == expected => {}
772            _ => return (false, Some(REASON_EVIDENCE_HASH_MISMATCH.into())),
773        }
774    }
775    (true, None)
776}
777
778// ---------------------------------------------------------------------------
779// Intent recheck: bind seal freshness to the action, not the interval alone
780// ---------------------------------------------------------------------------
781
782/// Where an action's execution time falls relative to the current pulse window
783/// `[last_pulse, last_pulse + interval)`.
784#[derive(Debug, Clone, Copy, PartialEq, Eq)]
785pub struct PulseWindow {
786    /// Execution is inside the current window (a pulse is not yet due).
787    pub in_window: bool,
788    /// Execution is in the gap past the window's end (the next pulse is overdue).
789    pub in_gap: bool,
790    /// Seconds from `last_pulse` to execution (negative if execution precedes it).
791    pub seconds_into_window: i64,
792}
793
794/// Classify an action's execution time against the pulse schedule. `last_pulse`
795/// is the issue time of the most recent heartbeat; `interval_seconds` is the
796/// heartbeat period.
797pub fn pulse_window(
798    last_pulse: &str,
799    interval_seconds: i64,
800    exec_time: &str,
801) -> Result<PulseWindow> {
802    let pulse = parse_protocol_time_ns(last_pulse)?;
803    let exec = parse_protocol_time_ns(exec_time)?;
804    let delta = exec - pulse;
805    let interval = seconds_to_ns(interval_seconds);
806    let in_window = delta >= 0 && delta < interval;
807    Ok(PulseWindow {
808        in_window,
809        in_gap: delta >= interval,
810        seconds_into_window: delta.div_euclid(1_000_000_000) as i64,
811    })
812}
813
814/// The freshness requirement a consequence tier imposes on an intent seal.
815#[derive(Debug, Clone, PartialEq, Eq)]
816pub struct FreshnessRequirement {
817    /// The seal must post-date the last pulse boundary (be sealed in the current
818    /// window), not merely predate execution.
819    pub require_fresh_seal: bool,
820    /// The seal must be at most this many seconds older than execution. `i64::MAX`
821    /// means no age bound.
822    pub max_age_seconds: i64,
823    /// A caller's own age limit when it is not a whole number of seconds
824    /// (a fraction, a negative number, a number past i64): it replaces
825    /// `max_age_seconds`.
826    pub max_age: Option<MaxAge>,
827}
828
829/// An age limit as a caller wrote it: the limit in nanoseconds the elapsed
830/// time is compared with (the floor of the reference's `max_age * 1e9`, which
831/// compares the same for a whole number of nanoseconds), and its text for the
832/// refusal.
833#[derive(Debug, Clone, PartialEq, Eq)]
834pub struct MaxAge {
835    pub limit_ns: i128,
836    pub text: String,
837}
838
839impl FreshnessRequirement {
840    pub const NONE: FreshnessRequirement = FreshnessRequirement {
841        require_fresh_seal: false,
842        max_age_seconds: i64::MAX,
843        max_age: None,
844    };
845}
846
847/// Consequence tiers, aligned with PAD-017 commitment levels (0..4) and the
848/// trust-entropy stakes bands. Higher tiers demand a fresher seal.
849pub const TIER_ROUTINE: i64 = 0;
850pub const TIER_LOW: i64 = 1;
851pub const TIER_MEDIUM: i64 = 2;
852pub const TIER_HIGH: i64 = 3;
853pub const TIER_CRITICAL: i64 = 4;
854
855/// Reference intent-freshness policy: routine/low/medium tiers inherit the last
856/// pulse's assurance; high and critical tiers require a seal sealed after the
857/// last pulse boundary, within a tightening max age. Deployments substitute their
858/// own thresholds; these are reference values.
859pub fn default_requirement(tier: i64) -> FreshnessRequirement {
860    match tier {
861        t if t >= TIER_CRITICAL => FreshnessRequirement {
862            require_fresh_seal: true,
863            max_age_seconds: 60,
864            max_age: None,
865        },
866        TIER_HIGH => FreshnessRequirement {
867            require_fresh_seal: true,
868            max_age_seconds: 300,
869            max_age: None,
870        },
871        _ => FreshnessRequirement::NONE,
872    }
873}
874
875/// Read the seal timestamp from a reasoned-action credential: the attached
876/// escrow receipt's `depositedAt` when there is a receipt (a neutral witness),
877/// else the justification's own `sealedAt`.
878///
879/// This reads the receipt without verifying it; [`recheck_intent_freshness`]
880/// verifies the receipt first and is what a verifier should call.
881pub fn seal_timestamp(credential: &Value) -> Option<String> {
882    crate::nesting::deep_guard!(None; credential);
883    let jblock = credential
884        .get("credentialSubject")
885        .and_then(|s| s.get("justification"))?;
886    // A receipt (an object) decides: its depositedAt, or nothing when it
887    // carries none, never the agent's own sealedAt.
888    if let Some(receipt) = jblock.get("escrowReceipt").filter(|r| r.is_object()) {
889        return receipt
890            .get("credentialSubject")
891            .and_then(|s| s.get("depositedAt"))
892            .and_then(|v| v.as_str())
893            .filter(|d| !d.is_empty())
894            .map(str::to_string);
895    }
896    jblock
897        .get("sealedAt")
898        .and_then(|v| v.as_str())
899        .filter(|s| !s.is_empty())
900        .map(|s| s.to_string())
901}
902
903/// The core intent-recheck rule. Given a seal time, the action's execution time,
904/// the last pulse boundary, and a tier's freshness requirement, return `None` if
905/// the seal is fresh enough, else a stable reason string.
906///
907/// - `intent_seal_stale:sealed_at=<t>,last_pulse=<t>`: a pulse boundary elapsed
908///   between sealing and execution; the action inherited a prior pulse's
909///   assurance. This is the timing-the-gap case.
910/// - `intent_seal_expired:sealed_at=<t>,max_age=<n>s`: the seal is within the
911///   current window but older than the tier's max age.
912///
913/// This compares the timestamps it is given; it does not know the verifier's
914/// clock or verify an escrow receipt. [`recheck_intent_freshness`] does both.
915pub fn check_seal_freshness(
916    sealed_at: &str,
917    exec_time: &str,
918    last_pulse: &str,
919    requirement: FreshnessRequirement,
920) -> Result<Option<String>> {
921    if !requirement.require_fresh_seal {
922        return Ok(None);
923    }
924    let sealed = parse_protocol_time_ns(sealed_at)?;
925    let exec = parse_protocol_time_ns(exec_time)?;
926    let pulse = parse_protocol_time_ns(last_pulse)?;
927    if sealed < pulse {
928        return Ok(Some(format!(
929            "{REASON_INTENT_SEAL_STALE}:sealed_at={sealed_at},last_pulse={last_pulse}"
930        )));
931    }
932    if let Some(limit) = &requirement.max_age {
933        if exec - sealed > limit.limit_ns {
934            return Ok(Some(format!(
935                "{REASON_INTENT_SEAL_EXPIRED}:sealed_at={sealed_at},max_age={}s",
936                limit.text
937            )));
938        }
939        return Ok(None);
940    }
941    if requirement.max_age_seconds != i64::MAX
942        && exec - sealed > seconds_to_ns(requirement.max_age_seconds)
943    {
944        return Ok(Some(format!(
945            "{REASON_INTENT_SEAL_EXPIRED}:sealed_at={sealed_at},max_age={}s",
946            requirement.max_age_seconds
947        )));
948    }
949    Ok(None)
950}
951
952/// Verify intent freshness for a reasoned-action credential at a given tier,
953/// without an escrow key or a clock. A tier that requires a fresh seal needs a
954/// verified escrow receipt, which this form cannot check, so it refuses
955/// (`intent_seal_missing:tier=<n>` with no receipt, else
956/// `escrow_receipt_invalid`); a tier with no requirement returns `None`. A
957/// verifier calls [`recheck_intent_freshness`].
958pub fn verify_intent_freshness(
959    credential: &Value,
960    tier: i64,
961    last_pulse: &str,
962    requirement: FreshnessRequirement,
963) -> Result<Option<String>> {
964    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
965    if !requirement.require_fresh_seal {
966        return Ok(None);
967    }
968    parse_protocol_time_ns(last_pulse)?;
969    let receipt = credential
970        .get("credentialSubject")
971        .and_then(|s| s.get("justification"))
972        .and_then(|j| j.get("escrowReceipt"));
973    Ok(Some(match receipt {
974        None => format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}"),
975        Some(_) => REASON_ESCROW_INVALID.to_string(),
976    }))
977}
978
979/// The intent recheck a verifier runs at a consequence tier. A tier that
980/// requires a fresh seal (high and critical in the reference policy) requires
981/// an escrow receipt, because the agent's own `sealedAt` is only its word; the
982/// seal time is the receipt's VERIFIED `depositedAt`. Checks, in order (the
983/// first failure is returned):
984///
985/// 1. No escrow receipt: `intent_seal_missing:tier=<n>`.
986/// 2. The receipt does not verify under `escrow_public_key`:
987///    `escrow_receipt_invalid`; it names another agent than the credential's
988///    issuer: `escrow_agent_mismatch`; it commits to another digest:
989///    `escrow_digest_mismatch`.
990/// 3. `validFrom` or `sealedAt` is malformed: `malformed_time`.
991/// 4. `sealedAt` is later than `depositedAt`: `seal_after_deposit`;
992///    `depositedAt` is later than `validFrom`: `escrow_after_execution`.
993/// 5. `depositedAt` is later than `now` + skew:
994///    `intent_seal_future:sealed_at=<depositedAt>`.
995/// 6. `validFrom` (the execution time) is not within `now` +/- skew:
996///    `intent_execution_not_current:valid_from=<validFrom>`.
997/// 7. [`check_seal_freshness`] with `depositedAt` as the seal time
998///    (`intent_seal_stale` / `intent_seal_expired`).
999///
1000/// This checks the escrow receipt's signature, not the agent's own proof: run
1001/// [`check_reasoned_action_at`] for that. Returns `None` when accepted (or the
1002/// tier imposes no requirement). Errors on a malformed `now`, `last_pulse` or a
1003/// skew outside 0..120 seconds.
1004#[allow(clippy::too_many_arguments)]
1005pub fn recheck_intent_freshness(
1006    credential: &Value,
1007    tier: i64,
1008    last_pulse: &str,
1009    requirement: FreshnessRequirement,
1010    now_iso: &str,
1011    clock_skew_seconds: i64,
1012    escrow_public_key: Option<&[u8]>,
1013) -> Result<Option<String>> {
1014    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
1015    recheck_intent_freshness_with(
1016        credential,
1017        tier,
1018        last_pulse,
1019        requirement,
1020        now_iso,
1021        clock_skew_seconds,
1022        escrow_public_key,
1023        false,
1024    )
1025}
1026
1027/// [`recheck_intent_freshness`] for a host whose receipt had no JSON form
1028/// (`receipt_unreadable`): the host sends the credential with those values
1029/// as null, and the receipt never verifies (`escrow_receipt_invalid` at its
1030/// step); its signature is never checked over the changed copy.
1031#[allow(clippy::too_many_arguments)]
1032pub fn recheck_intent_freshness_with(
1033    credential: &Value,
1034    tier: i64,
1035    last_pulse: &str,
1036    requirement: FreshnessRequirement,
1037    now_iso: &str,
1038    clock_skew_seconds: i64,
1039    escrow_public_key: Option<&[u8]>,
1040    receipt_unreadable: bool,
1041) -> Result<Option<String>> {
1042    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
1043    if !requirement.require_fresh_seal {
1044        return Ok(None);
1045    }
1046    let skew = check_clock_skew(clock_skew_seconds)?;
1047    let now = parse_protocol_time_ns(now_iso)?;
1048    parse_protocol_time_ns(last_pulse)?;
1049
1050    let jblock = credential
1051        .get("credentialSubject")
1052        .and_then(|s| s.get("justification"))
1053        .filter(|j| j.is_object());
1054    let Some(receipt) = jblock.and_then(|j| j.get("escrowReceipt")) else {
1055        return Ok(Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}")));
1056    };
1057    let (ok, rsubject) = match escrow_public_key {
1058        Some(_) if receipt_unreadable => (false, None),
1059        Some(k) => verify_escrow_receipt(receipt, k),
1060        None => (false, None),
1061    };
1062    let Some(rsubject) = rsubject.filter(|_| ok) else {
1063        return Ok(Some(REASON_ESCROW_INVALID.into()));
1064    };
1065    if rsubject.get("agent").and_then(|v| v.as_str()) != crate::credentials::issuer_did(credential)
1066    {
1067        return Ok(Some(REASON_ESCROW_AGENT_MISMATCH.into()));
1068    }
1069    let digest = jblock
1070        .and_then(|j| j.get("commitment"))
1071        .and_then(|c| c.get("digest"))
1072        .and_then(|d| d.as_str())
1073        .filter(|d| !d.is_empty());
1074    if digest.is_none() || rsubject.get("committedDigest").and_then(|v| v.as_str()) != digest {
1075        return Ok(Some(REASON_ESCROW_DIGEST_MISMATCH.into()));
1076    }
1077
1078    let exec_str = credential
1079        .get("validFrom")
1080        .and_then(|v| v.as_str())
1081        .unwrap_or_default();
1082    let deposited_str = rsubject
1083        .get("depositedAt")
1084        .and_then(|v| v.as_str())
1085        .unwrap_or_default()
1086        .to_string();
1087    let (Ok(executed), Ok(deposited)) = (
1088        time_of(credential.get("validFrom")),
1089        time_of(rsubject.get("depositedAt")),
1090    ) else {
1091        return Ok(Some(REASON_MALFORMED_TIME.into()));
1092    };
1093    let sealed = match jblock.and_then(|j| j.get("sealedAt")) {
1094        None => None,
1095        Some(v) => match time_of(Some(v)) {
1096            Ok(t) => Some(t),
1097            Err(()) => return Ok(Some(REASON_MALFORMED_TIME.into())),
1098        },
1099    };
1100    if sealed.is_some_and(|t| t > deposited) {
1101        return Ok(Some(REASON_SEAL_AFTER_DEPOSIT.into()));
1102    }
1103    if deposited > executed {
1104        return Ok(Some(REASON_ESCROW_AFTER_EXECUTION.into()));
1105    }
1106    if deposited > now + skew {
1107        return Ok(Some(format!(
1108            "{REASON_INTENT_SEAL_FUTURE}:sealed_at={deposited_str}"
1109        )));
1110    }
1111    if (executed - now).abs() > skew {
1112        return Ok(Some(format!(
1113            "{REASON_INTENT_EXECUTION_NOT_CURRENT}:valid_from={exec_str}"
1114        )));
1115    }
1116    check_seal_freshness(&deposited_str, exec_str, last_pulse, requirement)
1117}
1118
1119/// Execution-time reseal helper: seal the intent right now and issue a fresh
1120/// `ReasonedActionCredential` whose `sealedAt` and `validFrom` are both `now`, so
1121/// a sensitive action carries a seal made in the current pulse window. Reuses
1122/// [`build_justification`] and [`sign_reasoned_action`]; no new cryptography.
1123#[allow(clippy::too_many_arguments)]
1124pub fn reseal_intent(
1125    seed: &[u8],
1126    issuer_did: &str,
1127    verification_method: &str,
1128    intent: &Value,
1129    anchors: &[Value],
1130    commitment_level: Option<i64>,
1131    now: &str,
1132    credential_id: &str,
1133    include_reasoning: bool,
1134) -> Result<Value> {
1135    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent, anchors);
1136    reseal_intent_with(
1137        Some(seed),
1138        issuer_did,
1139        verification_method,
1140        intent,
1141        anchors,
1142        commitment_level,
1143        now,
1144        credential_id,
1145        include_reasoning,
1146        None,
1147    )
1148}
1149
1150/// [`reseal_intent`] with the seed optional (unsigned without one) and the
1151/// proof's `created`, the time of signing (None keeps `now`).
1152#[allow(clippy::too_many_arguments)]
1153pub fn reseal_intent_with(
1154    seed: Option<&[u8]>,
1155    issuer_did: &str,
1156    verification_method: &str,
1157    intent: &Value,
1158    anchors: &[Value],
1159    commitment_level: Option<i64>,
1160    now: &str,
1161    credential_id: &str,
1162    include_reasoning: bool,
1163    created: Option<&str>,
1164) -> Result<Value> {
1165    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent, anchors);
1166    let justification = build_justification(intent, anchors, commitment_level)?;
1167    let opts = SignReasonedActionOptions {
1168        include_reasoning,
1169        escrow_receipt: None,
1170        sealed_at: Some(now.to_string()),
1171        created: created.map(str::to_string),
1172    };
1173    sign_reasoned_action_with(
1174        seed,
1175        issuer_did,
1176        verification_method,
1177        intent,
1178        &justification,
1179        now,
1180        credential_id,
1181        &opts,
1182    )
1183}
1184
1185// What the no_std depth guard checks in the JSON these types carry.
1186crate::nesting::nested_fields!(SignReasonedActionOptions; escrow_receipt);
1187
1188#[cfg(test)]
1189mod tests {
1190    use super::*;
1191    use crate::keys::Ed25519KeyPair;
1192    use serde_json::json;
1193
1194    fn seed() -> [u8; 32] {
1195        [7u8; 32]
1196    }
1197
1198    fn pubkey() -> [u8; 32] {
1199        Ed25519KeyPair::from_seed_slice(&seed())
1200            .unwrap()
1201            .public_key()
1202    }
1203
1204    fn sample_intent() -> Value {
1205        json!({"action": "transfer_funds", "target": "account:9911", "resource": "https://bank.example/v1/xfer"})
1206    }
1207
1208    fn sample_justification() -> Value {
1209        let anchor = evidence_anchor(
1210            "user approved the transfer",
1211            "urn:msg:42",
1212            Some(&json!({"text": "please move $500 to savings"})),
1213            None,
1214            "user_message",
1215        )
1216        .unwrap();
1217        build_justification(&sample_intent(), &[anchor], Some(TIER_HIGH)).unwrap()
1218    }
1219
1220    #[test]
1221    fn justification_digest_is_multibase_b64url() {
1222        let d = justification_digest(&sample_justification()).unwrap();
1223        assert!(d.starts_with('u'));
1224    }
1225
1226    #[test]
1227    fn sign_then_verify_reasoned_action() {
1228        let cred = sign_reasoned_action(
1229            &seed(),
1230            "did:web:agent.example",
1231            "did:web:agent.example#key-1",
1232            &sample_intent(),
1233            &sample_justification(),
1234            "2026-08-02T10:00:00Z",
1235            "urn:uuid:11111111-1111-1111-1111-111111111111",
1236            &SignReasonedActionOptions::new(),
1237        )
1238        .unwrap();
1239        assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
1240        assert_eq!(
1241            check_reasoned_action(&cred, &pubkey(), None, true),
1242            Some(REASON_MISSING_ESCROW.into())
1243        );
1244    }
1245
1246    #[test]
1247    fn tampered_action_fails() {
1248        let mut cred = sign_reasoned_action(
1249            &seed(),
1250            "did:web:agent.example",
1251            "did:web:agent.example#key-1",
1252            &sample_intent(),
1253            &sample_justification(),
1254            "2026-08-02T10:00:00Z",
1255            "urn:uuid:11111111-1111-1111-1111-111111111111",
1256            &SignReasonedActionOptions::new(),
1257        )
1258        .unwrap();
1259        cred["credentialSubject"]["intent"]["action"] = json!("drain_account");
1260        assert_eq!(
1261            check_reasoned_action(&cred, &pubkey(), None, false),
1262            Some(REASON_INVALID_PROOF.into())
1263        );
1264    }
1265
1266    #[test]
1267    fn pulse_window_classifies_window_and_gap() {
1268        // interval 60s, last pulse at 10:00:00.
1269        let w = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:00:30Z").unwrap();
1270        assert!(w.in_window && !w.in_gap);
1271        let g = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:02:00Z").unwrap();
1272        assert!(g.in_gap && !g.in_window);
1273    }
1274
1275    // --- Intent recheck acceptance/rejection matrix ---
1276
1277    fn reasoned_with_seal(sealed_at: &str, exec: &str, level: i64) -> Value {
1278        let anchor = evidence_anchor(
1279            "user approved",
1280            "urn:msg:42",
1281            Some(&json!({"text": "go"})),
1282            None,
1283            "user_message",
1284        )
1285        .unwrap();
1286        let just = build_justification(&sample_intent(), &[anchor], Some(level)).unwrap();
1287        let opts = SignReasonedActionOptions {
1288            include_reasoning: true,
1289            escrow_receipt: None,
1290            sealed_at: Some(sealed_at.to_string()),
1291            created: None,
1292        };
1293        sign_reasoned_action(
1294            &seed(),
1295            "did:web:agent.example",
1296            "did:web:agent.example#key-1",
1297            &sample_intent(),
1298            &just,
1299            exec,
1300            "urn:uuid:22222222-2222-2222-2222-222222222222",
1301            &opts,
1302        )
1303        .unwrap()
1304    }
1305
1306    #[test]
1307    fn agent_seal_alone_does_not_meet_a_high_tier() {
1308        // High tier, sealed at 10:00:10 by the agent itself, no escrow receipt:
1309        // the agent's own word is not a witnessed seal.
1310        let cred = reasoned_with_seal("2026-08-02T10:00:10Z", "2026-08-02T10:00:20Z", TIER_HIGH);
1311        let r = recheck_intent_freshness(
1312            &cred,
1313            TIER_HIGH,
1314            "2026-08-02T10:00:00Z",
1315            default_requirement(TIER_HIGH),
1316            "2026-08-02T10:00:20Z",
1317            30,
1318            Some(&pubkey()),
1319        )
1320        .unwrap();
1321        assert_eq!(
1322            r,
1323            Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_HIGH}"))
1324        );
1325    }
1326
1327    #[test]
1328    fn stale_seal_across_boundary_rejects() {
1329        // Sealed 09:59:50 (before the 10:00:00 pulse), executed at 10:00:20 in
1330        // the gap after the boundary: the timestamp rule refuses it.
1331        let r = check_seal_freshness(
1332            "2026-08-02T09:59:50Z",
1333            "2026-08-02T10:00:20Z",
1334            "2026-08-02T10:00:00Z",
1335            default_requirement(TIER_HIGH),
1336        )
1337        .unwrap();
1338        assert_eq!(
1339            r,
1340            Some(
1341                "intent_seal_stale:sealed_at=2026-08-02T09:59:50Z,last_pulse=2026-08-02T10:00:00Z"
1342                    .into()
1343            )
1344        );
1345        assert_eq!(
1346            check_seal_freshness(
1347                "2026-08-02T10:00:10Z",
1348                "2026-08-02T10:00:20Z",
1349                "2026-08-02T10:00:00Z",
1350                default_requirement(TIER_HIGH),
1351            )
1352            .unwrap(),
1353            None
1354        );
1355    }
1356
1357    #[test]
1358    fn reseal_in_gap_is_a_valid_action() {
1359        // Even executing at 10:05:00, a reseal at 10:05:00 with a pulse boundary
1360        // advanced to 10:05:00 is fresh.
1361        let cred = reseal_intent(
1362            &seed(),
1363            "did:web:agent.example",
1364            "did:web:agent.example#key-1",
1365            &sample_intent(),
1366            &[evidence_anchor(
1367                "user approved",
1368                "urn:msg:42",
1369                Some(&json!({"text": "go"})),
1370                None,
1371                "user_message",
1372            )
1373            .unwrap()],
1374            Some(TIER_HIGH),
1375            "2026-08-02T10:05:00Z",
1376            "urn:uuid:33333333-3333-3333-3333-333333333333",
1377            true,
1378        )
1379        .unwrap();
1380        // The reseal itself is a valid action credential; a high tier still
1381        // needs an escrow receipt for the seal.
1382        assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
1383        let r = verify_intent_freshness(
1384            &cred,
1385            TIER_HIGH,
1386            "2026-08-02T10:05:00Z",
1387            default_requirement(TIER_HIGH),
1388        )
1389        .unwrap();
1390        assert_eq!(
1391            r,
1392            Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_HIGH}"))
1393        );
1394    }
1395
1396    #[test]
1397    fn non_sensitive_tier_ignores_stale_seal() {
1398        // Same stale seal, but a routine tier does not require freshness.
1399        let cred = reasoned_with_seal("2026-08-02T09:59:50Z", "2026-08-02T10:00:20Z", TIER_ROUTINE);
1400        let r = verify_intent_freshness(
1401            &cred,
1402            TIER_ROUTINE,
1403            "2026-08-02T10:00:00Z",
1404            default_requirement(TIER_ROUTINE),
1405        )
1406        .unwrap();
1407        assert_eq!(r, None);
1408    }
1409
1410    #[test]
1411    fn sensitive_tier_without_seal_is_missing() {
1412        // A high-tier action with no seal timestamp at all.
1413        let cred = sign_reasoned_action(
1414            &seed(),
1415            "did:web:agent.example",
1416            "did:web:agent.example#key-1",
1417            &sample_intent(),
1418            &sample_justification(),
1419            "2026-08-02T10:00:20Z",
1420            "urn:uuid:44444444-4444-4444-4444-444444444444",
1421            &SignReasonedActionOptions::new(),
1422        )
1423        .unwrap();
1424        let r = verify_intent_freshness(
1425            &cred,
1426            TIER_HIGH,
1427            "2026-08-02T10:00:00Z",
1428            default_requirement(TIER_HIGH),
1429        )
1430        .unwrap();
1431        assert_eq!(r, Some("intent_seal_missing:tier=3".into()));
1432    }
1433
1434    #[test]
1435    fn escrow_roundtrip_and_seal_from_deposit() {
1436        let escrow_seed = [3u8; 32];
1437        let escrow_pub = Ed25519KeyPair::from_seed_slice(&escrow_seed)
1438            .unwrap()
1439            .public_key();
1440        let digest = justification_digest(&sample_justification()).unwrap();
1441        let receipt = build_escrow_receipt(
1442            &escrow_seed,
1443            "did:web:escrow.example",
1444            "did:web:escrow.example#key-1",
1445            "did:web:agent.example",
1446            &digest,
1447            "2026-08-02T10:00:05Z",
1448            "urn:uuid:55555555-5555-5555-5555-555555555555",
1449        )
1450        .unwrap();
1451        let (ok, _) = verify_escrow_receipt(&receipt, &escrow_pub);
1452        assert!(ok);
1453
1454        // The escrow writes the receipt's @context into its proof. The same
1455        // signed receipt without it (the form written before proofs carried
1456        // it) still verifies.
1457        let context = receipt["@context"].clone();
1458        assert_eq!(receipt["proof"]["@context"], context);
1459        let mut older = receipt.clone();
1460        older["proof"].as_object_mut().unwrap().remove("@context");
1461        assert!(verify_escrow_receipt(&older, &escrow_pub).0);
1462        // A proof @context that is only the start of the receipt's passes
1463        // general Data Integrity verification, but the escrow receipt check
1464        // takes only an exact copy.
1465        let mut second = receipt.clone();
1466        {
1467            let proof = second["proof"].as_object_mut().unwrap();
1468            proof.remove("proofValue");
1469            proof.insert("@context".into(), json!([context[0].clone()]));
1470        }
1471        let unsigned = second["proof"].as_object().unwrap().clone();
1472        let input = data_integrity::hash_data(&second, &unsigned).unwrap();
1473        let sig = Ed25519KeyPair::from_seed(&escrow_seed).sign(&input);
1474        second["proof"]["proofValue"] = json!(format!("z{}", bs58::encode(sig).into_string()));
1475        assert!(data_integrity::verify_proof(&second, &escrow_pub).unwrap());
1476        assert_eq!(verify_escrow_receipt(&second, &escrow_pub), (false, None));
1477        let mut in_a_list = receipt.clone();
1478        let mut listed = in_a_list["proof"].clone();
1479        listed["@context"] = json!(["https://example.com/other"]);
1480        in_a_list["proof"] = Value::Array(vec![listed]);
1481        assert_eq!(
1482            verify_escrow_receipt(&in_a_list, &escrow_pub),
1483            (false, None)
1484        );
1485
1486        let opts = SignReasonedActionOptions {
1487            include_reasoning: true,
1488            escrow_receipt: Some(receipt),
1489            sealed_at: None,
1490            created: None,
1491        };
1492        let cred = sign_reasoned_action(
1493            &seed(),
1494            "did:web:agent.example",
1495            "did:web:agent.example#key-1",
1496            &sample_intent(),
1497            &sample_justification(),
1498            "2026-08-02T10:00:20Z",
1499            "urn:uuid:66666666-6666-6666-6666-666666666666",
1500            &opts,
1501        )
1502        .unwrap();
1503        // Seal timestamp falls back to the escrow depositedAt.
1504        assert_eq!(
1505            seal_timestamp(&cred).as_deref(),
1506            Some("2026-08-02T10:00:05Z")
1507        );
1508        assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub), true).is_none());
1509    }
1510
1511    // --- Recheck against a verified escrow receipt and the verifier's clock ---
1512
1513    fn escrow_seed() -> [u8; 32] {
1514        [9u8; 32]
1515    }
1516
1517    fn escrow_pub() -> [u8; 32] {
1518        Ed25519KeyPair::from_seed(&escrow_seed()).public_key()
1519    }
1520
1521    /// A critical-tier action executed at `exec`, carrying an escrow receipt
1522    /// deposited at `deposited` for `agent`, and (optionally) the agent's own
1523    /// `sealedAt`.
1524    fn escrowed(agent: &str, deposited: &str, exec: &str, sealed: Option<&str>) -> Value {
1525        let just = sample_justification();
1526        let digest = justification_digest(&just).unwrap();
1527        let receipt = build_escrow_receipt(
1528            &escrow_seed(),
1529            "did:web:escrow.example",
1530            "did:web:escrow.example#key-1",
1531            agent,
1532            &digest,
1533            deposited,
1534            "urn:uuid:33333333-3333-3333-3333-333333333333",
1535        )
1536        .unwrap();
1537        let opts = SignReasonedActionOptions {
1538            include_reasoning: true,
1539            escrow_receipt: Some(receipt),
1540            sealed_at: sealed.map(String::from),
1541            created: None,
1542        };
1543        sign_reasoned_action(
1544            &seed(),
1545            "did:web:agent.example",
1546            "did:web:agent.example#key-1",
1547            &sample_intent(),
1548            &just,
1549            exec,
1550            "urn:uuid:44444444-4444-4444-4444-444444444444",
1551            &opts,
1552        )
1553        .unwrap()
1554    }
1555
1556    fn recheck(cred: &Value, now: &str) -> Option<String> {
1557        recheck_intent_freshness(
1558            cred,
1559            TIER_CRITICAL,
1560            "2026-04-26T10:00:00Z",
1561            default_requirement(TIER_CRITICAL),
1562            now,
1563            30,
1564            Some(&escrow_pub()),
1565        )
1566        .unwrap()
1567    }
1568
1569    #[test]
1570    fn recheck_accepts_a_fresh_witnessed_seal() {
1571        let cred = escrowed(
1572            "did:web:agent.example",
1573            "2026-04-26T10:02:30Z",
1574            "2026-04-26T10:03:00Z",
1575            None,
1576        );
1577        assert_eq!(recheck(&cred, "2026-04-26T10:03:05Z"), None);
1578        assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub()), true).is_none());
1579    }
1580
1581    #[test]
1582    fn recheck_uses_the_escrow_time_not_the_agents_claim() {
1583        // Deposited before the pulse; the agent claims a fresh sealedAt.
1584        let honest = escrowed(
1585            "did:web:agent.example",
1586            "2026-04-26T09:55:00Z",
1587            "2026-04-26T10:03:00Z",
1588            None,
1589        );
1590        assert!(recheck(&honest, "2026-04-26T10:03:00Z")
1591            .unwrap()
1592            .starts_with(REASON_INTENT_SEAL_STALE));
1593        let lying = escrowed(
1594            "did:web:agent.example",
1595            "2026-04-26T09:55:00Z",
1596            "2026-04-26T10:03:00Z",
1597            Some("2026-04-26T10:02:30Z"),
1598        );
1599        assert_eq!(
1600            recheck(&lying, "2026-04-26T10:03:00Z"),
1601            Some(REASON_SEAL_AFTER_DEPOSIT.into())
1602        );
1603        assert_eq!(
1604            check_reasoned_action(&lying, &pubkey(), Some(&escrow_pub()), true),
1605            Some(REASON_SEAL_AFTER_DEPOSIT.into())
1606        );
1607        // The form without an escrow key cannot verify a receipt, so it refuses.
1608        let old = verify_intent_freshness(
1609            &lying,
1610            TIER_CRITICAL,
1611            "2026-04-26T10:00:00Z",
1612            default_requirement(TIER_CRITICAL),
1613        )
1614        .unwrap();
1615        assert_eq!(old, Some(REASON_ESCROW_INVALID.into()));
1616    }
1617
1618    #[test]
1619    fn recheck_refuses_forward_dated_and_late_seals() {
1620        let future = escrowed(
1621            "did:web:agent.example",
1622            "2099-01-01T00:00:00Z",
1623            "2099-01-01T00:00:00Z",
1624            Some("2099-01-01T00:00:00Z"),
1625        );
1626        assert_eq!(
1627            recheck(&future, "2026-04-26T10:03:00Z"),
1628            Some(format!(
1629                "{REASON_INTENT_SEAL_FUTURE}:sealed_at=2099-01-01T00:00:00Z"
1630            ))
1631        );
1632        assert_eq!(
1633            check_reasoned_action_at(
1634                &future,
1635                &pubkey(),
1636                Some(&escrow_pub()),
1637                true,
1638                "2026-04-26T10:03:00Z",
1639                30
1640            )
1641            .unwrap(),
1642            Some(REASON_SEAL_IN_FUTURE.into())
1643        );
1644        // Deposited after execution.
1645        let late = escrowed(
1646            "did:web:agent.example",
1647            "2026-04-26T10:10:00Z",
1648            "2026-04-26T10:03:00Z",
1649            None,
1650        );
1651        assert_eq!(
1652            recheck(&late, "2026-04-26T10:03:00Z"),
1653            Some(REASON_ESCROW_AFTER_EXECUTION.into())
1654        );
1655        // A seal later than the verifier's clock.
1656        let ahead = escrowed(
1657            "did:web:agent.example",
1658            "2026-04-26T10:03:20Z",
1659            "2026-04-26T10:03:20Z",
1660            None,
1661        );
1662        assert_eq!(recheck(&ahead, "2026-04-26T10:03:00Z"), None, "inside skew");
1663        assert!(recheck(&ahead, "2026-04-26T10:02:40Z").is_some());
1664        // An agent seal made after execution is refused, escrow or not.
1665        let after =
1666            reasoned_with_seal("2026-04-26T10:10:00Z", "2026-04-26T10:03:00Z", TIER_ROUTINE);
1667        assert_eq!(
1668            check_reasoned_action(&after, &pubkey(), None, false),
1669            Some(REASON_SEAL_AFTER_EXECUTION.into())
1670        );
1671        // Executed well away from the verifier's clock.
1672        let fresh = escrowed(
1673            "did:web:agent.example",
1674            "2026-04-26T10:02:30Z",
1675            "2026-04-26T10:03:00Z",
1676            None,
1677        );
1678        assert_eq!(
1679            recheck(&fresh, "2026-04-26T10:09:00Z"),
1680            Some(format!(
1681                "{REASON_INTENT_EXECUTION_NOT_CURRENT}:valid_from=2026-04-26T10:03:00Z"
1682            ))
1683        );
1684    }
1685
1686    #[test]
1687    fn recheck_binds_the_receipt_to_the_agent_and_key() {
1688        let stolen = escrowed(
1689            "did:web:someone-else.example",
1690            "2026-04-26T10:02:30Z",
1691            "2026-04-26T10:03:00Z",
1692            None,
1693        );
1694        assert_eq!(
1695            recheck(&stolen, "2026-04-26T10:03:00Z"),
1696            Some(REASON_ESCROW_AGENT_MISMATCH.into())
1697        );
1698        assert_eq!(
1699            check_reasoned_action(&stolen, &pubkey(), Some(&escrow_pub()), true),
1700            Some(REASON_ESCROW_AGENT_MISMATCH.into())
1701        );
1702        let good = escrowed(
1703            "did:web:agent.example",
1704            "2026-04-26T10:02:30Z",
1705            "2026-04-26T10:03:00Z",
1706            None,
1707        );
1708        // Wrong escrow key, no escrow key, no receipt at a critical tier.
1709        let wrong = recheck_intent_freshness(
1710            &good,
1711            TIER_CRITICAL,
1712            "2026-04-26T10:00:00Z",
1713            default_requirement(TIER_CRITICAL),
1714            "2026-04-26T10:03:00Z",
1715            30,
1716            Some(&pubkey()),
1717        )
1718        .unwrap();
1719        assert_eq!(wrong, Some(REASON_ESCROW_INVALID.into()));
1720        let none = recheck_intent_freshness(
1721            &good,
1722            TIER_CRITICAL,
1723            "2026-04-26T10:00:00Z",
1724            default_requirement(TIER_CRITICAL),
1725            "2026-04-26T10:03:00Z",
1726            30,
1727            None,
1728        )
1729        .unwrap();
1730        assert_eq!(none, Some(REASON_ESCROW_INVALID.into()));
1731        let bare = reasoned_with_seal(
1732            "2026-04-26T10:02:30Z",
1733            "2026-04-26T10:03:00Z",
1734            TIER_CRITICAL,
1735        );
1736        assert_eq!(
1737            recheck(&bare, "2026-04-26T10:03:00Z"),
1738            Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_CRITICAL}"))
1739        );
1740        // A skew outside 0..120 seconds is a caller error.
1741        assert!(recheck_intent_freshness(
1742            &good,
1743            TIER_CRITICAL,
1744            "2026-04-26T10:00:00Z",
1745            default_requirement(TIER_CRITICAL),
1746            "2026-04-26T10:03:00Z",
1747            121,
1748            Some(&escrow_pub()),
1749        )
1750        .is_err());
1751    }
1752
1753    #[test]
1754    fn proof_bound_to_another_did_is_refused() {
1755        let cred = sign_reasoned_action(
1756            &seed(),
1757            "did:web:agent.example",
1758            "did:web:other.example#key-1",
1759            &sample_intent(),
1760            &sample_justification(),
1761            "2026-08-02T10:00:00Z",
1762            "urn:uuid:11111111-1111-1111-1111-111111111111",
1763            &SignReasonedActionOptions::new(),
1764        )
1765        .unwrap();
1766        assert_eq!(
1767            check_reasoned_action(&cred, &pubkey(), None, false),
1768            Some(REASON_INVALID_PROOF.into())
1769        );
1770    }
1771}