jacs 0.9.5

JACS JSON AI Communication Standard
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
//! Provenance wrapping for A2A artifacts (v0.4.0)

use crate::a2a::{A2AArtifact, A2AMessage};
#[cfg(not(target_arch = "wasm32"))]
use crate::agent::loaders::fetch_remote_public_key;
use crate::agent::{
    AGENT_SIGNATURE_FIELDNAME, Agent, SignatureContentMode, boilerplate::BoilerPlate,
    build_signature_content, document::DocumentTraits, extract_signature_fields,
    loaders::FileLoader,
};
use crate::config::{KeyResolutionSource, get_key_resolution_order};
use crate::crypt::{KeyManager, hash::hash_public_key};
use crate::error::JacsError;
use crate::schema::utils::ValueExt;
use crate::time_utils;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tracing::{info, warn};
use uuid::Uuid;

/// Verification status indicating whether and how a signature was verified
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum VerificationStatus {
    /// Signature was cryptographically verified
    Verified,
    /// Signature is from the current agent (self-signed) and was verified
    SelfSigned,
    /// Signature is from a foreign agent and could not be verified because
    /// the public key is not available. The signature may or may not be valid.
    Unverified { reason: String },
    /// Signature verification failed - the signature is invalid
    Invalid { reason: String },
}

impl VerificationStatus {
    /// Returns true if the signature was cryptographically verified
    pub fn is_verified(&self) -> bool {
        matches!(
            self,
            VerificationStatus::Verified | VerificationStatus::SelfSigned
        )
    }

    /// Returns true if the signature could not be verified due to missing public key
    pub fn is_unverified(&self) -> bool {
        matches!(self, VerificationStatus::Unverified { .. })
    }

    /// Returns true if the signature was checked and found to be invalid
    pub fn is_invalid(&self) -> bool {
        matches!(self, VerificationStatus::Invalid { .. })
    }
}

fn resolve_foreign_public_key(
    agent: &Agent,
    signer_id: &str,
    signer_version: &str,
    public_key_hash: &str,
) -> Result<(Vec<u8>, String), String> {
    if public_key_hash.is_empty() {
        return Err("Missing publicKeyHash in signature".to_string());
    }

    let resolution_order = get_key_resolution_order();
    let mut last_error = "No key source attempted".to_string();

    for source in &resolution_order {
        match source {
            KeyResolutionSource::Local => match agent.fs_load_public_key(public_key_hash) {
                Ok(public_key) => match agent.fs_load_public_key_type(public_key_hash) {
                    Ok(enc_type) => {
                        return Ok((public_key, enc_type.trim().to_string()));
                    }
                    Err(e) => {
                        last_error = format!("Local key type lookup failed: {}", e);
                    }
                },
                Err(e) => {
                    last_error = format!("Local key lookup failed: {}", e);
                }
            },
            KeyResolutionSource::Dns => {
                // DNS can validate identity but does not return key material.
                last_error = "DNS source does not provide public key bytes".to_string();
            }
            KeyResolutionSource::Registry => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    if signer_id.is_empty() || signer_version.is_empty() {
                        last_error =
                            "Registry lookup requires signer agent ID and version UUID".to_string();
                        continue;
                    }

                    match fetch_remote_public_key(signer_id, signer_version) {
                        Ok(key_info) => {
                            if !key_info.hash.is_empty() && key_info.hash != public_key_hash {
                                last_error = format!(
                                    "Registry key hash mismatch: expected {}..., got {}...",
                                    &public_key_hash[..public_key_hash.len().min(16)],
                                    &key_info.hash[..key_info.hash.len().min(16)]
                                );
                                continue;
                            }
                            return Ok((key_info.public_key, key_info.algorithm));
                        }
                        Err(e) => {
                            last_error = format!("Registry key lookup failed: {}", e);
                        }
                    }
                }
                #[cfg(target_arch = "wasm32")]
                {
                    let _ = signer_id;
                    let _ = signer_version;
                    last_error = "Registry lookup is not available on wasm32 targets in this build"
                        .to_string();
                }
            }
        }
    }

    Err(format!(
        "Could not resolve signer key {}... using sources {:?}. Last error: {}",
        &public_key_hash[..public_key_hash.len().min(16)],
        resolution_order,
        last_error
    ))
}

fn verify_with_resolved_key(
    agent: &Agent,
    wrapped_artifact: &Value,
    signature_info: &Value,
    public_key: Vec<u8>,
    public_key_enc_type: String,
) -> Result<(), String> {
    let signature = signature_info
        .get_str("signature")
        .ok_or_else(|| "No signature found in jacsSignature".to_string())?;
    let signature_hash = signature_info
        .get_str("publicKeyHash")
        .ok_or_else(|| "No publicKeyHash found in jacsSignature".to_string())?;

    let computed_hash = hash_public_key(&public_key);
    if computed_hash != signature_hash {
        return Err(format!(
            "Resolved public key hash mismatch: expected {}..., got {}...",
            &signature_hash[..signature_hash.len().min(16)],
            &computed_hash[..computed_hash.len().min(16)]
        ));
    }

    let signature_fields = extract_signature_fields(wrapped_artifact, AGENT_SIGNATURE_FIELDNAME);
    let (signable_data, _) = build_signature_content(
        wrapped_artifact,
        signature_fields,
        AGENT_SIGNATURE_FIELDNAME,
        SignatureContentMode::CanonicalV2,
    )
    .map_err(|e| format!("Could not build signable payload: {}", e))?;

    let explicit_alg = if public_key_enc_type.is_empty() {
        signature_info
            .get_str("signingAlgorithm")
            .map(|s| s.to_string())
    } else {
        Some(public_key_enc_type)
    };

    agent
        .verify_string(&signable_data, &signature, public_key, explicit_alg)
        .map_err(|e| format!("Signature verification failed: {}", e))
}

