vouch-core 4.1.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
//! Reasoned Action Proofs and event-triggered intent recheck.
//!
//! A standard credential answers *who* acted and *under what authority*. It says
//! nothing about *why*. This module adds the missing "why" layer: before acting,
//! an agent states a structured **justification** (an intent plus a set of
//! **evidence anchors**, each a claim tied to a real artifact by that artifact's
//! hash). The justification is committed by digest, optionally deposited with a
//! neutral **escrow** that timestamps it, and the executed action credential
//! carries the commitment. Three properties then hold: no fabrication (each
//! reason names an artifact a verifier re-resolves and hashes), no post-hoc
//! rewrite (the credential carries the digest), and, with escrow, committed
//! before execution (the deposit time is not after execution).
//!
//! This is the canonical port of the Python reference `vouch/reasoning.py`. The
//! digest algorithm and every stable reason string match byte for byte, so a
//! seal built in one language verifies in another. Everything here is an ordinary
//! `eddsa-jcs-2022` Verifiable Credential.
//!
//! ## Intent recheck (event-triggered)
//!
//! A heartbeat proves the agent is alive across an interval; it does not prove the
//! agent's intent is current at the moment of a sensitive action. A justification
//! sealed early in an interval still passes for an action executed much later in
//! the same interval, so a sophisticated actor can time a sensitive action to land
//! after a pulse boundary while reusing an intent sealed before it. The intent
//! recheck binds seal freshness to the action: for a sensitive consequence tier
//! the seal must post-date the last pulse boundary and be within a configurable
//! max age, not merely predate execution. See [`verify_intent_freshness`] and
//! [`reseal_intent`].

use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

use crate::data_integrity::{self, BuildProofOptions};
use crate::error::{CoreError, Result};
use crate::jcs;
use crate::time::{check_clock_skew, parse_protocol_time_ns, seconds_to_ns};

pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";

pub const REASONED_ACTION_TYPE: &str = "ReasonedActionCredential";
pub const ESCROW_RECEIPT_TYPE: &str = "JustificationEscrowReceipt";

pub const JUSTIFICATION_ALGORITHM: &str = "sha-256-jcs";

// Structured verification reasons (stable strings, mirrored by every SDK).
pub const REASON_INVALID_PROOF: &str = "invalid_proof";
pub const REASON_NOT_REASONED_ACTION: &str = "not_reasoned_action";
pub const REASON_MISSING_COMMITMENT: &str = "missing_commitment";
pub const REASON_MISSING_ESCROW: &str = "missing_escrow";
pub const REASON_ESCROW_INVALID: &str = "escrow_receipt_invalid";
pub const REASON_ESCROW_DIGEST_MISMATCH: &str = "escrow_digest_mismatch";
pub const REASON_ESCROW_AFTER_EXECUTION: &str = "escrow_after_execution";
pub const REASON_JUSTIFICATION_DIGEST_MISMATCH: &str = "justification_digest_mismatch";
pub const REASON_EVIDENCE_UNRESOLVED: &str = "evidence_unresolved";
pub const REASON_EVIDENCE_HASH_MISMATCH: &str = "evidence_hash_mismatch";
pub const REASON_UNANCHORED_CLAIM: &str = "unanchored_claim";

// Intent-recheck reasons (stable prefixes; carry a structured suffix).
pub const REASON_INTENT_SEAL_STALE: &str = "intent_seal_stale";
pub const REASON_INTENT_SEAL_EXPIRED: &str = "intent_seal_expired";
pub const REASON_INTENT_SEAL_MISSING: &str = "intent_seal_missing";
/// The receipt names another agent than the credential's issuer.
pub const REASON_ESCROW_AGENT_MISMATCH: &str = "escrow_agent_mismatch";
/// The agent's own `sealedAt` is later than the escrow's `depositedAt`.
pub const REASON_SEAL_AFTER_DEPOSIT: &str = "seal_after_deposit";
/// The agent's own `sealedAt` is later than the execution time (`validFrom`).
pub const REASON_SEAL_AFTER_EXECUTION: &str = "seal_after_execution";
/// A seal is later than the verifier's clock plus skew.
pub const REASON_SEAL_IN_FUTURE: &str = "seal_in_future";
/// `validFrom`, `sealedAt` or `depositedAt` does not follow the time grammar.
pub const REASON_MALFORMED_TIME: &str = "malformed_time";
/// Intent recheck: the witnessed seal is later than the verifier's clock plus
/// skew (carries `:sealed_at=<depositedAt>`).
pub const REASON_INTENT_SEAL_FUTURE: &str = "intent_seal_future";
/// Intent recheck: the execution time is not within the verifier's clock +/-
/// skew (carries `:valid_from=<validFrom>`).
pub const REASON_INTENT_EXECUTION_NOT_CURRENT: &str = "intent_execution_not_current";

// ---------------------------------------------------------------------------
// Low-level helpers
// ---------------------------------------------------------------------------

/// Multibase base64url-no-pad of raw bytes, matching the Python `_mb64` helper
/// (`"u"` prefix + RFC 4648 base64url without padding).
fn mb64(bytes: &[u8]) -> String {
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine;
    format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
}

/// Canonical bytes of an evidence artifact, for content addressing. A JSON string
/// is hashed as its UTF-8 bytes; a JSON object is JCS-canonicalized. This matches
/// the `str`/`dict` cases of the Python `_artifact_bytes`. Raw byte artifacts use
/// [`artifact_digest_bytes`].
fn artifact_bytes(artifact: &Value) -> Result<Vec<u8>> {
    match artifact {
        Value::String(s) => Ok(s.as_bytes().to_vec()),
        Value::Object(_) => Ok(jcs::canonicalize(artifact)),
        _ => Err(CoreError::Json(
            "evidence artifact must be a JSON object or string".into(),
        )),
    }
}

/// Multibase SHA-256 of an evidence artifact (JSON object or string).
pub fn artifact_digest(artifact: &Value) -> Result<String> {
    Ok(mb64(&Sha256::digest(&artifact_bytes(artifact)?)))
}

/// Multibase SHA-256 of a raw-byte evidence artifact.
pub fn artifact_digest_bytes(artifact: &[u8]) -> String {
    mb64(&Sha256::digest(artifact))
}

fn type_list(credential: &Value) -> Vec<String> {
    match credential.get("type") {
        Some(Value::String(s)) => vec![s.clone()],
        Some(Value::Array(a)) => a
            .iter()
            .filter_map(|v| v.as_str().map(|s| s.to_string()))
            .collect(),
        _ => Vec::new(),
    }
}

/// Attach an `eddsa-jcs-2022` proof to `credential` in place, signing with the
/// raw Ed25519 seed and stamping `created`.
fn attach_proof(
    credential: &mut Value,
    seed: &[u8],
    verification_method: &str,
    created: &str,
) -> Result<()> {
    let opts = BuildProofOptions::new(verification_method, created);
    let proof = data_integrity::build_proof(credential, seed, &opts)?;
    credential
        .as_object_mut()
        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
        .insert("proof".into(), proof);
    Ok(())
}

