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