/// Wrap an A2A artifact with JACS provenance signature
pub fn wrap_artifact_with_provenance(
    agent: &mut Agent,
    artifact: Value,
    artifact_type: &str,
    parent_signatures: Option<Vec<Value>>,
) -> Result<Value, JacsError> {
    // Create a JACS header for the artifact
    let artifact_id = Uuid::new_v4().to_string();
    let artifact_version = Uuid::new_v4().to_string();

    let mut wrapped_artifact = json!({
        "jacsId": artifact_id,
        "jacsVersion": artifact_version,
        "jacsType": format!("a2a-{}", artifact_type),
        "jacsLevel": "artifact",
        "jacsPreviousVersion": null,
        "jacsVersionDate": time_utils::now_rfc3339(),
        "$schema": "https://jacs.sh/schemas/header/v1/header.schema.json",
        "a2aArtifact": artifact,
    });

    // Add parent signatures if this is part of a chain
    if let Some(parents) = parent_signatures {
        wrapped_artifact["jacsParentSignatures"] = json!(parents);
    }

    // Sign the wrapped artifact
    let signature = agent.signing_procedure(&wrapped_artifact, None, AGENT_SIGNATURE_FIELDNAME)?;
    wrapped_artifact[AGENT_SIGNATURE_FIELDNAME] = signature;

    // Add SHA256 hash
    let document_hash = agent.hash_doc(&wrapped_artifact)?;
    wrapped_artifact[crate::agent::SHA256_FIELDNAME] = json!(document_hash);

    info!("Successfully wrapped A2A artifact with JACS provenance");
    Ok(wrapped_artifact)
}

/// Wrap a typed A2A Artifact (v0.4.0) with JACS provenance signature.
pub fn wrap_a2a_artifact_with_provenance(
    agent: &mut Agent,
    artifact: &A2AArtifact,
    parent_signatures: Option<Vec<Value>>,
) -> Result<Value, JacsError> {
    let artifact_value = serde_json::to_value(artifact)?;
    wrap_artifact_with_provenance(agent, artifact_value, "artifact", parent_signatures)
}

/// Wrap a typed A2A Message (v0.4.0) with JACS provenance signature.
pub fn wrap_a2a_message_with_provenance(
    agent: &mut Agent,
    message: &A2AMessage,
    parent_signatures: Option<Vec<Value>>,
) -> Result<Value, JacsError> {
    let message_value = serde_json::to_value(message)?;
    wrap_artifact_with_provenance(agent, message_value, "message", parent_signatures)
}

/// Verify a JACS-wrapped A2A artifact
///
/// This function verifies the signature on a wrapped artifact. The verification
/// status indicates whether the signature could be verified:
///
/// - `Verified` or `SelfSigned`: The signature was cryptographically verified
/// - `Unverified`: The signature could not be verified because the public key
///   for the signing agent is not available (foreign agent, no registry lookup)
/// - `Invalid`: The signature was checked and found to be invalid
///
/// For foreign agents (agents other than the current agent), the public key
/// is resolved via configured key resolution order (`local`, `dns`, `registry`).
/// DNS can validate identity but does not provide key bytes; practical signature
/// verification requires local key material or remote registry key retrieval.
pub fn verify_wrapped_artifact(
    agent: &Agent,
    wrapped_artifact: &Value,
) -> Result<VerificationResult, JacsError> {
    // First verify the hash
    if let Err(e) = agent.verify_hash(wrapped_artifact) {
        return Ok(VerificationResult {
            status: VerificationStatus::Invalid {
                reason: format!("Hash verification failed: {}", e),
            },
            valid: false,
            signer_id: String::new(),
            signer_version: String::new(),
            artifact_type: wrapped_artifact.get_str_or("jacsType", "unknown"),
            timestamp: wrapped_artifact.get_str_or("jacsVersionDate", ""),
            parent_signatures_valid: false,
            parent_verification_results: vec![],
            original_artifact: wrapped_artifact
                .get("a2aArtifact")
                .cloned()
                .unwrap_or(Value::Null),
            trust_level: None,
            trust_assessment: None,
        });
    }

    // Get the signer's public key info
    let signature_info = wrapped_artifact
        .get(AGENT_SIGNATURE_FIELDNAME)
        .ok_or("No JACS signature found")?;

    let agent_id = signature_info
        .get_str("agentID")
        .ok_or("No agent ID in signature")?;
    let agent_version = signature_info
        .get_str("agentVersion")
        .ok_or("No agent version in signature")?;
    let public_key_hash = signature_info.get_str_or("publicKeyHash", "");

    // Check if this is a self-signed document
    let current_agent_id = agent.get_id().ok();
    let is_self_signed = current_agent_id
        .as_ref()
        .map(|id| id == &agent_id)
        .unwrap_or(false);

    // Determine verification status
    let (status, valid) = if is_self_signed {
        // Self-signed: we can verify with our own key
        let public_key = agent.get_public_key()?;
        match agent.signature_verification_procedure(
            wrapped_artifact,
            None,
            AGENT_SIGNATURE_FIELDNAME,
            public_key,
            agent.get_key_algorithm().cloned(),
            None,
            None,
        ) {
            Ok(_) => (VerificationStatus::SelfSigned, true),
            Err(e) => (
                VerificationStatus::Invalid {
                    reason: format!("Signature verification failed: {}", e),
                },
                false,
            ),
        }
    } else {
        match resolve_foreign_public_key(agent, &agent_id, &agent_version, &public_key_hash) {
            Ok((public_key, public_key_enc_type)) => match verify_with_resolved_key(
                agent,
                wrapped_artifact,
                signature_info,
                public_key,
                public_key_enc_type,
            ) {
                Ok(_) => (VerificationStatus::Verified, true),
                Err(e) => (
                    VerificationStatus::Invalid {
                        reason: format!("Foreign signature verification failed: {}", e),
                    },
                    false,
                ),
            },
            Err(reason) => {
                warn!(
                    "Could not resolve foreign signature key for agent {}: {}",
                    agent_id, reason
                );
                (VerificationStatus::Unverified { reason }, false)
            }
        }
    };

    // Extract the original A2A artifact
    let original_artifact = wrapped_artifact
        .get("a2aArtifact")
        .ok_or("No A2A artifact found in wrapper")?;

    // Verify parent signatures if present
    let (parent_signatures_valid, parent_verification_results) =
        verify_parent_signatures(agent, wrapped_artifact)?;

    Ok(VerificationResult {
        status,
        valid,
        signer_id: agent_id.clone(),
        signer_version: agent_version.clone(),
        artifact_type: wrapped_artifact.get_str_or("jacsType", "unknown"),
        timestamp: wrapped_artifact.get_str_or("jacsVersionDate", ""),
        parent_signatures_valid,
        parent_verification_results,
        original_artifact: original_artifact.clone(),
        trust_level: None,
        trust_assessment: None,
    })
}

