adk-payments 2.3.0

Protocol-neutral agentic commerce and payment orchestration for ADK-Rust
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
use std::sync::Arc;

use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
use chrono::{DateTime, Utc};
use serde::de::DeserializeOwned;
use serde_json::json;

use crate::domain::{
    CommerceMode, EvidenceReference, InterventionKind, InterventionState, InterventionStatus,
    ProtocolEnvelopeDigest, ProtocolExtensions, ProtocolReference, TransactionRecord,
    TransactionState,
};
use crate::kernel::{
    BeginInterventionCommand, CommerceContext, CreateCheckoutCommand, EvidenceLookup,
    EvidenceStore, InterventionService, MerchantCheckoutService, PaymentExecutionOutcome,
    PaymentExecutionResult, PaymentExecutionService, ProtocolCorrelator, ProtocolRefKind,
    StoreEvidenceCommand, StoredEvidence, TransactionLookup, TransactionStore,
    UpdateCheckoutCommand,
};
use crate::protocol::ap2::error::Ap2Error;
use crate::protocol::ap2::ledger::{InMemoryPaymentMandateLedger, PaymentMandateLedger};
use crate::protocol::ap2::mapper::{
    ap2_descriptor, cart_amount_scale, cart_from_cart_mandate, execute_payment_command,
    fulfillment_from_cart_mandate, intent_create_checkout_command, merge_extensions,
    sync_payment_outcome_command, update_record_extensions, update_record_state_from_receipt,
};
use crate::protocol::ap2::types::{
    AuthorizationArtifact, CartMandate, IntentMandate, PaymentMandate, PaymentReceipt,
    PaymentStatusEnvelope,
};
use crate::protocol::ap2::verification::{
    MerchantAuthorizationVerifier, RequireMerchantAuthorization, RequireUserAuthorization,
    UserAuthorizationVerifier, VERIFIED_MERCHANT_NAME_CLAIM, VerifiedAuthorization,
};

/// `ProtocolReference::reference_kind` marking a payment mandate that reached
/// the payment backend.
const EXECUTED_PAYMENT_MANDATE_REF_KIND: &str = "ap2_executed_payment_mandate_id";

struct StoredArtifactSet {
    envelope: crate::domain::ProtocolExtensionEnvelope,
    evidence: Vec<StoredEvidence>,
}

#[derive(Default)]
struct ProtocolRefUpdate {
    intent_ref: Option<String>,
    cart_ref: Option<String>,
    payment_ref: Option<String>,
    executed_payment_ref: Option<String>,
    receipt_ref: Option<String>,
}

/// AP2 alpha adapter over the canonical commerce kernel.
///
/// The adapter fails closed: until a [`MerchantAuthorizationVerifier`] and a
/// [`UserAuthorizationVerifier`] are configured, every merchant, intent, and
/// payment authorization artifact is rejected with
/// [`Ap2Error::AuthorizationVerifierNotConfigured`]. Payment mandates are
/// single-use: a mandate that reached the payment backend is refused when
/// resubmitted, and a transaction executes at most one payment mandate.
///
/// # Example
///
/// ```rust,ignore
/// use adk_payments::protocol::ap2::Ap2Adapter;
///
/// let adapter = Ap2Adapter::new(checkout, payments, transactions, evidence)
///     .with_merchant_authorization_verifier(merchant_jws_verifier)
///     .with_user_authorization_verifier(user_sd_jwt_verifier)
///     .with_intervention_service(interventions);
/// ```
pub struct Ap2Adapter {
    checkout_service: Arc<dyn MerchantCheckoutService>,
    payment_service: Arc<dyn PaymentExecutionService>,
    transaction_store: Arc<dyn TransactionStore>,
    evidence_store: Arc<dyn EvidenceStore>,
    merchant_verifier: Option<Arc<dyn MerchantAuthorizationVerifier>>,
    user_verifier: Option<Arc<dyn UserAuthorizationVerifier>>,
    allow_unverified_authorizations: bool,
    payment_mandate_ledger: Arc<dyn PaymentMandateLedger>,
    intervention_service: Option<Arc<dyn InterventionService>>,
}

impl Ap2Adapter {
    /// Creates a new AP2 adapter bound to the canonical checkout, journal, and evidence services.
    ///
    /// No authorization verifier is configured, so every authorization
    /// artifact is rejected until
    /// [`with_merchant_authorization_verifier`](Self::with_merchant_authorization_verifier)
    /// and [`with_user_authorization_verifier`](Self::with_user_authorization_verifier)
    /// are called. Executed payment mandates are tracked in an
    /// [`InMemoryPaymentMandateLedger`] unless
    /// [`with_payment_mandate_ledger`](Self::with_payment_mandate_ledger) replaces it.
    #[must_use]
    pub fn new(
        checkout_service: Arc<dyn MerchantCheckoutService>,
        payment_service: Arc<dyn PaymentExecutionService>,
        transaction_store: Arc<dyn TransactionStore>,
        evidence_store: Arc<dyn EvidenceStore>,
    ) -> Self {
        Self {
            checkout_service,
            payment_service,
            transaction_store,
            evidence_store,
            merchant_verifier: None,
            user_verifier: None,
            allow_unverified_authorizations: false,
            payment_mandate_ledger: Arc::new(InMemoryPaymentMandateLedger::new()),
            intervention_service: None,
        }
    }

    /// Sets the merchant authorization verifier used for cart mandates.
    #[must_use]
    pub fn with_merchant_authorization_verifier(
        mut self,
        verifier: Arc<dyn MerchantAuthorizationVerifier>,
    ) -> Self {
        self.merchant_verifier = Some(verifier);
        self
    }

    /// Sets the user authorization verifier used for intent and payment mandates.
    #[must_use]
    pub fn with_user_authorization_verifier(
        mut self,
        verifier: Arc<dyn UserAuthorizationVerifier>,
    ) -> Self {
        self.user_verifier = Some(verifier);
        self
    }