// ---------------------------------------------------------------------------
// Justification: the structured "why", anchored to real evidence
// ---------------------------------------------------------------------------

/// Build one evidence anchor: a claim tied to a verifiable artifact. Supply
/// `evidence` (its hash is computed) OR a precomputed `evidence_hash`.
pub fn evidence_anchor(
    claim: &str,
    reference: &str,
    evidence: Option<&Value>,
    evidence_hash: Option<&str>,
    anchor_type: &str,
) -> Result<Value> {
    if claim.is_empty() || reference.is_empty() {
        return Err(CoreError::Json(
            "an evidence anchor needs a claim and a ref".into(),
        ));
    }
    let hash = match evidence_hash {
        Some(h) => h.to_string(),
        None => match evidence {
            Some(e) => artifact_digest(e)?,
            None => {
                return Err(CoreError::Json(
                    "supply evidence or evidence_hash for the anchor".into(),
                ))
            }
        },
    };
    let mut anchor = Map::new();
    anchor.insert("type".into(), Value::String(anchor_type.to_string()));
    anchor.insert("claim".into(), Value::String(claim.to_string()));
    anchor.insert("ref".into(), Value::String(reference.to_string()));
    anchor.insert("evidenceHash".into(), Value::String(hash));
    Ok(Value::Object(anchor))
}

/// Assemble a justification: the intent plus its evidence anchors. `intent` must
/// carry at least `action` and `target`; at least one anchor is required.
pub fn build_justification(
    intent: &Value,
    anchors: &[Value],
    commitment_level: Option<i64>,
) -> Result<Value> {
    if !intent.is_object()
        || intent.get("action").and_then(|v| v.as_str()).is_none()
        || intent.get("target").and_then(|v| v.as_str()).is_none()
    {
        return Err(CoreError::Json(
            "intent must be an object with at least action and target".into(),
        ));
    }
    if anchors.is_empty() {
        return Err(CoreError::Json(
            "a justification needs at least one evidence anchor".into(),
        ));
    }
    let mut just = Map::new();
    just.insert("intent".into(), intent.clone());
    just.insert("evidenceAnchors".into(), Value::Array(anchors.to_vec()));
    if let Some(level) = commitment_level {
        just.insert("commitmentLevel".into(), Value::from(level));
    }
    Ok(Value::Object(just))
}

/// Multibase SHA-256 over the JCS-canonical justification.
pub fn justification_digest(justification: &Value) -> Result<String> {
    if !justification.is_object() {
        return Err(CoreError::Json(
            "justification must be a JSON object".into(),
        ));
    }
    Ok(mb64(&Sha256::digest(jcs::canonicalize(justification))))
}

// ---------------------------------------------------------------------------
// Escrow: a neutral timestamp that fixes the commitment before execution
// ---------------------------------------------------------------------------

/// Issue a signed `JustificationEscrowReceipt` fixing a commitment in time. The
/// escrow sees only the digest, never the plaintext justification.
#[allow(clippy::too_many_arguments)]
pub fn build_escrow_receipt(
    escrow_seed: &[u8],
    escrow_did: &str,
    escrow_verification_method: &str,
    agent_did: &str,
    committed_digest: &str,
    deposited_at: &str,
    credential_id: &str,
) -> Result<Value> {
    let mut subject = Map::new();
    subject.insert("agent".into(), Value::String(agent_did.to_string()));
    subject.insert(
        "committedDigest".into(),
        Value::String(committed_digest.to_string()),
    );
    subject.insert(
        "depositedAt".into(),
        Value::String(deposited_at.to_string()),
    );

    let mut receipt = Map::new();
    receipt.insert(
        "@context".into(),
        Value::Array(vec![
            Value::String(VC_CONTEXT_V2.into()),
            Value::String(VOUCH_CONTEXT_V1.into()),
        ]),
    );
    receipt.insert(
        "type".into(),
        Value::Array(vec![
            Value::String("VerifiableCredential".into()),
            Value::String(ESCROW_RECEIPT_TYPE.into()),
        ]),
    );
    receipt.insert("id".into(), Value::String(credential_id.to_string()));
    receipt.insert("issuer".into(), Value::String(escrow_did.to_string()));
    receipt.insert("validFrom".into(), Value::String(deposited_at.to_string()));
    receipt.insert("credentialSubject".into(), Value::Object(subject));

    let mut receipt = Value::Object(receipt);
    attach_proof(
        &mut receipt,
        escrow_seed,
        escrow_verification_method,
        deposited_at,
    )?;
    Ok(receipt)
}

/// Verify an escrow receipt's proof and structure against the escrow's raw
/// Ed25519 public key. The proof must be bound to the receipt's issuer
/// (proofPurpose "assertionMethod", a verificationMethod of the escrow's DID),
/// the subject must name the `agent` and carry the `committedDigest`, and
/// `depositedAt` must be a protocol time. A proof that carries an `@context` is
/// refused: an escrow never writes one, and with one the same signed receipt
/// would have a second form with different bytes. Returns `(ok, subject)`.
pub fn verify_escrow_receipt(receipt: &Value, escrow_public_key: &[u8]) -> (bool, Option<Value>) {
    if !type_list(receipt).iter().any(|t| t == ESCROW_RECEIPT_TYPE) {
        return (false, None);
    }
    let has_context = |item: &Value| {
        item.as_object()
            .is_some_and(|proof| proof.contains_key("@context"))
    };
    let proof_carries_context = match receipt.get("proof") {
        Some(Value::Array(items)) => items.iter().any(has_context),
        Some(item) => has_context(item),
        None => false,
    };
    if proof_carries_context {
        return (false, None);
    }
    // The receipt's proof must be the escrow's own assertion.
    let bound = match (
        crate::credentials::issuer_did(receipt),
        receipt.get("proof"),
    ) {
        (Some(issuer), Some(proof)) => crate::credentials::proof_bound_to_issuer(proof, issuer),
        _ => false,
    };
    if !bound {
        return (false, None);
    }
    match data_integrity::verify_proof(receipt, escrow_public_key) {
        Ok(true) => {}
        _ => return (false, None),
    }
    let subject = match receipt.get("credentialSubject").and_then(|s| s.as_object()) {
        Some(s) => s,
        None => return (false, None),
    };
    let has_digest = subject
        .get("committedDigest")
        .and_then(|v| v.as_str())
        .is_some_and(|s| !s.is_empty());
    let has_agent = subject.get("agent").is_some_and(|v| v.is_string());
    let has_deposited = subject
        .get("depositedAt")
        .and_then(|v| v.as_str())
        .is_some_and(|s| parse_protocol_time_ns(s).is_ok());
    if !has_digest || !has_agent || !has_deposited {
        return (false, None);
    }
    (true, Some(Value::Object(subject.clone())))
}

// ---------------------------------------------------------------------------
// Reasoned action credential: the executed action, carrying its commitment
// ---------------------------------------------------------------------------

