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