    /// Accepts any non-empty authorization artifact where no verifier is configured.
    ///
    /// **Development only.** Forged merchant signatures and user authorizations
    /// pass this check, so a payment mandate carrying any non-empty
    /// `user_authorization` reaches the payment backend. Verifiers configured
    /// through `with_*_authorization_verifier` still apply. Emits one `warn!`
    /// when called.
    #[must_use]
    pub fn allow_unverified_authorizations(mut self) -> Self {
        tracing::warn!(
            merchant_verifier.configured = self.merchant_verifier.is_some(),
            user_verifier.configured = self.user_verifier.is_some(),
            "ap2 adapter accepts unverified authorization artifacts; this is unsafe outside local development"
        );
        self.allow_unverified_authorizations = true;
        self
    }

    /// Replaces the ledger that records consumed payment mandate identifiers.
    ///
    /// Use shared durable storage when several adapter instances serve one
    /// merchant, so a mandate cannot be replayed against another instance.
    #[must_use]
    pub fn with_payment_mandate_ledger(mut self, ledger: Arc<dyn PaymentMandateLedger>) -> Self {
        self.payment_mandate_ledger = ledger;
        self
    }

    /// Enables canonical intervention handling for AP2 return-to-user flows.
    #[must_use]
    pub fn with_intervention_service(
        mut self,
        intervention_service: Arc<dyn InterventionService>,
    ) -> Self {
        self.intervention_service = Some(intervention_service);
        self
    }

    /// Starts or refreshes a human-not-present transaction from an intent mandate.
    ///
    /// # Errors
    ///
    /// Returns an error when the intent is expired, unsigned, fails user
    /// authorization verification, or lacks explicit autonomous authority
    /// constraints.
    pub async fn submit_intent_mandate(
        &self,
        context: CommerceContext,
        intent_mandate: IntentMandate,
        authorization_artifact: Option<AuthorizationArtifact>,
    ) -> Result<TransactionRecord> {
        self.validate_intent_mandate(&context, &intent_mandate, authorization_artifact.as_ref())?;
        let verification = if let Some(artifact) = authorization_artifact.as_ref() {
            Some(self.verify_intent_authorization(&intent_mandate, artifact).await?)
        } else {
            None
        };

        let context = self.normalize_context(context, ProtocolExtensions::default());
        let artifacts = self
            .store_intent_artifacts(
                &context,
                &intent_mandate,
                authorization_artifact.as_ref(),
                verification.as_ref(),
            )
            .await?;
        let intent_ref = artifacts.evidence.first().and_then(|stored| {
            stored
                .evidence_ref
                .digest
                .clone()
                .or_else(|| Some(stored.evidence_ref.evidence_id.clone()))
        });
        let command = intent_create_checkout_command(&intent_mandate, context.clone());
        let record = self.checkout_service.create_checkout(command).await?;

        self.finalize_record(
            &context,
            record,
            artifacts,
            ProtocolRefUpdate { intent_ref, ..ProtocolRefUpdate::default() },
        )
        .await
    }

    /// Creates or updates canonical checkout state from a merchant cart mandate.
    ///
    /// # Errors
    ///
    /// Returns an error when the cart is expired, unsigned, fails merchant
    /// authorization verification, names a merchant other than the verified
    /// signer, carries invalid amounts, or violates the stored intent
    /// constraints for a human-not-present transaction.
    pub async fn submit_cart_mandate(
        &self,
        context: CommerceContext,
        cart_mandate: CartMandate,
    ) -> Result<TransactionRecord> {
        self.validate_not_expired("cart_expiry", &cart_mandate.contents.cart_expiry)?;
        let context = self.normalize_context(context, ProtocolExtensions::default());

        let merchant_authorization = cart_mandate
            .merchant_authorization
            .clone()
            .map(|value| AuthorizationArtifact::new("merchant_authorization", value, "text/plain"))
            .ok_or_else(|| {
                AdkError::from(Ap2Error::MissingMerchantAuthorization {
                    cart_id: cart_mandate.contents.id.clone(),
                })
            })?;
        let verification =
            self.verify_cart_authorization(&cart_mandate, &merchant_authorization).await?;
        if let Some(verified) =
            verification.claims.get(VERIFIED_MERCHANT_NAME_CLAIM).and_then(|name| name.as_str())
            && !verified.eq_ignore_ascii_case(&cart_mandate.contents.merchant_name)
        {
            return Err(Ap2Error::MerchantIdentityMismatch {
                claimed: cart_mandate.contents.merchant_name.clone(),
                verified: verified.to_string(),
            }
            .into());
        }

        let existing = self.lookup(&context).await?;
        if let Some(record) = existing.as_ref() {
            self.validate_intent_constraints(&context, record, &cart_mandate).await?;
        }
        let cart = cart_from_cart_mandate(&cart_mandate)?;
        let fulfillment = fulfillment_from_cart_mandate(&cart_mandate)?;

        let artifacts = self
            .store_cart_artifacts(&context, &cart_mandate, &merchant_authorization, &verification)
            .await?;

        let record = if existing.is_some() {
            self.checkout_service
                .update_checkout(UpdateCheckoutCommand {
                    context: context.clone(),
                    cart: Some(cart),
                    fulfillment,
                })
                .await?
        } else {
            self.checkout_service
                .create_checkout(CreateCheckoutCommand {
                    context: context.clone(),
                    cart,
                    fulfillment,
                })
                .await?
        };

        self.finalize_record(
            &context,
            record,
            artifacts,
            ProtocolRefUpdate {
                cart_ref: Some(cart_mandate.contents.id.clone()),
                ..ProtocolRefUpdate::default()
            },
        )
        .await
    }