/// Options for [`sign_reasoned_action`].
#[derive(Debug, Clone, Default)]
pub struct SignReasonedActionOptions {
    /// If false, publish only the digest (private reasoning); reveal anchors out
    /// of band at audit time. Defaults to true.
    pub include_reasoning: bool,
    /// Attach an escrow receipt proving the commitment was fixed before this
    /// action.
    pub escrow_receipt: Option<Value>,
    /// The moment the intent was sealed. Read by the intent recheck. When escrow
    /// is used this SHOULD equal the receipt's `depositedAt`; without escrow the
    /// signer stamps it. Absent by default (backward compatible).
    pub sealed_at: Option<String>,
}

impl SignReasonedActionOptions {
    pub fn new() -> Self {
        Self {
            include_reasoning: true,
            escrow_receipt: None,
            sealed_at: None,
        }
    }
}

/// Issue a `ReasonedActionCredential`: the action bound to its justification.
/// `valid_from` is the execution time and also the proof `created`.
#[allow(clippy::too_many_arguments)]
pub fn sign_reasoned_action(
    seed: &[u8],
    issuer_did: &str,
    verification_method: &str,
    intent: &Value,
    justification: &Value,
    valid_from: &str,
    credential_id: &str,
    opts: &SignReasonedActionOptions,
) -> Result<Value> {
    if !intent.is_object()
        || intent.get("action").and_then(|v| v.as_str()).is_none()
        || intent.get("target").and_then(|v| v.as_str()).is_none()
    {
        return Err(CoreError::Json(
            "intent must be an object with at least action and target".into(),
        ));
    }
    let digest = justification_digest(justification)?;

    let mut commitment = Map::new();
    commitment.insert(
        "algorithm".into(),
        Value::String(JUSTIFICATION_ALGORITHM.into()),
    );
    commitment.insert("digest".into(), Value::String(digest));

    let mut jblock = Map::new();
    jblock.insert("commitment".into(), Value::Object(commitment));
    if let Some(sealed) = &opts.sealed_at {
        jblock.insert("sealedAt".into(), Value::String(sealed.clone()));
    }
    if let Some(level) = justification.get("commitmentLevel") {
        jblock.insert("commitmentLevel".into(), level.clone());
    }
    if let Some(receipt) = &opts.escrow_receipt {
        jblock.insert("escrowReceipt".into(), receipt.clone());
    }
    if opts.include_reasoning {
        let anchors = justification
            .get("evidenceAnchors")
            .cloned()
            .unwrap_or_else(|| Value::Array(Vec::new()));
        jblock.insert("evidenceAnchors".into(), anchors);
    }

    let mut subject = Map::new();
    subject.insert("intent".into(), intent.clone());
    subject.insert("justification".into(), Value::Object(jblock));

    let mut credential = Map::new();
    credential.insert(
        "@context".into(),
        Value::Array(vec![
            Value::String(VC_CONTEXT_V2.into()),
            Value::String(VOUCH_CONTEXT_V1.into()),
        ]),
    );
    credential.insert(
        "type".into(),
        Value::Array(vec![
            Value::String("VerifiableCredential".into()),
            Value::String(REASONED_ACTION_TYPE.into()),
        ]),
    );
    credential.insert("id".into(), Value::String(credential_id.to_string()));
    credential.insert("issuer".into(), Value::String(issuer_did.to_string()));
    credential.insert("validFrom".into(), Value::String(valid_from.to_string()));
    credential.insert("credentialSubject".into(), Value::Object(subject));

    let mut credential = Value::Object(credential);
    attach_proof(&mut credential, seed, verification_method, valid_from)?;
    Ok(credential)
}

fn time_of(v: Option<&Value>) -> std::result::Result<i128, ()> {
    match v.and_then(|v| v.as_str()) {
        Some(s) => parse_protocol_time_ns(s).map_err(|_| ()),
        None => Err(()),
    }
}

/// The checks of [`check_reasoned_action_at`]; `clock` is the verifier's
/// `(now, skew)` in nanoseconds, or `None` to skip the clock comparisons.
fn check_reasoned_action_inner(
    credential: &Value,
    public_key: &[u8],
    escrow_public_key: Option<&[u8]>,
    require_escrow: bool,
    clock: Option<(i128, i128)>,
) -> Option<String> {
    if !type_list(credential)
        .iter()
        .any(|t| t == REASONED_ACTION_TYPE)
    {
        return Some(REASON_NOT_REASONED_ACTION.into());
    }
    let bound = match (
        crate::credentials::issuer_did(credential),
        credential.get("proof"),
    ) {
        (Some(issuer), Some(proof)) => crate::credentials::proof_bound_to_issuer(proof, issuer),
        _ => false,
    };
    if !bound {
        return Some(REASON_INVALID_PROOF.into());
    }
    match data_integrity::verify_proof(credential, public_key) {
        Ok(true) => {}
        _ => return Some(REASON_INVALID_PROOF.into()),
    }

    let jblock = credential
        .get("credentialSubject")
        .and_then(|s| s.get("justification"))
        .filter(|j| j.is_object());
    let Some(jblock) = jblock else {
        return Some(REASON_MISSING_COMMITMENT.into());
    };
    let commitment_digest = jblock
        .get("commitment")
        .and_then(|c| c.get("digest"))
        .and_then(|d| d.as_str());
    let commitment_digest = match commitment_digest {
        Some(d) if !d.is_empty() => d,
        _ => return Some(REASON_MISSING_COMMITMENT.into()),
    };

    let Ok(executed) = time_of(credential.get("validFrom")) else {
        return Some(REASON_MALFORMED_TIME.into());
    };
    let sealed = match jblock.get("sealedAt") {
        None => None,
        Some(v) => match time_of(Some(v)) {
            Ok(t) => Some(t),
            Err(()) => return Some(REASON_MALFORMED_TIME.into()),
        },
    };
    if let Some(t) = sealed {
        if t > executed {
            return Some(REASON_SEAL_AFTER_EXECUTION.into());
        }
        if let Some((now, skew)) = clock {
            if t > now + skew {
                return Some(REASON_SEAL_IN_FUTURE.into());
            }
        }
    }

    let receipt = match jblock.get("escrowReceipt") {
        None => {
            return if require_escrow {
                Some(REASON_MISSING_ESCROW.into())
            } else {
                None
            };
        }
        Some(r) => r,
    };
    let escrow_key = match escrow_public_key {
        Some(k) => k,
        None => return Some(REASON_ESCROW_INVALID.into()),
    };
    let (ok, rsubject) = verify_escrow_receipt(receipt, escrow_key);
    let Some(rsubject) = rsubject.filter(|_| ok) else {
        return Some(REASON_ESCROW_INVALID.into());
    };
    // The receipt must witness THIS agent's commitment.
    if rsubject.get("agent").and_then(|v| v.as_str()) != crate::credentials::issuer_did(credential)
    {
        return Some(REASON_ESCROW_AGENT_MISMATCH.into());
    }
    if rsubject.get("committedDigest").and_then(|v| v.as_str()) != Some(commitment_digest) {
        return Some(REASON_ESCROW_DIGEST_MISMATCH.into());
    }
    let Ok(deposited) = time_of(rsubject.get("depositedAt")) else {
        return Some(REASON_ESCROW_INVALID.into());
    };
    if let Some(t) = sealed {
        if t > deposited {
            return Some(REASON_SEAL_AFTER_DEPOSIT.into());
        }
    }
    if deposited > executed {
        return Some(REASON_ESCROW_AFTER_EXECUTION.into());
    }
    if let Some((now, skew)) = clock {
        if deposited > now + skew {
            return Some(REASON_SEAL_IN_FUTURE.into());
        }
    }
    None
}