/// Verify a JACS-wrapped A2A artifact with trust policy enforcement.
///
/// This combines cryptographic signature verification with trust policy
/// evaluation. The remote agent's Agent Card is assessed against the
/// specified trust policy, and the trust level is included in the result.
///
/// # Arguments
///
/// * `agent` - The local agent performing the verification
/// * `wrapped_artifact` - The JACS-wrapped artifact to verify
/// * `remote_card` - The remote agent's A2A Agent Card
/// * `policy` - The trust policy to apply
///
/// # Returns
///
/// A `VerificationResult` with `trust_level` and `trust_assessment` populated.
/// If the trust policy rejects the agent, `valid` is set to `false` and
/// `status` reflects the rejection reason.
pub fn verify_wrapped_artifact_with_policy(
    agent: &Agent,
    wrapped_artifact: &Value,
    remote_card: &super::AgentCard,
    policy: super::trust::A2ATrustPolicy,
) -> Result<VerificationResult, JacsError> {
    use super::trust::assess_a2a_agent;

    // First perform the trust assessment
    let assessment = assess_a2a_agent(agent, remote_card, policy);

    if !assessment.allowed {
        // Trust policy rejected the agent — short-circuit without crypto verification
        info!(
            policy = %policy,
            trust_level = %assessment.trust_level,
            reason = %assessment.reason,
            "A2A trust policy rejected remote agent"
        );
        return Ok(VerificationResult {
            status: VerificationStatus::Invalid {
                reason: assessment.reason.clone(),
            },
            valid: false,
            signer_id: assessment.agent_id.clone().unwrap_or_default(),
            signer_version: String::new(),
            artifact_type: wrapped_artifact.get_str_or("jacsType", "unknown"),
            timestamp: wrapped_artifact.get_str_or("jacsVersionDate", ""),
            parent_signatures_valid: false,
            parent_verification_results: vec![],
            original_artifact: wrapped_artifact
                .get("a2aArtifact")
                .cloned()
                .unwrap_or(Value::Null),
            trust_level: Some(assessment.trust_level),
            trust_assessment: Some(assessment),
        });
    }

    // Trust policy accepted the agent — proceed with cryptographic verification
    let mut result = verify_wrapped_artifact(agent, wrapped_artifact)?;

    // Enrich result with trust information
    result.trust_level = Some(assessment.trust_level);
    result.trust_assessment = Some(assessment);

    info!(
        policy = %policy,
        trust_level = ?result.trust_level,
        crypto_valid = result.valid,
        "A2A artifact verified with trust policy"
    );

    Ok(result)
}

/// Verify parent signatures in a chain of custody
///
/// Returns (all_valid, individual_results) where all_valid is true only if
/// all parent signatures were successfully verified.
fn verify_parent_signatures(
    agent: &Agent,
    wrapped_artifact: &Value,
) -> Result<(bool, Vec<ParentVerificationResult>), JacsError> {
    let parents = match wrapped_artifact.get("jacsParentSignatures") {
        Some(Value::Array(arr)) => arr,
        Some(_) => return Err("Invalid jacsParentSignatures: must be an array".into()),
        None => return Ok((true, vec![])), // No parents = valid chain
    };

    if parents.is_empty() {
        return Ok((true, vec![]));
    }

    let mut results = Vec::with_capacity(parents.len());
    let mut all_valid = true;

    for (index, parent) in parents.iter().enumerate() {
        let parent_id = parent.get_str_or("jacsId", "unknown");
        let parent_signer =
            parent.get_path_str_or(&[AGENT_SIGNATURE_FIELDNAME, "agentID"], "unknown");

        // Try to verify each parent signature
        // Note: This recursively calls verify_wrapped_artifact
        let verification = match verify_wrapped_artifact(agent, parent) {
            Ok(result) => {
                let status = result.status.clone();
                let verified = result.valid;
                if !verified {
                    all_valid = false;
                }
                ParentVerificationResult {
                    index,
                    artifact_id: parent_id,
                    signer_id: parent_signer,
                    status,
                    verified,
                }
            }
            Err(e) => {
                all_valid = false;
                ParentVerificationResult {
                    index,
                    artifact_id: parent_id,
                    signer_id: parent_signer,
                    status: VerificationStatus::Invalid {
                        reason: format!("Verification error: {}", e),
                    },
                    verified: false,
                }
            }
        };

        results.push(verification);
    }

    Ok((all_valid, results))
}

/// Result of parent signature verification
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ParentVerificationResult {
    /// Index in the parent signatures array
    pub index: usize,
    /// ID of the parent artifact
    pub artifact_id: String,
    /// ID of the agent that signed the parent
    pub signer_id: String,
    /// Verification status
    pub status: VerificationStatus,
    /// Whether the signature was verified (convenience field)
    pub verified: bool,
}

/// Result of artifact verification
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VerificationResult {
    /// Detailed verification status
    pub status: VerificationStatus,
    /// Whether the signature was cryptographically verified.
    /// This is false for both Invalid and Unverified statuses.
    pub valid: bool,
    /// ID of the signing agent
    pub signer_id: String,
    /// Version of the signing agent
    pub signer_version: String,
    /// Type of the artifact (e.g., "a2a-task", "a2a-message")
    pub artifact_type: String,
    /// Timestamp when the artifact was signed
    pub timestamp: String,
    /// Whether all parent signatures in the chain are valid
    pub parent_signatures_valid: bool,
    /// Individual verification results for each parent signature
    pub parent_verification_results: Vec<ParentVerificationResult>,
    /// The original A2A artifact that was wrapped
    pub original_artifact: Value,
    /// Trust level of the signing agent (set when policy-based verification is used)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trust_level: Option<super::trust::TrustLevel>,
    /// Trust policy assessment details (set when policy-based verification is used)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trust_assessment: Option<super::trust::TrustAssessment>,
}