    /// Executes or escalates a payment mandate against the canonical payment service.
    ///
    /// Payment mandates are single-use. The mandate identifier is consumed in
    /// the [`PaymentMandateLedger`] immediately before the payment backend is
    /// called and recorded on the transaction afterwards, so a resubmitted
    /// mandate never executes twice and a transaction never executes a second
    /// mandate.
    ///
    /// # Errors
    ///
    /// Returns an error when the mandate does not match the current cart, fails
    /// user authorization verification, was already executed, targets a
    /// transaction that already executed a payment or is bound to another
    /// mandate, or the flow lacks user authorization and cannot proceed
    /// autonomously.
    pub async fn submit_payment_mandate(
        &self,
        context: CommerceContext,
        payment_mandate: PaymentMandate,
    ) -> Result<PaymentExecutionResult> {
        let context = self.normalize_context(context, ProtocolExtensions::default());
        let existing = self.lookup(&context).await?.ok_or_else(|| {
            AdkError::from(Ap2Error::TransactionNotFound {
                transaction_id: context.transaction_id.as_str().to_string(),
            })
        })?;
        self.ensure_payment_mandate_admissible(&existing, &payment_mandate)?;
        let cart_mandate: CartMandate =
            self.load_latest_json(&context, &existing, "cart_mandate").await?.ok_or_else(|| {
                AdkError::from(Ap2Error::TransactionNotFound {
                    transaction_id: context.transaction_id.as_str().to_string(),
                })
            })?;
        self.validate_payment_mandate_against_cart(&payment_mandate, &cart_mandate)?;
        let amount_scale = cart_amount_scale(&cart_mandate)?;

        let authorization = match payment_mandate.user_authorization.clone() {
            Some(user_authorization) => {
                let artifact = AuthorizationArtifact::new(
                    "user_authorization",
                    user_authorization,
                    "text/plain",
                );
                let verification =
                    self.verify_payment_authorization(&payment_mandate, &artifact).await?;
                Some((artifact, verification))
            }
            None => {
                if !self.evaluate_autonomous_authority(&context, &existing, &cart_mandate).await? {
                    let artifacts = self
                        .store_payment_artifacts(&context, &payment_mandate, None, None)
                        .await?;
                    return self
                        .begin_user_reconfirmation(
                            context,
                            existing,
                            cart_mandate,
                            payment_mandate,
                            artifacts.envelope,
                            artifacts.evidence,
                        )
                        .await;
                }
                None
            }
        };

        let payment_mandate_id =
            payment_mandate.payment_mandate_contents.payment_mandate_id.clone();
        if let Some(previous) = self
            .payment_mandate_ledger
            .consume(&payment_mandate_id, &context.transaction_id)
            .await?
        {
            return Err(Ap2Error::PaymentMandateReplayed {
                payment_mandate_id,
                transaction_id: previous.as_str().to_string(),
            }
            .into());
        }

        let artifacts = self
            .store_payment_artifacts(
                &context,
                &payment_mandate,
                authorization.as_ref().map(|(artifact, _)| artifact),
                authorization.as_ref().map(|(_, verification)| verification),
            )
            .await?;
        let evidence = artifacts.evidence;
        let supporting_evidence_refs = self.ap2_evidence_refs(&existing, &evidence);
        let payment_envelope = self.payment_envelope(
            &payment_mandate,
            authorization.as_ref().map(|(_, verification)| verification),
            &evidence,
        );
        let mut command = execute_payment_command(
            &payment_mandate,
            amount_scale,
            self.normalize_context(
                context.clone(),
                ProtocolExtensions::from(vec![payment_envelope.clone()]),
            ),
            supporting_evidence_refs,
        )?;
        command.extensions = ProtocolExtensions::from(vec![payment_envelope.clone()]);

        let result = self.payment_service.execute_payment(command).await?;
        let transaction = self
            .finalize_record(
                &context,
                result.transaction.clone(),
                StoredArtifactSet { envelope: payment_envelope, evidence: evidence.clone() },
                ProtocolRefUpdate {
                    payment_ref: Some(payment_mandate_id.clone()),
                    executed_payment_ref: Some(payment_mandate_id),
                    ..ProtocolRefUpdate::default()
                },
            )
            .await?;

        let mut generated_evidence_refs = result.generated_evidence_refs;
        for stored in evidence {
            if !generated_evidence_refs.contains(&stored.evidence_ref) {
                generated_evidence_refs.push(stored.evidence_ref);
            }
        }

        Ok(PaymentExecutionResult {
            outcome: result.outcome,
            transaction,
            order: result.order,
            intervention: result.intervention,
            generated_evidence_refs,
        })
    }

    /// Applies a final AP2 payment receipt to canonical transaction state.
    ///
    /// # Errors
    ///
    /// Returns an error when the underlying transaction does not exist or the
    /// receipt references a payment mandate other than the one bound to the
    /// transaction.
    pub async fn apply_payment_receipt(
        &self,
        context: CommerceContext,
        payment_receipt: PaymentReceipt,
    ) -> Result<TransactionRecord> {
        let context = self.normalize_context(context, ProtocolExtensions::default());
        let existing = self.lookup(&context).await?;
        if let Some(bound) = existing
            .as_ref()
            .and_then(|record| record.protocol_refs.ap2_payment_mandate_id.as_deref())
            && bound != payment_receipt.payment_mandate_id
        {
            return Err(Ap2Error::PaymentMandateMismatch {
                payment_mandate_id: payment_receipt.payment_mandate_id.clone(),
                field: "payment_receipt.payment_mandate_id".to_string(),
            }
            .into());
        }
        let artifacts = self.store_receipt_artifacts(&context, &payment_receipt).await?;
        let mut command =
            sync_payment_outcome_command(existing.as_ref(), &payment_receipt, context.clone());
        command.generated_evidence_refs =
            artifacts.evidence.iter().map(|stored| stored.evidence_ref.clone()).collect();
        command.context.extensions = merge_extensions(
            command.context.extensions,
            ProtocolExtensions::from(vec![artifacts.envelope.clone()]),
        );

        let mut record = self.payment_service.sync_payment_outcome(command).await?;
        update_record_state_from_receipt(&mut record, &payment_receipt);
        self.finalize_record(
            &context,
            record,
            artifacts,
            ProtocolRefUpdate {
                payment_ref: Some(payment_receipt.payment_mandate_id.clone()),
                receipt_ref: Some(payment_receipt.payment_id.clone()),
                ..ProtocolRefUpdate::default()
            },
        )
        .await
    }