/// Verify a reasoned-action credential. Returns `None` on success or a
/// structured reason string on failure. Checks, in order:
///
/// 1. The type, and the agent's proof (proofPurpose "assertionMethod", a key
///    of the issuer's DID, valid under `public_key`): `invalid_proof`.
/// 2. A commitment digest (`missing_commitment`); `validFrom` and any
///    `sealedAt` follow the time grammar (`malformed_time`).
/// 3. `sealedAt`, when present, is no later than `validFrom`
///    (`seal_after_execution`).
/// 4. With an escrow receipt: it verifies under `escrow_public_key`
///    (`escrow_receipt_invalid`), names this credential's issuer as its agent
///    (`escrow_agent_mismatch`) and its commitment (`escrow_digest_mismatch`);
///    `sealedAt <= depositedAt` (`seal_after_deposit`) and `depositedAt <=
///    validFrom` (`escrow_after_execution`).
///
/// This form has no clock; [`check_reasoned_action_at`] also refuses a seal
/// later than the verifier's `now` plus skew (`seal_in_future`).
pub fn check_reasoned_action(
    credential: &Value,
    public_key: &[u8],
    escrow_public_key: Option<&[u8]>,
    require_escrow: bool,
) -> Option<String> {
    check_reasoned_action_inner(
        credential,
        public_key,
        escrow_public_key,
        require_escrow,
        None,
    )
}

/// [`check_reasoned_action`] with the verifier's clock: a `sealedAt` or a
/// `depositedAt` later than `now_iso` plus the skew is refused
/// (`seal_in_future`). Errors on a malformed `now_iso` or a skew outside
/// 0..120 seconds (a caller error, not a verdict).
pub fn check_reasoned_action_at(
    credential: &Value,
    public_key: &[u8],
    escrow_public_key: Option<&[u8]>,
    require_escrow: bool,
    now_iso: &str,
    clock_skew_seconds: i64,
) -> Result<Option<String>> {
    let skew = check_clock_skew(clock_skew_seconds)?;
    let now = parse_protocol_time_ns(now_iso)?;
    Ok(check_reasoned_action_inner(
        credential,
        public_key,
        escrow_public_key,
        require_escrow,
        Some((now, skew)),
    ))
}

/// Convenience wrapper over [`check_reasoned_action`] returning
/// `(ok, credentialSubject)`.
pub fn verify_reasoned_action(
    credential: &Value,
    public_key: &[u8],
    escrow_public_key: Option<&[u8]>,
    require_escrow: bool,
) -> (bool, Option<Value>) {
    if check_reasoned_action(credential, public_key, escrow_public_key, require_escrow).is_some() {
        return (false, None);
    }
    (true, credential.get("credentialSubject").cloned())
}

/// Check a revealed justification against a verified credential's commitment: the
/// justification must recompute to the committed digest, and every anchor must
/// resolve (via `resolver`) to an artifact whose hash matches. Returns
/// `(true, None)` on success, else `(false, Some(reason))`.
pub fn verify_justification<F>(
    presented_justification: &Value,
    credential_subject: &Value,
    resolver: F,
) -> (bool, Option<String>)
where
    F: Fn(&str) -> Option<Value>,
{
    let committed = credential_subject
        .get("justification")
        .and_then(|j| j.get("commitment"))
        .and_then(|c| c.get("digest"))
        .and_then(|d| d.as_str());
    let committed = match committed {
        Some(d) if !d.is_empty() => d,
        _ => return (false, Some(REASON_MISSING_COMMITMENT.into())),
    };

    match justification_digest(presented_justification) {
        Ok(d) if d == committed => {}
        _ => return (false, Some(REASON_JUSTIFICATION_DIGEST_MISMATCH.into())),
    }

    let anchors = presented_justification
        .get("evidenceAnchors")
        .and_then(|a| a.as_array());
    let anchors = match anchors {
        Some(a) if !a.is_empty() => a,
        _ => return (false, Some(REASON_UNANCHORED_CLAIM.into())),
    };
    for anchor in anchors {
        let reference = anchor.get("ref").and_then(|v| v.as_str());
        let artifact = reference.and_then(&resolver);
        let artifact = match artifact {
            Some(a) => a,
            None => return (false, Some(REASON_EVIDENCE_UNRESOLVED.into())),
        };
        let expected = anchor.get("evidenceHash").and_then(|v| v.as_str());
        match artifact_digest(&artifact) {
            Ok(actual) if Some(actual.as_str()) == expected => {}
            _ => return (false, Some(REASON_EVIDENCE_HASH_MISMATCH.into())),
        }
    }
    (true, None)
}

// ---------------------------------------------------------------------------
// Intent recheck: bind seal freshness to the action, not the interval alone
// ---------------------------------------------------------------------------

/// Where an action's execution time falls relative to the current pulse window
/// `[last_pulse, last_pulse + interval)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PulseWindow {
    /// Execution is inside the current window (a pulse is not yet due).
    pub in_window: bool,
    /// Execution is in the gap past the window's end (the next pulse is overdue).
    pub in_gap: bool,
    /// Seconds from `last_pulse` to execution (negative if execution precedes it).
    pub seconds_into_window: i64,
}

/// Classify an action's execution time against the pulse schedule. `last_pulse`
/// is the issue time of the most recent heartbeat; `interval_seconds` is the
/// heartbeat period.
pub fn pulse_window(
    last_pulse: &str,
    interval_seconds: i64,
    exec_time: &str,
) -> Result<PulseWindow> {
    let pulse = parse_protocol_time_ns(last_pulse)?;
    let exec = parse_protocol_time_ns(exec_time)?;
    let delta = exec - pulse;
    let interval = seconds_to_ns(interval_seconds);
    let in_window = delta >= 0 && delta < interval;
    Ok(PulseWindow {
        in_window,
        in_gap: delta >= interval,
        seconds_into_window: delta.div_euclid(1_000_000_000) as i64,
    })
}

/// The freshness requirement a consequence tier imposes on an intent seal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FreshnessRequirement {
    /// The seal must post-date the last pulse boundary (be sealed in the current
    /// window), not merely predate execution.
    pub require_fresh_seal: bool,
    /// The seal must be at most this many seconds older than execution. `i64::MAX`
    /// means no age bound.
    pub max_age_seconds: i64,
}

impl FreshnessRequirement {
    pub const NONE: FreshnessRequirement = FreshnessRequirement {
        require_fresh_seal: false,
        max_age_seconds: i64::MAX,
    };
}

/// Consequence tiers, aligned with PAD-017 commitment levels (0..4) and the
/// trust-entropy stakes bands. Higher tiers demand a fresher seal.
pub const TIER_ROUTINE: i64 = 0;
pub const TIER_LOW: i64 = 1;
pub const TIER_MEDIUM: i64 = 2;
pub const TIER_HIGH: i64 = 3;
pub const TIER_CRITICAL: i64 = 4;