/// Create a chain of custody document for multi-agent workflows
pub fn create_chain_of_custody(artifacts: Vec<Value>) -> Result<Value, JacsError> {
    let mut chain = Vec::new();

    for artifact in artifacts {
        if let Some(sig) = artifact.get(AGENT_SIGNATURE_FIELDNAME) {
            let entry = json!({
                "artifactId": artifact.get("jacsId"),
                "artifactType": artifact.get("jacsType"),
                "timestamp": artifact.get("jacsVersionDate"),
                "agentId": sig.get("agentID"),
                "agentVersion": sig.get("agentVersion"),
                "signatureHash": sig.get("publicKeyHash"),
            });
            chain.push(entry);
        }
    }

    Ok(json!({
        "chainOfCustody": chain,
        "created": time_utils::now_rfc3339(),
        "totalArtifacts": chain.len(),
    }))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_verification_status_is_verified() {
        assert!(VerificationStatus::Verified.is_verified());
        assert!(VerificationStatus::SelfSigned.is_verified());
        assert!(
            !VerificationStatus::Unverified {
                reason: "test".to_string()
            }
            .is_verified()
        );
        assert!(
            !VerificationStatus::Invalid {
                reason: "test".to_string()
            }
            .is_verified()
        );
    }

    #[test]
    fn test_verification_status_is_unverified() {
        assert!(!VerificationStatus::Verified.is_unverified());
        assert!(!VerificationStatus::SelfSigned.is_unverified());
        assert!(
            VerificationStatus::Unverified {
                reason: "test".to_string()
            }
            .is_unverified()
        );
        assert!(
            !VerificationStatus::Invalid {
                reason: "test".to_string()
            }
            .is_unverified()
        );
    }

    #[test]
    fn test_verification_status_is_invalid() {
        assert!(!VerificationStatus::Verified.is_invalid());
        assert!(!VerificationStatus::SelfSigned.is_invalid());
        assert!(
            !VerificationStatus::Unverified {
                reason: "test".to_string()
            }
            .is_invalid()
        );
        assert!(
            VerificationStatus::Invalid {
                reason: "test".to_string()
            }
            .is_invalid()
        );
    }

    #[test]
    fn test_verification_result_creation() {
        let result = VerificationResult {
            status: VerificationStatus::SelfSigned,
            valid: true,
            signer_id: "test-agent".to_string(),
            signer_version: "v1".to_string(),
            artifact_type: "a2a-task".to_string(),
            timestamp: time_utils::now_rfc3339(),
            parent_signatures_valid: true,
            parent_verification_results: vec![],
            original_artifact: json!({"test": "data"}),
            trust_level: None,
            trust_assessment: None,
        };

        assert!(result.valid);
        assert!(result.status.is_verified());
        assert_eq!(result.signer_id, "test-agent");
    }

    #[test]
    fn test_create_chain_of_custody_empty() {
        let chain = create_chain_of_custody(vec![]).unwrap();
        assert_eq!(chain["totalArtifacts"], 0);
    }

    #[test]
    fn test_verification_result_serialization() {
        let result = VerificationResult {
            status: VerificationStatus::Unverified {
                reason: "No public key".to_string(),
            },
            valid: false,
            signer_id: "foreign-agent".to_string(),
            signer_version: "v2".to_string(),
            artifact_type: "a2a-message".to_string(),
            timestamp: "2024-01-01T00:00:00Z".to_string(),
            parent_signatures_valid: true,
            parent_verification_results: vec![],
            original_artifact: json!({"message": "hello"}),
            trust_level: None,
            trust_assessment: None,
        };

        // Should be serializable to JSON
        let json = serde_json::to_string(&result).expect("serialization should succeed");
        assert!(json.contains("Unverified"));
        assert!(json.contains("foreign-agent"));
    }

    // =========================================================================
    // verify_wrapped_artifact_with_policy tests
    // =========================================================================

    use crate::a2a::trust::{A2ATrustPolicy, TrustLevel};
    use crate::a2a::{
        A2A_PROTOCOL_VERSION, AgentCapabilities, AgentCard, AgentExtension, AgentInterface,
        JACS_EXTENSION_URI,
    };

    /// Create a minimal Agent Card for trust policy tests.
    fn make_test_card(
        name: &str,
        with_jacs_extension: bool,
        agent_id: Option<&str>,
        version: Option<&str>,
    ) -> AgentCard {
        let extensions = if with_jacs_extension {
            Some(vec![AgentExtension {
                uri: JACS_EXTENSION_URI.to_string(),
                description: Some("JACS provenance".to_string()),
                required: Some(false),
            }])
        } else {
            None
        };

        let metadata = match (agent_id, version) {
            (Some(id), Some(ver)) => Some(json!({
                "jacsId": id,
                "jacsVersion": ver,
            })),
            (Some(id), None) => Some(json!({ "jacsId": id })),
            _ => None,
        };

        AgentCard {
            name: name.to_string(),
            description: format!("Test agent: {}", name),
            version: "1.0".to_string(),
            protocol_versions: vec![A2A_PROTOCOL_VERSION.to_string()],
            supported_interfaces: vec![AgentInterface {
                url: "https://test.example.com".to_string(),
                protocol_binding: "jsonrpc".to_string(),
                tenant: None,
            }],
            default_input_modes: vec!["text/plain".to_string()],
            default_output_modes: vec!["text/plain".to_string()],
            capabilities: AgentCapabilities {
                streaming: None,
                push_notifications: None,
                extended_agent_card: None,
                extensions,
            },
            skills: vec![],
            provider: None,
            documentation_url: None,
            icon_url: None,
            security_schemes: None,
            security: None,
            signatures: None,
            metadata,
        }
    }

    /// Create a dummy wrapped artifact (not cryptographically valid).
    fn make_dummy_wrapped_artifact(artifact_type: &str, agent_id: &str) -> Value {
        json!({
            "jacsId": "artifact-test-001",
            "jacsVersion": "v1",
            "jacsType": format!("a2a-{}", artifact_type),
            "jacsLevel": "artifact",
            "jacsVersionDate": "2025-01-01T00:00:00Z",
            "$schema": "https://jacs.sh/schemas/header/v1/header.schema.json",
            "a2aArtifact": { "test": "data" },
            "jacsSignature": {
                "agentID": agent_id,
                "agentVersion": "v1",
                "publicKeyHash": "abc123",
                "signature": "deadbeef",
            }
        })
    }

    #[test]
    fn test_policy_open_accepts_non_jacs_agent() {
        let agent = crate::get_empty_agent();
        let card = make_test_card("plain-agent", false, None, None);
        let artifact = make_dummy_wrapped_artifact("task", "foreign-agent");

        let result =
            verify_wrapped_artifact_with_policy(&agent, &artifact, &card, A2ATrustPolicy::Open)
                .unwrap();

        // Open policy always allows — trust level should be Untrusted
        assert_eq!(result.trust_level, Some(TrustLevel::Untrusted));
        assert!(result.trust_assessment.is_some());
        assert!(result.trust_assessment.as_ref().unwrap().allowed);
    }

    #[test]
    fn test_policy_open_accepts_jacs_agent() {
        let agent = crate::get_empty_agent();
        let card = make_test_card("jacs-agent", true, Some("agent-1"), Some("v1"));
        let artifact = make_dummy_wrapped_artifact("message", "agent-1");

        let result =
            verify_wrapped_artifact_with_policy(&agent, &artifact, &card, A2ATrustPolicy::Open)
                .unwrap();

        // Test card has no signatures so card_signature_verified=false → Untrusted.
        // Open policy still allows the agent regardless of trust level.
        assert_eq!(result.trust_level, Some(TrustLevel::Untrusted));
        assert!(result.trust_assessment.as_ref().unwrap().allowed);
    }

    #[test]
    fn test_policy_verified_rejects_non_jacs_agent() {
        let agent = crate::get_empty_agent();
        let card = make_test_card("plain-agent", false, Some("no-jacs"), Some("v1"));
        let artifact = make_dummy_wrapped_artifact("task", "no-jacs");

        let result =
            verify_wrapped_artifact_with_policy(&agent, &artifact, &card, A2ATrustPolicy::Verified)
                .unwrap();

        // Verified policy should reject non-JACS agent
        assert!(!result.valid);
        assert_eq!(result.trust_level, Some(TrustLevel::Untrusted));
        assert!(!result.trust_assessment.as_ref().unwrap().allowed);
        assert!(
            result
                .trust_assessment
                .as_ref()
                .unwrap()
                .reason
                .contains("does not declare JACS provenance")
        );
    }

    #[test]
    fn test_policy_verified_rejects_unsigned_jacs_agent() {
        let agent = crate::get_empty_agent();
        let card = make_test_card("jacs-agent", true, Some("agent-2"), Some("v1"));
        let artifact = make_dummy_wrapped_artifact("task", "agent-2");

        let result =
            verify_wrapped_artifact_with_policy(&agent, &artifact, &card, A2ATrustPolicy::Verified)
                .unwrap();

        // Test card declares JACS extension but has no signatures,
        // so card_signature_verified=false → Untrusted.
        // Verified policy rejects Untrusted agents.
        assert!(!result.valid);
        assert_eq!(result.trust_level, Some(TrustLevel::Untrusted));
        assert!(!result.trust_assessment.as_ref().unwrap().allowed);
    }

    #[test]
    fn test_policy_strict_rejects_jacs_not_trusted_agent() {
        let agent = crate::get_empty_agent();
        let card = make_test_card(
            "jacs-not-trusted",
            true,
            Some("550e8400-e29b-41d4-a716-446655440077"),
            Some("550e8400-e29b-41d4-a716-446655440078"),
        );
        let artifact = make_dummy_wrapped_artifact("task", "550e8400-e29b-41d4-a716-446655440077");

        let result =
            verify_wrapped_artifact_with_policy(&agent, &artifact, &card, A2ATrustPolicy::Strict)
                .unwrap();

        // Strict policy rejects agents not in trust store.
        // Test card has no signatures so trust_level=Untrusted (not JacsVerified).
        assert!(!result.valid);
        assert_eq!(result.trust_level, Some(TrustLevel::Untrusted));
        assert!(!result.trust_assessment.as_ref().unwrap().allowed);
        assert!(
            result
                .trust_assessment
                .as_ref()
                .unwrap()
                .reason
                .contains("not in the local trust store")
        );
    }

    #[test]
    fn test_policy_strict_rejects_non_jacs_agent() {
        let agent = crate::get_empty_agent();
        let card = make_test_card("plain-untrusted", false, None, None);
        let artifact = make_dummy_wrapped_artifact("task", "unknown");

        let result =
            verify_wrapped_artifact_with_policy(&agent, &artifact, &card, A2ATrustPolicy::Strict)
                .unwrap();

        assert!(!result.valid);
        assert_eq!(result.trust_level, Some(TrustLevel::Untrusted));
        assert!(!result.trust_assessment.as_ref().unwrap().allowed);
    }

    #[test]
    fn test_policy_rejection_preserves_artifact_type() {
        let agent = crate::get_empty_agent();
        let card = make_test_card("rejected-agent", false, Some("rej-1"), Some("v1"));
        let artifact = make_dummy_wrapped_artifact("message", "rej-1");

        let result =
            verify_wrapped_artifact_with_policy(&agent, &artifact, &card, A2ATrustPolicy::Verified)
                .unwrap();

        assert!(!result.valid);
        assert_eq!(result.artifact_type, "a2a-message");
        assert_eq!(result.original_artifact, json!({ "test": "data" }));
    }

    #[test]
    fn test_policy_open_proceeds_to_crypto_verification() {
        let agent = crate::get_empty_agent();
        let card = make_test_card("open-agent", false, Some("agent-open"), Some("v1"));
        // Dummy artifact with no valid hash — crypto verification will fail
        let artifact = make_dummy_wrapped_artifact("task", "agent-open");

        let result =
            verify_wrapped_artifact_with_policy(&agent, &artifact, &card, A2ATrustPolicy::Open)
                .unwrap();

        // Trust check passes (Open), but crypto verification should fail
        // (dummy artifact doesn't have a real hash/signature)
        assert!(result.trust_assessment.as_ref().unwrap().allowed);
        assert_eq!(result.trust_level, Some(TrustLevel::Untrusted));
        // Crypto verification fails due to missing/invalid hash
        assert!(!result.valid);
    }

    #[test]
    fn test_verification_result_with_trust_serialization() {
        use crate::a2a::trust::TrustAssessment;

        let result = VerificationResult {
            status: VerificationStatus::Verified,
            valid: true,
            signer_id: "trusted-agent".to_string(),
            signer_version: "v1".to_string(),
            artifact_type: "a2a-task".to_string(),
            timestamp: "2025-01-01T00:00:00Z".to_string(),
            parent_signatures_valid: true,
            parent_verification_results: vec![],
            original_artifact: json!({"data": "test"}),
            trust_level: Some(TrustLevel::JacsVerified),
            trust_assessment: Some(TrustAssessment {
                allowed: true,
                trust_level: TrustLevel::JacsVerified,
                reason: "Verified policy: agent has JACS provenance".to_string(),
                jacs_registered: true,
                agent_id: Some("trusted-agent".to_string()),
                policy: A2ATrustPolicy::Verified,
            }),
        };

        let json_str = serde_json::to_string(&result).expect("should serialize");
        assert!(json_str.contains("trustLevel"));
        assert!(json_str.contains("trustAssessment"));
        assert!(json_str.contains("JacsVerified"));

        // Deserialize back
        let deserialized: VerificationResult =
            serde_json::from_str(&json_str).expect("should deserialize");
        assert_eq!(deserialized.trust_level, Some(TrustLevel::JacsVerified));
        assert!(deserialized.trust_assessment.unwrap().allowed);
    }

    #[test]
    fn test_verification_result_without_trust_omits_fields() {
        let result = VerificationResult {
            status: VerificationStatus::Verified,
            valid: true,
            signer_id: "agent".to_string(),
            signer_version: "v1".to_string(),
            artifact_type: "a2a-task".to_string(),
            timestamp: "2025-01-01T00:00:00Z".to_string(),
            parent_signatures_valid: true,
            parent_verification_results: vec![],
            original_artifact: json!({}),
            trust_level: None,
            trust_assessment: None,
        };

        let json_str = serde_json::to_string(&result).expect("should serialize");
        // When None, these fields should be omitted (skip_serializing_if)
        assert!(!json_str.contains("trustLevel"));
        assert!(!json_str.contains("trustAssessment"));
    }

    // =========================================================================
    // A2A contract schema tests (Task 001)
    // =========================================================================

    /// Validate that VerificationResult serializes to camelCase JSON fields
    /// matching the cross-language contract (TR-3).
    #[test]
    fn test_verification_result_camel_case_contract() {
        let result = VerificationResult {
            status: VerificationStatus::Verified,
            valid: true,
            signer_id: "agent-contract-test".to_string(),
            signer_version: "v1-contract".to_string(),
            artifact_type: "a2a-task".to_string(),
            timestamp: "2025-06-01T00:00:00Z".to_string(),
            parent_signatures_valid: true,
            parent_verification_results: vec![],
            original_artifact: json!({"content": "test"}),
            trust_level: Some(TrustLevel::JacsVerified),
            trust_assessment: Some(crate::a2a::trust::TrustAssessment {
                allowed: true,
                trust_level: TrustLevel::JacsVerified,
                reason: "Contract test".to_string(),
                jacs_registered: true,
                agent_id: Some("agent-contract-test".to_string()),
                policy: A2ATrustPolicy::Verified,
            }),
        };

        let json_value: Value = serde_json::to_value(&result).expect("should serialize to Value");

        // All top-level fields must be camelCase
        assert!(json_value.get("status").is_some(), "missing 'status'");
        assert!(json_value.get("valid").is_some(), "missing 'valid'");
        assert!(json_value.get("signerId").is_some(), "missing 'signerId'");
        assert!(
            json_value.get("signerVersion").is_some(),
            "missing 'signerVersion'"
        );
        assert!(
            json_value.get("artifactType").is_some(),
            "missing 'artifactType'"
        );
        assert!(json_value.get("timestamp").is_some(), "missing 'timestamp'");
        assert!(
            json_value.get("parentSignaturesValid").is_some(),
            "missing 'parentSignaturesValid'"
        );
        assert!(
            json_value.get("parentVerificationResults").is_some(),
            "missing 'parentVerificationResults'"
        );
        assert!(
            json_value.get("originalArtifact").is_some(),
            "missing 'originalArtifact'"
        );
        assert!(
            json_value.get("trustLevel").is_some(),
            "missing 'trustLevel'"
        );
        assert!(
            json_value.get("trustAssessment").is_some(),
            "missing 'trustAssessment'"
        );

        // Verify no snake_case leakage
        assert!(
            json_value.get("signer_id").is_none(),
            "snake_case 'signer_id' should not appear"
        );
        assert!(
            json_value.get("signer_version").is_none(),
            "snake_case 'signer_version' should not appear"
        );
        assert!(
            json_value.get("artifact_type").is_none(),
            "snake_case 'artifact_type' should not appear"
        );
        assert!(
            json_value.get("parent_signatures_valid").is_none(),
            "snake_case 'parent_signatures_valid' should not appear"
        );
        assert!(
            json_value.get("original_artifact").is_none(),
            "snake_case 'original_artifact' should not appear"
        );
        assert!(
            json_value.get("trust_level").is_none(),
            "snake_case 'trust_level' should not appear"
        );
        assert!(
            json_value.get("trust_assessment").is_none(),
            "snake_case 'trust_assessment' should not appear"
        );

        // Verify values
        assert_eq!(json_value["signerId"], "agent-contract-test");
        assert_eq!(json_value["signerVersion"], "v1-contract");
        assert_eq!(json_value["artifactType"], "a2a-task");
        assert_eq!(json_value["valid"], true);
        assert_eq!(json_value["parentSignaturesValid"], true);

        // Trust assessment fields should also be camelCase
        let trust = json_value.get("trustAssessment").unwrap();
        assert!(
            trust.get("trustLevel").is_some(),
            "missing trust.trustLevel"
        );
        assert!(
            trust.get("jacsRegistered").is_some(),
            "missing trust.jacsRegistered"
        );
        assert!(trust.get("agentId").is_some(), "missing trust.agentId");
        assert!(trust.get("policy").is_some(), "missing trust.policy");
        assert!(trust.get("allowed").is_some(), "missing trust.allowed");
        assert!(trust.get("reason").is_some(), "missing trust.reason");
    }

    /// Validate that each VerificationStatus variant produces the expected JSON shape.
    #[test]
    fn test_verification_status_variant_json_shapes() {
        // Verified - simple string
        let verified = serde_json::to_value(&VerificationStatus::Verified).unwrap();
        assert_eq!(verified, json!("Verified"));

        // SelfSigned - simple string
        let self_signed = serde_json::to_value(&VerificationStatus::SelfSigned).unwrap();
        assert_eq!(self_signed, json!("SelfSigned"));

        // Unverified - tagged enum with reason
        let unverified = serde_json::to_value(&VerificationStatus::Unverified {
            reason: "No public key available".to_string(),
        })
        .unwrap();
        assert!(unverified.get("Unverified").is_some());
        assert_eq!(
            unverified["Unverified"]["reason"],
            "No public key available"
        );

        // Invalid - tagged enum with reason
        let invalid = serde_json::to_value(&VerificationStatus::Invalid {
            reason: "Signature mismatch".to_string(),
        })
        .unwrap();
        assert!(invalid.get("Invalid").is_some());
        assert_eq!(invalid["Invalid"]["reason"], "Signature mismatch");
    }

    /// Validate that VerificationResult round-trips correctly through JSON.
    #[test]
    fn test_verification_result_json_round_trip() {
        let original = VerificationResult {
            status: VerificationStatus::Unverified {
                reason: "Foreign key not found".to_string(),
            },
            valid: false,
            signer_id: "foreign-agent-xyz".to_string(),
            signer_version: "v2".to_string(),
            artifact_type: "a2a-message".to_string(),
            timestamp: "2025-06-01T12:00:00Z".to_string(),
            parent_signatures_valid: false,
            parent_verification_results: vec![ParentVerificationResult {
                index: 0,
                artifact_id: "parent-001".to_string(),
                signer_id: "parent-signer".to_string(),
                status: VerificationStatus::Verified,
                verified: true,
            }],
            original_artifact: json!({"message": "hello from foreign agent"}),
            trust_level: None,
            trust_assessment: None,
        };

        let json_str = serde_json::to_string_pretty(&original).unwrap();
        let deserialized: VerificationResult = serde_json::from_str(&json_str).unwrap();

        assert_eq!(deserialized.signer_id, original.signer_id);
        assert_eq!(deserialized.signer_version, original.signer_version);
        assert_eq!(deserialized.artifact_type, original.artifact_type);
        assert_eq!(deserialized.valid, original.valid);
        assert_eq!(
            deserialized.parent_signatures_valid,
            original.parent_signatures_valid
        );
        assert_eq!(
            deserialized.parent_verification_results.len(),
            original.parent_verification_results.len()
        );
        assert_eq!(
            deserialized.parent_verification_results[0].artifact_id,
            "parent-001"
        );
        assert_eq!(
            deserialized.parent_verification_results[0].signer_id,
            "parent-signer"
        );
        assert!(deserialized.parent_verification_results[0].verified);

        // Verify the parent verification result also uses camelCase
        let json_value: Value = serde_json::from_str(&json_str).unwrap();
        let parent = &json_value["parentVerificationResults"][0];
        assert!(
            parent.get("artifactId").is_some(),
            "missing parent.artifactId"
        );
        assert!(parent.get("signerId").is_some(), "missing parent.signerId");
    }

    // =========================================================================
    // Golden serialization tests (Task 006)
    //
    // These tests pin the EXACT JSON output of core verification structs.
    // If any field is renamed, reordered, or its serialization changes,
    // the corresponding golden test will fail — signalling a breaking change
    // to the cross-language contract.
    // =========================================================================

    /// Pin exact JSON for VerificationResult with Verified status.
    #[test]
    fn test_verification_result_golden_verified() {
        let result = VerificationResult {
            status: VerificationStatus::Verified,
            valid: true,
            signer_id: "agent-golden-001".to_string(),
            signer_version: "v1".to_string(),
            artifact_type: "a2a-task".to_string(),
            timestamp: "2025-01-15T10:30:00Z".to_string(),
            parent_signatures_valid: true,
            parent_verification_results: vec![],
            original_artifact: json!({"task": "golden"}),
            trust_level: None,
            trust_assessment: None,
        };

        let actual: Value = serde_json::to_value(&result).unwrap();
        let expected = json!({
            "status": "Verified",
            "valid": true,
            "signerId": "agent-golden-001",
            "signerVersion": "v1",
            "artifactType": "a2a-task",
            "timestamp": "2025-01-15T10:30:00Z",
            "parentSignaturesValid": true,
            "parentVerificationResults": [],
            "originalArtifact": {"task": "golden"}
        });

        assert_eq!(actual, expected, "Golden JSON mismatch for Verified result");
    }

    /// Pin exact JSON for VerificationResult with SelfSigned status.
    #[test]
    fn test_verification_result_golden_self_signed() {
        let result = VerificationResult {
            status: VerificationStatus::SelfSigned,
            valid: true,
            signer_id: "self-signer-001".to_string(),
            signer_version: "v2".to_string(),
            artifact_type: "a2a-message".to_string(),
            timestamp: "2025-02-20T14:00:00Z".to_string(),
            parent_signatures_valid: true,
            parent_verification_results: vec![],
            original_artifact: json!({"msg": "self-signed"}),
            trust_level: None,
            trust_assessment: None,
        };

        let actual: Value = serde_json::to_value(&result).unwrap();
        let expected = json!({
            "status": "SelfSigned",
            "valid": true,
            "signerId": "self-signer-001",
            "signerVersion": "v2",
            "artifactType": "a2a-message",
            "timestamp": "2025-02-20T14:00:00Z",
            "parentSignaturesValid": true,
            "parentVerificationResults": [],
            "originalArtifact": {"msg": "self-signed"}
        });

        assert_eq!(
            actual, expected,
            "Golden JSON mismatch for SelfSigned result"
        );
    }

    /// Pin exact JSON for VerificationResult with Unverified status.
    #[test]
    fn test_verification_result_golden_unverified() {
        let result = VerificationResult {
            status: VerificationStatus::Unverified {
                reason: "Public key not available".to_string(),
            },
            valid: false,
            signer_id: "foreign-agent-xyz".to_string(),
            signer_version: "v3".to_string(),
            artifact_type: "a2a-artifact".to_string(),
            timestamp: "2025-03-10T08:45:00Z".to_string(),
            parent_signatures_valid: true,
            parent_verification_results: vec![],
            original_artifact: json!({"data": "unverified"}),
            trust_level: None,
            trust_assessment: None,
        };

        let actual: Value = serde_json::to_value(&result).unwrap();
        let expected = json!({
            "status": {
                "Unverified": {
                    "reason": "Public key not available"
                }
            },
            "valid": false,
            "signerId": "foreign-agent-xyz",
            "signerVersion": "v3",
            "artifactType": "a2a-artifact",
            "timestamp": "2025-03-10T08:45:00Z",
            "parentSignaturesValid": true,
            "parentVerificationResults": [],
            "originalArtifact": {"data": "unverified"}
        });

        assert_eq!(
            actual, expected,
            "Golden JSON mismatch for Unverified result"
        );
    }

    /// Pin exact JSON for VerificationResult with Invalid status.
    #[test]
    fn test_verification_result_golden_invalid() {
        let result = VerificationResult {
            status: VerificationStatus::Invalid {
                reason: "Signature mismatch".to_string(),
            },
            valid: false,
            signer_id: "bad-actor-agent".to_string(),
            signer_version: "v1".to_string(),
            artifact_type: "a2a-task".to_string(),
            timestamp: "2025-04-01T12:00:00Z".to_string(),
            parent_signatures_valid: false,
            parent_verification_results: vec![],
            original_artifact: json!({"compromised": true}),
            trust_level: None,
            trust_assessment: None,
        };

        let actual: Value = serde_json::to_value(&result).unwrap();
        let expected = json!({
            "status": {
                "Invalid": {
                    "reason": "Signature mismatch"
                }
            },
            "valid": false,
            "signerId": "bad-actor-agent",
            "signerVersion": "v1",
            "artifactType": "a2a-task",
            "timestamp": "2025-04-01T12:00:00Z",
            "parentSignaturesValid": false,
            "parentVerificationResults": [],
            "originalArtifact": {"compromised": true}
        });

        assert_eq!(actual, expected, "Golden JSON mismatch for Invalid result");
    }

    /// Pin exact JSON for VerificationResult with trust fields populated.
    #[test]
    fn test_verification_result_golden_with_trust() {
        use crate::a2a::trust::TrustAssessment;

        let result = VerificationResult {
            status: VerificationStatus::Verified,
            valid: true,
            signer_id: "trusted-agent-abc".to_string(),
            signer_version: "v1".to_string(),
            artifact_type: "a2a-task".to_string(),
            timestamp: "2025-05-01T09:00:00Z".to_string(),
            parent_signatures_valid: true,
            parent_verification_results: vec![],
            original_artifact: json!({"payload": "trusted"}),
            trust_level: Some(TrustLevel::JacsVerified),
            trust_assessment: Some(TrustAssessment {
                allowed: true,
                trust_level: TrustLevel::JacsVerified,
                reason: "Verified policy: agent has JACS provenance extension".to_string(),
                jacs_registered: true,
                agent_id: Some("trusted-agent-abc".to_string()),
                policy: A2ATrustPolicy::Verified,
            }),
        };

        let actual: Value = serde_json::to_value(&result).unwrap();
        let expected = json!({
            "status": "Verified",
            "valid": true,
            "signerId": "trusted-agent-abc",
            "signerVersion": "v1",
            "artifactType": "a2a-task",
            "timestamp": "2025-05-01T09:00:00Z",
            "parentSignaturesValid": true,
            "parentVerificationResults": [],
            "originalArtifact": {"payload": "trusted"},
            "trustLevel": "JacsVerified",
            "trustAssessment": {
                "allowed": true,
                "trustLevel": "JacsVerified",
                "reason": "Verified policy: agent has JACS provenance extension",
                "jacsRegistered": true,
                "agentId": "trusted-agent-abc",
                "policy": "Verified"
            }
        });

        assert_eq!(
            actual, expected,
            "Golden JSON mismatch for result with trust"
        );
    }

    /// Pin exact JSON for ParentVerificationResult.
    #[test]
    fn test_parent_verification_result_golden() {
        let parent = ParentVerificationResult {
            index: 0,
            artifact_id: "parent-artifact-001".to_string(),
            signer_id: "parent-signer-agent".to_string(),
            status: VerificationStatus::Verified,
            verified: true,
        };

        let actual: Value = serde_json::to_value(&parent).unwrap();
        let expected = json!({
            "index": 0,
            "artifactId": "parent-artifact-001",
            "signerId": "parent-signer-agent",
            "status": "Verified",
            "verified": true
        });

        assert_eq!(
            actual, expected,
            "Golden JSON mismatch for ParentVerificationResult"
        );

        // Also verify a parent with Unverified status
        let parent_unverified = ParentVerificationResult {
            index: 2,
            artifact_id: "parent-artifact-003".to_string(),
            signer_id: "unknown-signer".to_string(),
            status: VerificationStatus::Unverified {
                reason: "Key not found".to_string(),
            },
            verified: false,
        };

        let actual2: Value = serde_json::to_value(&parent_unverified).unwrap();
        let expected2 = json!({
            "index": 2,
            "artifactId": "parent-artifact-003",
            "signerId": "unknown-signer",
            "status": {
                "Unverified": {
                    "reason": "Key not found"
                }
            },
            "verified": false
        });

        assert_eq!(
            actual2, expected2,
            "Golden JSON mismatch for ParentVerificationResult (Unverified)"
        );
    }
}