    async fn verify_cart_authorization(
        &self,
        mandate: &CartMandate,
        artifact: &AuthorizationArtifact,
    ) -> Result<VerifiedAuthorization> {
        match (&self.merchant_verifier, self.allow_unverified_authorizations) {
            (Some(verifier), _) => verifier.verify_cart_authorization(mandate, artifact).await,
            (None, true) => {
                RequireMerchantAuthorization.verify_cart_authorization(mandate, artifact).await
            }
            (None, false) => Err(Ap2Error::AuthorizationVerifierNotConfigured {
                artifact_kind: "merchant_authorization".to_string(),
            }
            .into()),
        }
    }

    async fn verify_intent_authorization(
        &self,
        mandate: &IntentMandate,
        artifact: &AuthorizationArtifact,
    ) -> Result<VerifiedAuthorization> {
        match (&self.user_verifier, self.allow_unverified_authorizations) {
            (Some(verifier), _) => verifier.verify_intent_authorization(mandate, artifact).await,
            (None, true) => {
                RequireUserAuthorization.verify_intent_authorization(mandate, artifact).await
            }
            (None, false) => Err(Ap2Error::AuthorizationVerifierNotConfigured {
                artifact_kind: "intent_authorization".to_string(),
            }
            .into()),
        }
    }

    async fn verify_payment_authorization(
        &self,
        mandate: &PaymentMandate,
        artifact: &AuthorizationArtifact,
    ) -> Result<VerifiedAuthorization> {
        match (&self.user_verifier, self.allow_unverified_authorizations) {
            (Some(verifier), _) => verifier.verify_payment_authorization(mandate, artifact).await,
            (None, true) => {
                RequireUserAuthorization.verify_payment_authorization(mandate, artifact).await
            }
            (None, false) => Err(Ap2Error::AuthorizationVerifierNotConfigured {
                artifact_kind: "user_authorization".to_string(),
            }
            .into()),
        }
    }

    /// Refuses a payment mandate for a transaction that already executed a
    /// payment, can no longer be paid, or is bound to a different mandate.
    fn ensure_payment_mandate_admissible(
        &self,
        record: &TransactionRecord,
        payment_mandate: &PaymentMandate,
    ) -> Result<()> {
        let transaction_id = record.transaction_id.as_str().to_string();
        let payment_mandate_id = &payment_mandate.payment_mandate_contents.payment_mandate_id;
        if let Some(executed) = record
            .protocol_refs
            .additional
            .iter()
            .find(|reference| reference.reference_kind == EXECUTED_PAYMENT_MANDATE_REF_KIND)
        {
            return Err(if &executed.reference_value == payment_mandate_id {
                Ap2Error::PaymentMandateReplayed {
                    payment_mandate_id: payment_mandate_id.clone(),
                    transaction_id,
                }
            } else {
                Ap2Error::TransactionAlreadyPaid {
                    transaction_id,
                    executed_payment_mandate_id: executed.reference_value.clone(),
                }
            }
            .into());
        }
        match &record.state {
            TransactionState::Authorized
            | TransactionState::Completed
            | TransactionState::Canceled
            | TransactionState::Failed => {
                return Err(Ap2Error::TransactionNotPayable {
                    transaction_id,
                    state: format!("{:?}", record.state.tag()),
                }
                .into());
            }
            TransactionState::Draft
            | TransactionState::Negotiating
            | TransactionState::AwaitingUserAuthorization
            | TransactionState::AwaitingPaymentMethod
            | TransactionState::InterventionRequired(_) => {}
        }
        if let Some(bound) = record.protocol_refs.ap2_payment_mandate_id.as_deref()
            && bound != payment_mandate_id
        {
            return Err(Ap2Error::PaymentMandateRebind {
                transaction_id,
                bound_payment_mandate_id: bound.to_string(),
                payment_mandate_id: payment_mandate_id.clone(),
            }
            .into());
        }
        Ok(())
    }

    async fn begin_user_reconfirmation(
        &self,
        context: CommerceContext,
        existing: TransactionRecord,
        cart_mandate: CartMandate,
        payment_mandate: PaymentMandate,
        envelope: crate::domain::ProtocolExtensionEnvelope,
        evidence: Vec<StoredEvidence>,
    ) -> Result<PaymentExecutionResult> {
        let intervention_service = self.intervention_service.as_ref().ok_or_else(|| {
            AdkError::from(Ap2Error::InterventionServiceRequired {
                transaction_id: context.transaction_id.as_str().to_string(),
            })
        })?;
        let expires_at = self
            .load_latest_json::<IntentMandate>(&context, &existing, "intent_mandate")
            .await?
            .map(|intent| self.parse_timestamp("intent_expiry", &intent.intent_expiry))
            .transpose()?
            .or_else(|| {
                self.parse_timestamp("cart_expiry", &cart_mandate.contents.cart_expiry).ok()
            });
        let intervention = InterventionState {
            intervention_id: format!("ap2-reconfirm-{}", context.transaction_id.as_str()),
            kind: InterventionKind::BuyerReconfirmation,
            status: InterventionStatus::Pending,
            instructions: Some(
                "return to the user for explicit AP2 cart or payment confirmation".to_string(),
            ),
            continuation_token: Some(format!("ap2:return:{}", context.transaction_id.as_str())),
            requested_by: Some(context.actor.clone()),
            expires_at,
            extensions: ProtocolExtensions::default(),
        };
        let record = intervention_service
            .begin_intervention(BeginInterventionCommand {
                context: context.clone(),
                intervention: intervention.clone(),
            })
            .await?;
        let transaction = self
            .finalize_record(
                &context,
                record,
                StoredArtifactSet { envelope, evidence: evidence.clone() },
                ProtocolRefUpdate {
                    payment_ref: Some(payment_mandate.payment_mandate_contents.payment_mandate_id),
                    ..ProtocolRefUpdate::default()
                },
            )
            .await?;

        Ok(PaymentExecutionResult {
            outcome: PaymentExecutionOutcome::InterventionRequired,
            order: transaction.order.clone(),
            transaction,
            intervention: Some(intervention),
            generated_evidence_refs: evidence
                .into_iter()
                .map(|stored| stored.evidence_ref)
                .collect(),
        })
    }