/// Reference intent-freshness policy: routine/low/medium tiers inherit the last
/// pulse's assurance; high and critical tiers require a seal sealed after the
/// last pulse boundary, within a tightening max age. Deployments substitute their
/// own thresholds; these are reference values.
pub fn default_requirement(tier: i64) -> FreshnessRequirement {
    match tier {
        t if t >= TIER_CRITICAL => FreshnessRequirement {
            require_fresh_seal: true,
            max_age_seconds: 60,
        },
        TIER_HIGH => FreshnessRequirement {
            require_fresh_seal: true,
            max_age_seconds: 300,
        },
        _ => FreshnessRequirement::NONE,
    }
}

/// Read the seal timestamp from a reasoned-action credential: the attached
/// escrow receipt's `depositedAt` when there is a receipt (a neutral witness),
/// else the justification's own `sealedAt`.
///
/// This reads the receipt without verifying it; [`recheck_intent_freshness`]
/// verifies the receipt first and is what a verifier should call.
pub fn seal_timestamp(credential: &Value) -> Option<String> {
    let jblock = credential
        .get("credentialSubject")
        .and_then(|s| s.get("justification"))?;
    let deposited = jblock
        .get("escrowReceipt")
        .and_then(|r| r.get("credentialSubject"))
        .and_then(|s| s.get("depositedAt"))
        .and_then(|v| v.as_str());
    if let Some(d) = deposited {
        return Some(d.to_string());
    }
    jblock
        .get("sealedAt")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
}

/// The core intent-recheck rule. Given a seal time, the action's execution time,
/// the last pulse boundary, and a tier's freshness requirement, return `None` if
/// the seal is fresh enough, else a stable reason string.
///
/// - `intent_seal_stale:sealed_at=<t>,last_pulse=<t>`: a pulse boundary elapsed
///   between sealing and execution; the action inherited a prior pulse's
///   assurance. This is the timing-the-gap case.
/// - `intent_seal_expired:sealed_at=<t>,max_age=<n>s`: the seal is within the
///   current window but older than the tier's max age.
///
/// This compares the timestamps it is given; it does not know the verifier's
/// clock or verify an escrow receipt. [`recheck_intent_freshness`] does both.
pub fn check_seal_freshness(
    sealed_at: &str,
    exec_time: &str,
    last_pulse: &str,
    requirement: FreshnessRequirement,
) -> Result<Option<String>> {
    if !requirement.require_fresh_seal {
        return Ok(None);
    }
    let sealed = parse_protocol_time_ns(sealed_at)?;
    let exec = parse_protocol_time_ns(exec_time)?;
    let pulse = parse_protocol_time_ns(last_pulse)?;
    if sealed < pulse {
        return Ok(Some(format!(
            "{REASON_INTENT_SEAL_STALE}:sealed_at={sealed_at},last_pulse={last_pulse}"
        )));
    }
    if requirement.max_age_seconds != i64::MAX
        && exec - sealed > seconds_to_ns(requirement.max_age_seconds)
    {
        return Ok(Some(format!(
            "{REASON_INTENT_SEAL_EXPIRED}:sealed_at={sealed_at},max_age={}s",
            requirement.max_age_seconds
        )));
    }
    Ok(None)
}

/// Verify intent freshness for a reasoned-action credential at a given tier,
/// without an escrow key or a clock. A tier that requires a fresh seal needs a
/// verified escrow receipt, which this form cannot check, so it refuses
/// (`intent_seal_missing:tier=<n>` with no receipt, else
/// `escrow_receipt_invalid`); a tier with no requirement returns `None`. A
/// verifier calls [`recheck_intent_freshness`].
pub fn verify_intent_freshness(
    credential: &Value,
    tier: i64,
    last_pulse: &str,
    requirement: FreshnessRequirement,
) -> Result<Option<String>> {
    if !requirement.require_fresh_seal {
        return Ok(None);
    }
    parse_protocol_time_ns(last_pulse)?;
    let receipt = credential
        .get("credentialSubject")
        .and_then(|s| s.get("justification"))
        .and_then(|j| j.get("escrowReceipt"));
    Ok(Some(match receipt {
        None => format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}"),
        Some(_) => REASON_ESCROW_INVALID.to_string(),
    }))
}

/// The intent recheck a verifier runs at a consequence tier. A tier that
/// requires a fresh seal (high and critical in the reference policy) requires
/// an escrow receipt, because the agent's own `sealedAt` is only its word; the
/// seal time is the receipt's VERIFIED `depositedAt`. Checks, in order (the
/// first failure is returned):
///
/// 1. No escrow receipt: `intent_seal_missing:tier=<n>`.
/// 2. The receipt does not verify under `escrow_public_key`:
///    `escrow_receipt_invalid`; it names another agent than the credential's
///    issuer: `escrow_agent_mismatch`; it commits to another digest:
///    `escrow_digest_mismatch`.
/// 3. `validFrom` or `sealedAt` is malformed: `malformed_time`.
/// 4. `sealedAt` is later than `depositedAt`: `seal_after_deposit`;
///    `depositedAt` is later than `validFrom`: `escrow_after_execution`.
/// 5. `depositedAt` is later than `now` + skew:
///    `intent_seal_future:sealed_at=<depositedAt>`.
/// 6. `validFrom` (the execution time) is not within `now` +/- skew:
///    `intent_execution_not_current:valid_from=<validFrom>`.
/// 7. [`check_seal_freshness`] with `depositedAt` as the seal time
///    (`intent_seal_stale` / `intent_seal_expired`).
///
/// This checks the escrow receipt's signature, not the agent's own proof: run
/// [`check_reasoned_action_at`] for that. Returns `None` when accepted (or the
/// tier imposes no requirement). Errors on a malformed `now`, `last_pulse` or a
/// skew outside 0..120 seconds.
#[allow(clippy::too_many_arguments)]
pub fn recheck_intent_freshness(
    credential: &Value,
    tier: i64,
    last_pulse: &str,
    requirement: FreshnessRequirement,
    now_iso: &str,
    clock_skew_seconds: i64,
    escrow_public_key: Option<&[u8]>,
) -> Result<Option<String>> {
    if !requirement.require_fresh_seal {
        return Ok(None);
    }
    let skew = check_clock_skew(clock_skew_seconds)?;
    let now = parse_protocol_time_ns(now_iso)?;
    parse_protocol_time_ns(last_pulse)?;

    let jblock = credential
        .get("credentialSubject")
        .and_then(|s| s.get("justification"))
        .filter(|j| j.is_object());
    let Some(receipt) = jblock.and_then(|j| j.get("escrowReceipt")) else {
        return Ok(Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}")));
    };
    let (ok, rsubject) = match escrow_public_key {
        Some(k) => verify_escrow_receipt(receipt, k),
        None => (false, None),
    };
    let Some(rsubject) = rsubject.filter(|_| ok) else {
        return Ok(Some(REASON_ESCROW_INVALID.into()));
    };
    if rsubject.get("agent").and_then(|v| v.as_str()) != crate::credentials::issuer_did(credential)
    {
        return Ok(Some(REASON_ESCROW_AGENT_MISMATCH.into()));
    }
    let digest = jblock
        .and_then(|j| j.get("commitment"))
        .and_then(|c| c.get("digest"))
        .and_then(|d| d.as_str())
        .filter(|d| !d.is_empty());
    if digest.is_none() || rsubject.get("committedDigest").and_then(|v| v.as_str()) != digest {
        return Ok(Some(REASON_ESCROW_DIGEST_MISMATCH.into()));
    }

    let exec_str = credential
        .get("validFrom")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    let deposited_str = rsubject
        .get("depositedAt")
        .and_then(|v| v.as_str())
        .unwrap_or_default()
        .to_string();
    let (Ok(executed), Ok(deposited)) = (
        time_of(credential.get("validFrom")),
        time_of(rsubject.get("depositedAt")),
    ) else {
        return Ok(Some(REASON_MALFORMED_TIME.into()));
    };
    let sealed = match jblock.and_then(|j| j.get("sealedAt")) {
        None => None,
        Some(v) => match time_of(Some(v)) {
            Ok(t) => Some(t),
            Err(()) => return Ok(Some(REASON_MALFORMED_TIME.into())),
        },
    };
    if sealed.is_some_and(|t| t > deposited) {
        return Ok(Some(REASON_SEAL_AFTER_DEPOSIT.into()));
    }
    if deposited > executed {
        return Ok(Some(REASON_ESCROW_AFTER_EXECUTION.into()));
    }
    if deposited > now + skew {
        return Ok(Some(format!(
            "{REASON_INTENT_SEAL_FUTURE}:sealed_at={deposited_str}"
        )));
    }
    if (executed - now).abs() > skew {
        return Ok(Some(format!(
            "{REASON_INTENT_EXECUTION_NOT_CURRENT}:valid_from={exec_str}"
        )));
    }
    check_seal_freshness(&deposited_str, exec_str, last_pulse, requirement)
}