    fn normalize_context(
        &self,
        mut context: CommerceContext,
        extensions: ProtocolExtensions,
    ) -> CommerceContext {
        context.protocol = ap2_descriptor();
        context.extensions = merge_extensions(context.extensions, extensions);
        context
    }

    async fn lookup(&self, context: &CommerceContext) -> Result<Option<TransactionRecord>> {
        self.transaction_store
            .get(TransactionLookup {
                transaction_id: context.transaction_id.clone(),
                session_identity: context.session_identity.clone(),
            })
            .await
    }

    fn validate_intent_mandate(
        &self,
        context: &CommerceContext,
        intent_mandate: &IntentMandate,
        authorization_artifact: Option<&AuthorizationArtifact>,
    ) -> Result<()> {
        self.validate_not_expired("intent_expiry", &intent_mandate.intent_expiry)?;
        if context.mode == CommerceMode::HumanNotPresent {
            if authorization_artifact.is_none() {
                return Err(Ap2Error::MissingIntentAuthorization {
                    transaction_id: context.transaction_id.as_str().to_string(),
                }
                .into());
            }
            if !self.has_authority_constraints(intent_mandate) {
                return Err(Ap2Error::MissingAuthorityConstraints {
                    transaction_id: context.transaction_id.as_str().to_string(),
                }
                .into());
            }
        }
        Ok(())
    }

    /// Returns `true` when the intent bounds who or what the agent may buy.
    ///
    /// `requires_refundability` narrows item terms but not the merchant or
    /// product, so it does not count on its own.
    fn has_authority_constraints(&self, intent_mandate: &IntentMandate) -> bool {
        intent_mandate.merchants.as_ref().is_some_and(|merchants| !merchants.is_empty())
            || intent_mandate.skus.as_ref().is_some_and(|skus| !skus.is_empty())
    }

    /// Checks a cart against the stored human-not-present intent constraints.
    ///
    /// The merchant allow-list is compared against `contents.merchant_name`.
    /// That name is only as trustworthy as the merchant authorization
    /// verifier: when the verifier sets `VERIFIED_MERCHANT_NAME_CLAIM`,
    /// `submit_cart_mandate` has already rejected carts whose name differs
    /// from the verified signer; otherwise the comparison relies on the
    /// verifier binding the signing key to the named merchant.
    async fn validate_intent_constraints(
        &self,
        context: &CommerceContext,
        existing: &TransactionRecord,
        cart_mandate: &CartMandate,
    ) -> Result<()> {
        if context.mode != CommerceMode::HumanNotPresent {
            return Ok(());
        }
        let Some(intent_mandate) =
            self.load_latest_json::<IntentMandate>(context, existing, "intent_mandate").await?
        else {
            return Ok(());
        };
        self.validate_not_expired("intent_expiry", &intent_mandate.intent_expiry)?;
        if let Some(merchants) =
            intent_mandate.merchants.as_ref().filter(|merchants| !merchants.is_empty())
        {
            let merchant_name = cart_mandate.contents.merchant_name.to_ascii_lowercase();
            let allowed =
                merchants.iter().map(|merchant| merchant.to_ascii_lowercase()).collect::<Vec<_>>();
            if !allowed.iter().any(|merchant| merchant == &merchant_name) {
                return Err(Ap2Error::MerchantNotAuthorized {
                    merchant_name: cart_mandate.contents.merchant_name.clone(),
                }
                .into());
            }
        }

        if intent_mandate.skus.as_ref().is_some_and(|skus| !skus.is_empty()) {
            return Err(Ap2Error::SkuConstraintUnverifiable.into());
        }

        if intent_mandate.requires_refundability {
            let all_refundable = cart_mandate
                .contents
                .payment_request
                .details
                .display_items
                .iter()
                .all(|item| item.refund_period > 0);
            if !all_refundable {
                return Err(Ap2Error::RefundabilityRequired.into());
            }
        }

        Ok(())
    }

    fn validate_payment_mandate_against_cart(
        &self,
        payment_mandate: &PaymentMandate,
        cart_mandate: &CartMandate,
    ) -> Result<()> {
        let payment_details_id = &payment_mandate.payment_mandate_contents.payment_details_id;
        if payment_details_id != &cart_mandate.contents.payment_request.details.id {
            return Err(Ap2Error::PaymentMandateMismatch {
                payment_mandate_id: payment_mandate
                    .payment_mandate_contents
                    .payment_mandate_id
                    .clone(),
                field: "payment_details_id".to_string(),
            }
            .into());
        }
        if payment_mandate.payment_mandate_contents.payment_response.request_id
            != cart_mandate.contents.payment_request.details.id
        {
            return Err(Ap2Error::PaymentMandateMismatch {
                payment_mandate_id: payment_mandate
                    .payment_mandate_contents
                    .payment_mandate_id
                    .clone(),
                field: "payment_response.request_id".to_string(),
            }
            .into());
        }
        if payment_mandate.payment_mandate_contents.payment_details_total
            != cart_mandate.contents.payment_request.details.total
        {
            return Err(Ap2Error::PaymentMandateMismatch {
                payment_mandate_id: payment_mandate
                    .payment_mandate_contents
                    .payment_mandate_id
                    .clone(),
                field: "payment_details_total".to_string(),
            }
            .into());
        }
        self.validate_not_expired("cart_expiry", &cart_mandate.contents.cart_expiry)
    }