/// Execution-time reseal helper: seal the intent right now and issue a fresh
/// `ReasonedActionCredential` whose `sealedAt` and `validFrom` are both `now`, so
/// a sensitive action carries a seal made in the current pulse window. Reuses
/// [`build_justification`] and [`sign_reasoned_action`]; no new cryptography.
#[allow(clippy::too_many_arguments)]
pub fn reseal_intent(
    seed: &[u8],
    issuer_did: &str,
    verification_method: &str,
    intent: &Value,
    anchors: &[Value],
    commitment_level: Option<i64>,
    now: &str,
    credential_id: &str,
    include_reasoning: bool,
) -> Result<Value> {
    let justification = build_justification(intent, anchors, commitment_level)?;
    let opts = SignReasonedActionOptions {
        include_reasoning,
        escrow_receipt: None,
        sealed_at: Some(now.to_string()),
    };
    sign_reasoned_action(
        seed,
        issuer_did,
        verification_method,
        intent,
        &justification,
        now,
        credential_id,
        &opts,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keys::Ed25519KeyPair;
    use serde_json::json;

    fn seed() -> [u8; 32] {
        [7u8; 32]
    }

    fn pubkey() -> [u8; 32] {
        Ed25519KeyPair::from_seed_slice(&seed())
            .unwrap()
            .public_key()
    }

    fn sample_intent() -> Value {
        json!({"action": "transfer_funds", "target": "account:9911", "resource": "https://bank.example/v1/xfer"})
    }

    fn sample_justification() -> Value {
        let anchor = evidence_anchor(
            "user approved the transfer",
            "urn:msg:42",
            Some(&json!({"text": "please move $500 to savings"})),
            None,
            "user_message",
        )
        .unwrap();
        build_justification(&sample_intent(), &[anchor], Some(TIER_HIGH)).unwrap()
    }

    #[test]
    fn justification_digest_is_multibase_b64url() {
        let d = justification_digest(&sample_justification()).unwrap();
        assert!(d.starts_with('u'));
    }

    #[test]
    fn sign_then_verify_reasoned_action() {
        let cred = sign_reasoned_action(
            &seed(),
            "did:web:agent.example",
            "did:web:agent.example#key-1",
            &sample_intent(),
            &sample_justification(),
            "2026-08-02T10:00:00Z",
            "urn:uuid:11111111-1111-1111-1111-111111111111",
            &SignReasonedActionOptions::new(),
        )
        .unwrap();
        assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
        assert_eq!(
            check_reasoned_action(&cred, &pubkey(), None, true),
            Some(REASON_MISSING_ESCROW.into())
        );
    }

    #[test]
    fn tampered_action_fails() {
        let mut cred = sign_reasoned_action(
            &seed(),
            "did:web:agent.example",
            "did:web:agent.example#key-1",
            &sample_intent(),
            &sample_justification(),
            "2026-08-02T10:00:00Z",
            "urn:uuid:11111111-1111-1111-1111-111111111111",
            &SignReasonedActionOptions::new(),
        )
        .unwrap();
        cred["credentialSubject"]["intent"]["action"] = json!("drain_account");
        assert_eq!(
            check_reasoned_action(&cred, &pubkey(), None, false),
            Some(REASON_INVALID_PROOF.into())
        );
    }

    #[test]
    fn pulse_window_classifies_window_and_gap() {
        // interval 60s, last pulse at 10:00:00.
        let w = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:00:30Z").unwrap();
        assert!(w.in_window && !w.in_gap);
        let g = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:02:00Z").unwrap();
        assert!(g.in_gap && !g.in_window);
    }

    // --- Intent recheck acceptance/rejection matrix ---

    fn reasoned_with_seal(sealed_at: &str, exec: &str, level: i64) -> Value {
        let anchor = evidence_anchor(
            "user approved",
            "urn:msg:42",
            Some(&json!({"text": "go"})),
            None,
            "user_message",
        )
        .unwrap();
        let just = build_justification(&sample_intent(), &[anchor], Some(level)).unwrap();
        let opts = SignReasonedActionOptions {
            include_reasoning: true,
            escrow_receipt: None,
            sealed_at: Some(sealed_at.to_string()),
        };
        sign_reasoned_action(
            &seed(),
            "did:web:agent.example",
            "did:web:agent.example#key-1",
            &sample_intent(),
            &just,
            exec,
            "urn:uuid:22222222-2222-2222-2222-222222222222",
            &opts,
        )
        .unwrap()
    }

    #[test]
    fn agent_seal_alone_does_not_meet_a_high_tier() {
        // High tier, sealed at 10:00:10 by the agent itself, no escrow receipt:
        // the agent's own word is not a witnessed seal.
        let cred = reasoned_with_seal("2026-08-02T10:00:10Z", "2026-08-02T10:00:20Z", TIER_HIGH);
        let r = recheck_intent_freshness(
            &cred,
            TIER_HIGH,
            "2026-08-02T10:00:00Z",
            default_requirement(TIER_HIGH),
            "2026-08-02T10:00:20Z",
            30,
            Some(&pubkey()),
        )
        .unwrap();
        assert_eq!(
            r,
            Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_HIGH}"))
        );
    }

    #[test]
    fn stale_seal_across_boundary_rejects() {
        // Sealed 09:59:50 (before the 10:00:00 pulse), executed at 10:00:20 in
        // the gap after the boundary: the timestamp rule refuses it.
        let r = check_seal_freshness(
            "2026-08-02T09:59:50Z",
            "2026-08-02T10:00:20Z",
            "2026-08-02T10:00:00Z",
            default_requirement(TIER_HIGH),
        )
        .unwrap();
        assert_eq!(
            r,
            Some(
                "intent_seal_stale:sealed_at=2026-08-02T09:59:50Z,last_pulse=2026-08-02T10:00:00Z"
                    .into()
            )
        );
        assert_eq!(
            check_seal_freshness(
                "2026-08-02T10:00:10Z",
                "2026-08-02T10:00:20Z",
                "2026-08-02T10:00:00Z",
                default_requirement(TIER_HIGH),
            )
            .unwrap(),
            None
        );
    }

    #[test]
    fn reseal_in_gap_is_a_valid_action() {
        // Even executing at 10:05:00, a reseal at 10:05:00 with a pulse boundary
        // advanced to 10:05:00 is fresh.
        let cred = reseal_intent(
            &seed(),
            "did:web:agent.example",
            "did:web:agent.example#key-1",
            &sample_intent(),
            &[evidence_anchor(
                "user approved",
                "urn:msg:42",
                Some(&json!({"text": "go"})),
                None,
                "user_message",
            )
            .unwrap()],
            Some(TIER_HIGH),
            "2026-08-02T10:05:00Z",
            "urn:uuid:33333333-3333-3333-3333-333333333333",
            true,
        )
        .unwrap();
        // The reseal itself is a valid action credential; a high tier still
        // needs an escrow receipt for the seal.
        assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
        let r = verify_intent_freshness(
            &cred,
            TIER_HIGH,
            "2026-08-02T10:05:00Z",
            default_requirement(TIER_HIGH),
        )
        .unwrap();
        assert_eq!(
            r,
            Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_HIGH}"))
        );
    }

    #[test]
    fn non_sensitive_tier_ignores_stale_seal() {
        // Same stale seal, but a routine tier does not require freshness.
        let cred = reasoned_with_seal("2026-08-02T09:59:50Z", "2026-08-02T10:00:20Z", TIER_ROUTINE);
        let r = verify_intent_freshness(
            &cred,
            TIER_ROUTINE,
            "2026-08-02T10:00:00Z",
            default_requirement(TIER_ROUTINE),
        )
        .unwrap();
        assert_eq!(r, None);
    }

    #[test]
    fn sensitive_tier_without_seal_is_missing() {
        // A high-tier action with no seal timestamp at all.
        let cred = sign_reasoned_action(
            &seed(),
            "did:web:agent.example",
            "did:web:agent.example#key-1",
            &sample_intent(),
            &sample_justification(),
            "2026-08-02T10:00:20Z",
            "urn:uuid:44444444-4444-4444-4444-444444444444",
            &SignReasonedActionOptions::new(),
        )
        .unwrap();
        let r = verify_intent_freshness(
            &cred,
            TIER_HIGH,
            "2026-08-02T10:00:00Z",
            default_requirement(TIER_HIGH),
        )
        .unwrap();
        assert_eq!(r, Some("intent_seal_missing:tier=3".into()));
    }

    #[test]
    fn escrow_roundtrip_and_seal_from_deposit() {
        let escrow_seed = [3u8; 32];
        let escrow_pub = Ed25519KeyPair::from_seed_slice(&escrow_seed)
            .unwrap()
            .public_key();
        let digest = justification_digest(&sample_justification()).unwrap();
        let receipt = build_escrow_receipt(
            &escrow_seed,
            "did:web:escrow.example",
            "did:web:escrow.example#key-1",
            "did:web:agent.example",
            &digest,
            "2026-08-02T10:00:05Z",
            "urn:uuid:55555555-5555-5555-5555-555555555555",
        )
        .unwrap();
        let (ok, _) = verify_escrow_receipt(&receipt, &escrow_pub);
        assert!(ok);

        // The same signed receipt with the document's @context copied into its
        // proof still passes general Data Integrity verification, but an escrow
        // never writes one, so the escrow receipt check refuses it.
        let mut second = receipt.clone();
        let context = second["@context"].clone();
        second["proof"]["@context"] = context.clone();
        assert!(data_integrity::verify_proof(&second, &escrow_pub).unwrap());
        assert_eq!(verify_escrow_receipt(&second, &escrow_pub), (false, None));
        let mut in_a_list = receipt.clone();
        let mut listed = in_a_list["proof"].clone();
        listed["@context"] = context;
        in_a_list["proof"] = Value::Array(vec![listed]);
        assert_eq!(
            verify_escrow_receipt(&in_a_list, &escrow_pub),
            (false, None)
        );

        let opts = SignReasonedActionOptions {
            include_reasoning: true,
            escrow_receipt: Some(receipt),
            sealed_at: None,
        };
        let cred = sign_reasoned_action(
            &seed(),
            "did:web:agent.example",
            "did:web:agent.example#key-1",
            &sample_intent(),
            &sample_justification(),
            "2026-08-02T10:00:20Z",
            "urn:uuid:66666666-6666-6666-6666-666666666666",
            &opts,
        )
        .unwrap();
        // Seal timestamp falls back to the escrow depositedAt.
        assert_eq!(
            seal_timestamp(&cred).as_deref(),
            Some("2026-08-02T10:00:05Z")
        );
        assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub), true).is_none());
    }

    // --- Recheck against a verified escrow receipt and the verifier's clock ---

    fn escrow_seed() -> [u8; 32] {
        [9u8; 32]
    }

    fn escrow_pub() -> [u8; 32] {
        Ed25519KeyPair::from_seed(&escrow_seed()).public_key()
    }

    /// A critical-tier action executed at `exec`, carrying an escrow receipt
    /// deposited at `deposited` for `agent`, and (optionally) the agent's own
    /// `sealedAt`.
    fn escrowed(agent: &str, deposited: &str, exec: &str, sealed: Option<&str>) -> Value {
        let just = sample_justification();
        let digest = justification_digest(&just).unwrap();
        let receipt = build_escrow_receipt(
            &escrow_seed(),
            "did:web:escrow.example",
            "did:web:escrow.example#key-1",
            agent,
            &digest,
            deposited,
            "urn:uuid:33333333-3333-3333-3333-333333333333",
        )
        .unwrap();
        let opts = SignReasonedActionOptions {
            include_reasoning: true,
            escrow_receipt: Some(receipt),
            sealed_at: sealed.map(String::from),
        };
        sign_reasoned_action(
            &seed(),
            "did:web:agent.example",
            "did:web:agent.example#key-1",
            &sample_intent(),
            &just,
            exec,
            "urn:uuid:44444444-4444-4444-4444-444444444444",
            &opts,
        )
        .unwrap()
    }

    fn recheck(cred: &Value, now: &str) -> Option<String> {
        recheck_intent_freshness(
            cred,
            TIER_CRITICAL,
            "2026-04-26T10:00:00Z",
            default_requirement(TIER_CRITICAL),
            now,
            30,
            Some(&escrow_pub()),
        )
        .unwrap()
    }

    #[test]
    fn recheck_accepts_a_fresh_witnessed_seal() {
        let cred = escrowed(
            "did:web:agent.example",
            "2026-04-26T10:02:30Z",
            "2026-04-26T10:03:00Z",
            None,
        );
        assert_eq!(recheck(&cred, "2026-04-26T10:03:05Z"), None);
        assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub()), true).is_none());
    }

    #[test]
    fn recheck_uses_the_escrow_time_not_the_agents_claim() {
        // Deposited before the pulse; the agent claims a fresh sealedAt.
        let honest = escrowed(
            "did:web:agent.example",
            "2026-04-26T09:55:00Z",
            "2026-04-26T10:03:00Z",
            None,
        );
        assert!(recheck(&honest, "2026-04-26T10:03:00Z")
            .unwrap()
            .starts_with(REASON_INTENT_SEAL_STALE));
        let lying = escrowed(
            "did:web:agent.example",
            "2026-04-26T09:55:00Z",
            "2026-04-26T10:03:00Z",
            Some("2026-04-26T10:02:30Z"),
        );
        assert_eq!(
            recheck(&lying, "2026-04-26T10:03:00Z"),
            Some(REASON_SEAL_AFTER_DEPOSIT.into())
        );
        assert_eq!(
            check_reasoned_action(&lying, &pubkey(), Some(&escrow_pub()), true),
            Some(REASON_SEAL_AFTER_DEPOSIT.into())
        );
        // The form without an escrow key cannot verify a receipt, so it refuses.
        let old = verify_intent_freshness(
            &lying,
            TIER_CRITICAL,
            "2026-04-26T10:00:00Z",
            default_requirement(TIER_CRITICAL),
        )
        .unwrap();
        assert_eq!(old, Some(REASON_ESCROW_INVALID.into()));
    }

    #[test]
    fn recheck_refuses_forward_dated_and_late_seals() {
        let future = escrowed(
            "did:web:agent.example",
            "2099-01-01T00:00:00Z",
            "2099-01-01T00:00:00Z",
            Some("2099-01-01T00:00:00Z"),
        );
        assert_eq!(
            recheck(&future, "2026-04-26T10:03:00Z"),
            Some(format!(
                "{REASON_INTENT_SEAL_FUTURE}:sealed_at=2099-01-01T00:00:00Z"
            ))
        );
        assert_eq!(
            check_reasoned_action_at(
                &future,
                &pubkey(),
                Some(&escrow_pub()),
                true,
                "2026-04-26T10:03:00Z",
                30
            )
            .unwrap(),
            Some(REASON_SEAL_IN_FUTURE.into())
        );
        // Deposited after execution.
        let late = escrowed(
            "did:web:agent.example",
            "2026-04-26T10:10:00Z",
            "2026-04-26T10:03:00Z",
            None,
        );
        assert_eq!(
            recheck(&late, "2026-04-26T10:03:00Z"),
            Some(REASON_ESCROW_AFTER_EXECUTION.into())
        );
        // A seal later than the verifier's clock.
        let ahead = escrowed(
            "did:web:agent.example",
            "2026-04-26T10:03:20Z",
            "2026-04-26T10:03:20Z",
            None,
        );
        assert_eq!(recheck(&ahead, "2026-04-26T10:03:00Z"), None, "inside skew");
        assert!(recheck(&ahead, "2026-04-26T10:02:40Z").is_some());
        // An agent seal made after execution is refused, escrow or not.
        let after =
            reasoned_with_seal("2026-04-26T10:10:00Z", "2026-04-26T10:03:00Z", TIER_ROUTINE);
        assert_eq!(
            check_reasoned_action(&after, &pubkey(), None, false),
            Some(REASON_SEAL_AFTER_EXECUTION.into())
        );
        // Executed well away from the verifier's clock.
        let fresh = escrowed(
            "did:web:agent.example",
            "2026-04-26T10:02:30Z",
            "2026-04-26T10:03:00Z",
            None,
        );
        assert_eq!(
            recheck(&fresh, "2026-04-26T10:09:00Z"),
            Some(format!(
                "{REASON_INTENT_EXECUTION_NOT_CURRENT}:valid_from=2026-04-26T10:03:00Z"
            ))
        );
    }

    #[test]
    fn recheck_binds_the_receipt_to_the_agent_and_key() {
        let stolen = escrowed(
            "did:web:someone-else.example",
            "2026-04-26T10:02:30Z",
            "2026-04-26T10:03:00Z",
            None,
        );
        assert_eq!(
            recheck(&stolen, "2026-04-26T10:03:00Z"),
            Some(REASON_ESCROW_AGENT_MISMATCH.into())
        );
        assert_eq!(
            check_reasoned_action(&stolen, &pubkey(), Some(&escrow_pub()), true),
            Some(REASON_ESCROW_AGENT_MISMATCH.into())
        );
        let good = escrowed(
            "did:web:agent.example",
            "2026-04-26T10:02:30Z",
            "2026-04-26T10:03:00Z",
            None,
        );
        // Wrong escrow key, no escrow key, no receipt at a critical tier.
        let wrong = recheck_intent_freshness(
            &good,
            TIER_CRITICAL,
            "2026-04-26T10:00:00Z",
            default_requirement(TIER_CRITICAL),
            "2026-04-26T10:03:00Z",
            30,
            Some(&pubkey()),
        )
        .unwrap();
        assert_eq!(wrong, Some(REASON_ESCROW_INVALID.into()));
        let none = recheck_intent_freshness(
            &good,
            TIER_CRITICAL,
            "2026-04-26T10:00:00Z",
            default_requirement(TIER_CRITICAL),
            "2026-04-26T10:03:00Z",
            30,
            None,
        )
        .unwrap();
        assert_eq!(none, Some(REASON_ESCROW_INVALID.into()));
        let bare = reasoned_with_seal(
            "2026-04-26T10:02:30Z",
            "2026-04-26T10:03:00Z",
            TIER_CRITICAL,
        );
        assert_eq!(
            recheck(&bare, "2026-04-26T10:03:00Z"),
            Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_CRITICAL}"))
        );
        // A skew outside 0..120 seconds is a caller error.
        assert!(recheck_intent_freshness(
            &good,
            TIER_CRITICAL,
            "2026-04-26T10:00:00Z",
            default_requirement(TIER_CRITICAL),
            "2026-04-26T10:03:00Z",
            121,
            Some(&escrow_pub()),
        )
        .is_err());
    }

    #[test]
    fn proof_bound_to_another_did_is_refused() {
        let cred = sign_reasoned_action(
            &seed(),
            "did:web:agent.example",
            "did:web:other.example#key-1",
            &sample_intent(),
            &sample_justification(),
            "2026-08-02T10:00:00Z",
            "urn:uuid:11111111-1111-1111-1111-111111111111",
            &SignReasonedActionOptions::new(),
        )
        .unwrap();
        assert_eq!(
            check_reasoned_action(&cred, &pubkey(), None, false),
            Some(REASON_INVALID_PROOF.into())
        );
    }
}