    async fn evaluate_autonomous_authority(
        &self,
        context: &CommerceContext,
        existing: &TransactionRecord,
        cart_mandate: &CartMandate,
    ) -> Result<bool> {
        if context.mode != CommerceMode::HumanNotPresent {
            return Err(Ap2Error::MissingUserAuthorization {
                payment_mandate_id: context.transaction_id.as_str().to_string(),
            }
            .into());
        }
        let Some(intent_mandate) =
            self.load_latest_json::<IntentMandate>(context, existing, "intent_mandate").await?
        else {
            return Err(Ap2Error::MissingIntentAuthorization {
                transaction_id: context.transaction_id.as_str().to_string(),
            }
            .into());
        };
        self.validate_intent_constraints(context, existing, cart_mandate).await?;
        if intent_mandate.user_cart_confirmation_required
            || cart_mandate.contents.user_cart_confirmation_required
        {
            return Ok(false);
        }
        Ok(true)
    }

    fn parse_timestamp(&self, field: &str, value: &str) -> Result<DateTime<Utc>> {
        DateTime::parse_from_rfc3339(value).map(|timestamp| timestamp.with_timezone(&Utc)).map_err(
            |_| {
                AdkError::from(Ap2Error::InvalidTimestamp {
                    field: field.to_string(),
                    value: value.to_string(),
                })
            },
        )
    }

    fn validate_not_expired(&self, field: &str, value: &str) -> Result<()> {
        let timestamp = self.parse_timestamp(field, value)?;
        if timestamp < Utc::now() {
            return Err(Ap2Error::ExpiredArtifact {
                field: field.to_string(),
                expires_at: timestamp.to_rfc3339(),
            }
            .into());
        }
        Ok(())
    }

    async fn store_json(
        &self,
        context: &CommerceContext,
        artifact_kind: &str,
        unique_id: &str,
        payload: &impl serde::Serialize,
    ) -> Result<StoredEvidence> {
        self.evidence_store
            .store(StoreEvidenceCommand {
                transaction_id: context.transaction_id.clone(),
                session_identity: context.session_identity.clone(),
                evidence_ref: EvidenceReference {
                    evidence_id: format!("{artifact_kind}:{unique_id}"),
                    protocol: ap2_descriptor(),
                    artifact_kind: artifact_kind.to_string(),
                    digest: None,
                },
                body: serde_json::to_vec(payload).map_err(|err| {
                    AdkError::new(
                        ErrorComponent::Server,
                        ErrorCategory::InvalidInput,
                        "payments.ap2.serialize_failed",
                        format!("failed to serialize AP2 evidence: {err}"),
                    )
                })?,
                content_type: "application/json".to_string(),
            })
            .await
    }

    async fn store_inline_artifact(
        &self,
        context: &CommerceContext,
        artifact_kind: &str,
        unique_id: &str,
        artifact: &AuthorizationArtifact,
    ) -> Result<StoredEvidence> {
        self.evidence_store
            .store(StoreEvidenceCommand {
                transaction_id: context.transaction_id.clone(),
                session_identity: context.session_identity.clone(),
                evidence_ref: EvidenceReference {
                    evidence_id: format!("{artifact_kind}:{unique_id}"),
                    protocol: ap2_descriptor(),
                    artifact_kind: artifact_kind.to_string(),
                    digest: None,
                },
                body: artifact.value.as_bytes().to_vec(),
                content_type: artifact.content_type.clone(),
            })
            .await
    }

    async fn load_latest_json<T>(
        &self,
        context: &CommerceContext,
        record: &TransactionRecord,
        artifact_kind: &str,
    ) -> Result<Option<T>>
    where
        T: DeserializeOwned,
    {
        let Some(evidence_ref) = record
            .evidence_refs
            .iter()
            .rev()
            .find(|evidence_ref| {
                evidence_ref.protocol.name == "ap2" && evidence_ref.artifact_kind == artifact_kind
            })
            .cloned()
        else {
            return Ok(None);
        };

        let Some(stored) = self
            .evidence_store
            .load(EvidenceLookup {
                evidence_ref,
                session_identity: context.session_identity.clone(),
            })
            .await?
        else {
            return Ok(None);
        };

        serde_json::from_slice(&stored.body).map(Some).map_err(|err| {
            AdkError::new(
                ErrorComponent::Artifact,
                ErrorCategory::Internal,
                "payments.ap2.evidence_decode_failed",
                format!(
                    "failed to decode stored AP2 `{artifact_kind}` evidence for transaction `{}`: {err}",
                    context.transaction_id
                ),
            )
        })
    }

    async fn store_intent_artifacts(
        &self,
        context: &CommerceContext,
        intent_mandate: &IntentMandate,
        authorization_artifact: Option<&AuthorizationArtifact>,
        verification: Option<&VerifiedAuthorization>,
    ) -> Result<StoredArtifactSet> {
        let mandate = self
            .store_json(context, "intent_mandate", context.transaction_id.as_str(), intent_mandate)
            .await?;
        let mut envelope = crate::domain::ProtocolExtensionEnvelope::new(ap2_descriptor())
            .with_field("artifact_kind", json!("intent_mandate"))
            .with_field("intent_expiry", json!(intent_mandate.intent_expiry))
            .with_field(
                "user_cart_confirmation_required",
                json!(intent_mandate.user_cart_confirmation_required),
            )
            .with_field(
                "has_merchant_constraints",
                json!(
                    intent_mandate
                        .merchants
                        .as_ref()
                        .is_some_and(|merchants| !merchants.is_empty())
                ),
            )
            .with_field(
                "has_sku_constraints",
                json!(intent_mandate.skus.as_ref().is_some_and(|skus| !skus.is_empty())),
            )
            .with_field("requires_refundability", json!(intent_mandate.requires_refundability));
        let mut evidence = vec![mandate.clone()];
        envelope.evidence_refs.push(mandate.evidence_ref.clone());

        if let Some(artifact) = authorization_artifact {
            let stored = self
                .store_inline_artifact(
                    context,
                    "intent_authorization",
                    context.transaction_id.as_str(),
                    artifact,
                )
                .await?;
            envelope.evidence_refs.push(stored.evidence_ref.clone());
            envelope.fields.insert(
                "intent_authorization_artifact".to_string(),
                json!({
                    "artifactType": artifact.artifact_type,
                    "contentType": artifact.content_type,
                }),
            );
            evidence.push(stored);
        }
        if let Some(verification) = verification {
            envelope
                .fields
                .insert("intent_authorization_verification".to_string(), json!(verification));
        }

        Ok(StoredArtifactSet { envelope, evidence })
    }

    async fn store_cart_artifacts(
        &self,
        context: &CommerceContext,
        cart_mandate: &CartMandate,
        merchant_authorization: &AuthorizationArtifact,
        verification: &VerifiedAuthorization,
    ) -> Result<StoredArtifactSet> {
        let mandate = self
            .store_json(context, "cart_mandate", &cart_mandate.contents.id, cart_mandate)
            .await?;
        let authorization = self
            .store_inline_artifact(
                context,
                "merchant_authorization",
                &cart_mandate.contents.id,
                merchant_authorization,
            )
            .await?;
        let all_items_refundable = cart_mandate
            .contents
            .payment_request
            .details
            .display_items
            .iter()
            .all(|item| item.refund_period > 0);
        let mut envelope = crate::domain::ProtocolExtensionEnvelope::new(ap2_descriptor())
            .with_field("artifact_kind", json!("cart_mandate"))
            .with_field("cart_id", json!(cart_mandate.contents.id))
            .with_field(
                "payment_details_id",
                json!(cart_mandate.contents.payment_request.details.id),
            )
            .with_field("cart_expiry", json!(cart_mandate.contents.cart_expiry))
            .with_field("merchant_name", json!(cart_mandate.contents.merchant_name))
            .with_field(
                "user_cart_confirmation_required",
                json!(cart_mandate.contents.user_cart_confirmation_required),
            )
            .with_field("total", json!(cart_mandate.contents.payment_request.details.total))
            .with_field("all_items_refundable", json!(all_items_refundable));
        envelope.evidence_refs.push(mandate.evidence_ref.clone());
        envelope.evidence_refs.push(authorization.evidence_ref.clone());
        envelope
            .fields
            .insert("merchant_authorization_verification".to_string(), json!(verification));
        Ok(StoredArtifactSet { envelope, evidence: vec![mandate, authorization] })
    }

    async fn store_payment_artifacts(
        &self,
        context: &CommerceContext,
        payment_mandate: &PaymentMandate,
        user_authorization: Option<&AuthorizationArtifact>,
        verification: Option<&VerifiedAuthorization>,
    ) -> Result<StoredArtifactSet> {
        let mandate = self
            .store_json(
                context,
                "payment_mandate",
                &payment_mandate.payment_mandate_contents.payment_mandate_id,
                payment_mandate,
            )
            .await?;
        let mut envelope =
            self.payment_envelope(payment_mandate, verification, std::slice::from_ref(&mandate));
        let mut evidence = vec![mandate];
        if let Some(user_authorization) = user_authorization {
            let authorization = self
                .store_inline_artifact(
                    context,
                    "user_authorization",
                    &payment_mandate.payment_mandate_contents.payment_mandate_id,
                    user_authorization,
                )
                .await?;
            envelope.evidence_refs.push(authorization.evidence_ref.clone());
            evidence.push(authorization);
        }

        Ok(StoredArtifactSet { envelope, evidence })
    }

    async fn store_receipt_artifacts(
        &self,
        context: &CommerceContext,
        payment_receipt: &PaymentReceipt,
    ) -> Result<StoredArtifactSet> {
        let receipt = self
            .store_json(context, "payment_receipt", &payment_receipt.payment_id, payment_receipt)
            .await?;
        let status = match payment_receipt.payment_status {
            PaymentStatusEnvelope::Success(_) => "success",
            PaymentStatusEnvelope::Error(_) => "error",
            PaymentStatusEnvelope::Failure(_) => "failure",
        };
        let method_name = payment_receipt
            .payment_method_details
            .as_ref()
            .and_then(|details| details.get("method_name"))
            .and_then(serde_json::Value::as_str);
        let mut envelope = crate::domain::ProtocolExtensionEnvelope::new(ap2_descriptor())
            .with_field("artifact_kind", json!("payment_receipt"))
            .with_field("payment_mandate_id", json!(payment_receipt.payment_mandate_id))
            .with_field("timestamp", json!(payment_receipt.timestamp))
            .with_field("payment_id", json!(payment_receipt.payment_id))
            .with_field("amount", json!(payment_receipt.amount))
            .with_field("status", json!(status));
        if let Some(method_name) = method_name {
            envelope = envelope.with_field("method_name", json!(method_name));
        }
        envelope.evidence_refs.push(receipt.evidence_ref.clone());
        Ok(StoredArtifactSet { envelope, evidence: vec![receipt] })
    }

    fn payment_envelope(
        &self,
        payment_mandate: &PaymentMandate,
        verification: Option<&VerifiedAuthorization>,
        evidence: &[StoredEvidence],
    ) -> crate::domain::ProtocolExtensionEnvelope {
        let mut envelope = crate::domain::ProtocolExtensionEnvelope::new(ap2_descriptor())
            .with_field("artifact_kind", json!("payment_mandate"))
            .with_field(
                "payment_mandate_id",
                json!(payment_mandate.payment_mandate_contents.payment_mandate_id),
            )
            .with_field(
                "payment_details_id",
                json!(payment_mandate.payment_mandate_contents.payment_details_id),
            )
            .with_field(
                "payment_request_id",
                json!(payment_mandate.payment_mandate_contents.payment_response.request_id),
            )
            .with_field(
                "payment_details_total",
                json!(payment_mandate.payment_mandate_contents.payment_details_total),
            )
            .with_field(
                "method_name",
                json!(payment_mandate.payment_mandate_contents.payment_response.method_name),
            )
            .with_field(
                "merchant_agent",
                json!(payment_mandate.payment_mandate_contents.merchant_agent),
            )
            .with_field("timestamp", json!(payment_mandate.payment_mandate_contents.timestamp))
            .with_field(
                "user_authorization_present",
                json!(payment_mandate.user_authorization.is_some()),
            );
        envelope.evidence_refs.extend(evidence.iter().map(|stored| stored.evidence_ref.clone()));
        if let Some(verification) = verification {
            envelope
                .fields
                .insert("user_authorization_verification".to_string(), json!(verification));
        }
        envelope
    }

    fn ap2_evidence_refs(
        &self,
        existing: &TransactionRecord,
        new_evidence: &[StoredEvidence],
    ) -> Vec<EvidenceReference> {
        let mut refs = existing
            .evidence_refs
            .iter()
            .filter(|evidence_ref| evidence_ref.protocol.name == "ap2")
            .cloned()
            .collect::<Vec<_>>();
        for stored in new_evidence {
            if !refs.contains(&stored.evidence_ref) {
                refs.push(stored.evidence_ref.clone());
            }
        }
        refs
    }

    async fn finalize_record(
        &self,
        context: &CommerceContext,
        mut record: TransactionRecord,
        artifacts: StoredArtifactSet,
        refs: ProtocolRefUpdate,
    ) -> Result<TransactionRecord> {
        if let Some(existing) = self.lookup(context).await? {
            self.merge_existing(&mut record, existing);
        }
        record.session_identity = context.session_identity.clone();
        update_record_extensions(&mut record, artifacts.envelope);
        for stored in artifacts.evidence {
            if !record.evidence_refs.contains(&stored.evidence_ref) {
                record.attach_evidence_ref(stored.evidence_ref.clone());
            }
            if !record
                .evidence_digests
                .iter()
                .any(|digest| digest.evidence_ref == stored.evidence_ref)
            {
                record.attach_evidence_digest(ProtocolEnvelopeDigest::new(
                    stored.evidence_ref.clone(),
                    Utc::now(),
                ));
            }
        }
        if let Some(intent_ref) = refs.intent_ref {
            record.protocol_refs.ap2_intent_mandate_id = Some(intent_ref);
        }
        if let Some(cart_ref) = refs.cart_ref {
            record.protocol_refs.ap2_cart_mandate_id = Some(cart_ref);
        }
        if let Some(payment_ref) = refs.payment_ref {
            ProtocolCorrelator::attach_protocol_ref(
                &mut record,
                ProtocolRefKind::Ap2PaymentMandateId,
                payment_ref,
            )
            .map_err(AdkError::from)?;
        }
        if let Some(executed) = refs.executed_payment_ref {
            let marker = ProtocolReference {
                protocol: ap2_descriptor(),
                reference_kind: EXECUTED_PAYMENT_MANDATE_REF_KIND.to_string(),
                reference_value: executed,
            };
            if !record.protocol_refs.additional.contains(&marker) {
                record.protocol_refs.additional.push(marker);
            }
        }
        if let Some(receipt_ref) = refs.receipt_ref {
            record.protocol_refs.ap2_payment_receipt_id = Some(receipt_ref);
        }
        record.recompute_safe_summary();
        self.transaction_store.upsert(record.clone()).await?;
        Ok(record)
    }

    fn merge_existing(&self, record: &mut TransactionRecord, existing: TransactionRecord) {
        if record.fulfillment.is_none() {
            record.fulfillment = existing.fulfillment;
        }
        if record.order.is_none() {
            record.order = existing.order;
        }
        if record.payment_processor.is_none() {
            record.payment_processor = existing.payment_processor;
        }
        if record.protocol_refs.ap2_intent_mandate_id.is_none() {
            record.protocol_refs.ap2_intent_mandate_id =
                existing.protocol_refs.ap2_intent_mandate_id;
        }
        if record.protocol_refs.ap2_cart_mandate_id.is_none() {
            record.protocol_refs.ap2_cart_mandate_id = existing.protocol_refs.ap2_cart_mandate_id;
        }
        if record.protocol_refs.ap2_payment_mandate_id.is_none() {
            record.protocol_refs.ap2_payment_mandate_id =
                existing.protocol_refs.ap2_payment_mandate_id;
        }
        if record.protocol_refs.ap2_payment_receipt_id.is_none() {
            record.protocol_refs.ap2_payment_receipt_id =
                existing.protocol_refs.ap2_payment_receipt_id;
        }
        for reference in existing.protocol_refs.additional {
            if !record.protocol_refs.additional.contains(&reference) {
                record.protocol_refs.additional.push(reference);
            }
        }
        for envelope in existing.extensions.0 {
            if !record.extensions.as_slice().contains(&envelope) {
                record.attach_extension(envelope);
            }
        }
        for evidence_ref in existing.evidence_refs {
            if !record.evidence_refs.contains(&evidence_ref) {
                record.attach_evidence_ref(evidence_ref);
            }
        }
        for digest in existing.evidence_digests {
            if !record.evidence_digests.contains(&digest) {
                record.attach_evidence_digest(digest);
            }
        }
    }
}