adk-core 3.0.0

Core traits and types for Rust Agent Development Kit (ADK-Rust) agents, tools, sessions, and events
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
//! Conformance cases for [`ApprovalStore`] backends.
//!
//! | Case | Contract |
//! |------|----------|
//! | [`pending_requests_are_kept_once_oldest_first`] | A fingerprint is pending once, keeps its first request, and pending calls list oldest first within their scope |
//! | [`decision_is_consumed_once`] | `decide` clears the pending entry; `has_decision` does not consume; `take_decision` returns the decision once |
//! | [`later_decision_replaces_earlier`] | Deciding the same fingerprint again replaces the earlier decision |
//! | [`expired_decisions_are_discarded`] | A decision past its expiry is taken as `None` |
//! | [`decisions_stay_in_their_scope`] | A decision in one session never authorizes a call in another |
//! | [`decisions_stay_with_their_agent_and_tool`] | Calls with one tool name and arguments by different agents, or to tools with different origins, are pending and decided separately |
//! | [`concurrent_take_has_one_winner`] | Concurrent takes of one decision, across two handles, return it once |
//! | [`records_survive_a_restart`] | Pending requests and decisions read back unchanged after a restart |
//! | [`decisions_carry_edits_and_messages`] | `take_approval` returns a decision's edited arguments and message once; `take_decision` reports the bare decision |
//! | [`requests_are_created_once`] | `create_request` keeps the first request under an ID and returns it unchanged |
//! | [`concurrent_replace_has_one_winner`] | Of concurrent `replace_request` calls at one version, across two handles, exactly one succeeds |
//! | [`requests_list_in_order_with_filters`] | `list_requests` filters by state, openness, and application, orders by creation time then ID, and pages by cursor |
//! | [`requests_list_by_session`] | `list_requests` filtered by session (application, user and session ID) returns that session's requests alone, in order and by page, however many requests of other sessions list first (spec 3.3 §10 C1) |
//! | [`delegations_round_trip`] | Delegations are stored, replaced by ID, listed per delegate by ID, and deleted once |
//! | [`approval_requests_survive_a_restart`] | Requests and delegations read back unchanged after a restart |
//! | [`evidence_round_trips`] | A held call's evidence and a request's evidence read back unchanged after a restart; a decision binds to the evidence digest |
//!
//! Every request carries an [`ActingContext`] and a [`ToolOrigin`], and the cases compare
//! whole requests, so each backend proves the acting agent and the tool's origin are
//! recorded with the held call. Every [`ApprovalRequest`] carries its call's origin too
//! (spec 3.3 §7.1), so the request cases prove each backend keeps it.
//!
//! `has_decision` may report `true` when no live decision exists (the trait's default
//! does), so the suite checks only that it never misses a live decision and never
//! consumes one.

use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use chrono::Utc;
use serde_json::json;

use super::{base_time, unique, unique_unicode};
use crate::principal::SubjectRef;
use crate::{
    ActingContext, AgentId, AgentPrincipal, ApprovalCursor, ApprovalDecision, ApprovalDelegation,
    ApprovalPolicy, ApprovalRequest, ApprovalRequestQuery, ApprovalScope, ApprovalState,
    ApprovalStore, ApproverSelector, ArtifactLocator, DelegationScope, DelegationWindow, Evidence,
    ImageEvidence, PendingApproval, ToolApproval, ToolConfirmationDecision,
    ToolConfirmationRequest, ToolOrigin,
};

/// Opens an [`ApprovalStore`] backend for the conformance suite.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use adk_core::conformance::ApprovalStoreHarness;
/// use adk_core::{ApprovalStore, InMemoryApprovalStore, async_trait};
///
/// struct InMemory(Arc<InMemoryApprovalStore>);
///
/// #[async_trait]
/// impl ApprovalStoreHarness for InMemory {
///     async fn open(&self) -> Arc<dyn ApprovalStore> {
///         self.0.clone()
///     }
/// }
/// ```
#[async_trait]
pub trait ApprovalStoreHarness: Send + Sync {
    /// Opens the store.
    ///
    /// For a durable backend every call returns a new handle over the same stored data,
    /// as a restarted process or a second process would see it. A process-local backend
    /// returns the same store every time. Panics when the backend cannot be opened.
    async fn open(&self) -> Arc<dyn ApprovalStore>;
}

fn scope() -> ApprovalScope {
    ApprovalScope::new(unique("app"), unique("user"), unique("session"))
}

fn request(amount: u64, call_id: &str) -> ToolConfirmationRequest {
    ToolConfirmationRequest {
        tool_name: "conformance_transfer".into(),
        function_call_id: Some(call_id.into()),
        args: json!({ "amount": amount, "to": "acct:1/main" }),
        // Every case compares whole requests, so each backend proves the acting context
        // and the tool origin round-trip with the call.
        origin: Some(ToolOrigin::new(
            "mcp:conformance",
            &json!({ "name": "conformance_transfer", "parameters": { "type": "object" } }),
            Some(&json!({ "destructiveHint": true })),
        )),
        acting: Some(Box::new(
            ActingContext::new(
                AgentPrincipal::new(
                    AgentId::new("spiffe://conformance.test/agent/treasurer").unwrap(),
                )
                .with_tenant("conformance")
                .with_instance("replica-1"),
            )
            .on_behalf_of(SubjectRef::human("alice")),
        )),
        evidence: Vec::new(),
    }
}

async fn pending(store: &dyn ApprovalStore, scope: &ApprovalScope) -> Vec<PendingApproval> {
    store.pending(scope).await.expect("pending reads the store")
}

async fn take(
    store: &dyn ApprovalStore,
    scope: &ApprovalScope,
    fingerprint: &str,
) -> Option<ToolConfirmationDecision> {
    store.take_decision(scope, fingerprint).await.expect("take_decision reads the store")
}

async fn has(store: &dyn ApprovalStore, scope: &ApprovalScope, fingerprint: &str) -> bool {
    store.has_decision(scope, fingerprint).await.expect("has_decision reads the store")
}

/// Recording a fingerprint twice keeps one entry with the first request and time, and
/// pending calls list oldest first, only within their own scope.
pub async fn pending_requests_are_kept_once_oldest_first<H: ApprovalStoreHarness + ?Sized>(
    harness: &H,
) {
    let store = harness.open().await;
    let scope = scope();
    let older = request(10, "call-1");
    let newer = request(20, "call-2");

    store.record_pending(&scope, &older).await.expect("record");
    tokio::time::sleep(Duration::from_millis(20)).await;
    store.record_pending(&scope, &newer).await.expect("record");
    tokio::time::sleep(Duration::from_millis(20)).await;
    store.record_pending(&scope, &request(10, "call-3")).await.expect("re-record");

    let listed = pending(&*store, &scope).await;
    let summary: Vec<_> = listed.iter().map(|entry| (&entry.fingerprint, &entry.request)).collect();
    assert_eq!(
        summary,
        [(&older.fingerprint(), &older), (&newer.fingerprint(), &newer)],
        "one entry per fingerprint, keeping its first request, oldest first"
    );
    assert!(listed[0].requested_at < listed[1].requested_at, "{listed:?}");

    for other in [
        ApprovalScope::new(&scope.app_name, &scope.user_id, unique("session")),
        ApprovalScope::new(&scope.app_name, unique("user"), &scope.session_id),
        ApprovalScope::new(unique("app"), &scope.user_id, &scope.session_id),
    ] {
        assert_eq!(pending(&*store, &other).await, [], "nothing leaks into {other:?}");
    }
}

/// `decide` clears the pending entry, `has_decision` reports the decision without
/// consuming it, and `take_decision` returns it exactly once.
pub async fn decision_is_consumed_once<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let store = harness.open().await;
    let scope = scope();
    let decided = request(10, "call-1");
    let waiting = request(20, "call-2");
    store.record_pending(&scope, &decided).await.expect("record");
    store.record_pending(&scope, &waiting).await.expect("record");

    store.decide(&scope, &decided.fingerprint(), ToolApproval::approve()).await.expect("decide");
    let listed = pending(&*store, &scope).await;
    assert_eq!(
        listed.iter().map(|entry| &entry.fingerprint).collect::<Vec<_>>(),
        [&waiting.fingerprint()],
        "deciding clears the pending entry"
    );

    assert!(has(&*store, &scope, &decided.fingerprint()).await, "a live decision is reported");
    assert!(has(&*store, &scope, &decided.fingerprint()).await, "has_decision does not consume");
    assert!(!has(&*store, &scope, &waiting.fingerprint()).await, "a pending call has no decision");

    assert_eq!(
        take(&*store, &scope, &decided.fingerprint()).await,
        Some(ToolConfirmationDecision::Approve)
    );
    assert_eq!(take(&*store, &scope, &decided.fingerprint()).await, None, "taken once");
    assert_eq!(take(&*store, &scope, &waiting.fingerprint()).await, None, "never decided");
}

/// Deciding a fingerprint again replaces the earlier decision.
pub async fn later_decision_replaces_earlier<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let store = harness.open().await;
    let scope = scope();
    let fingerprint = request(10, "call-1").fingerprint();

    store.decide(&scope, &fingerprint, ToolApproval::approve()).await.expect("approve");
    store.decide(&scope, &fingerprint, ToolApproval::deny()).await.expect("then deny");
    assert_eq!(take(&*store, &scope, &fingerprint).await, Some(ToolConfirmationDecision::Deny));
    assert_eq!(take(&*store, &scope, &fingerprint).await, None);
}

/// A decision past its expiry is discarded and taken as `None`; one that has not
/// expired is taken normally.
pub async fn expired_decisions_are_discarded<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let store = harness.open().await;
    let scope = scope();
    let fingerprint = request(10, "call-1").fingerprint();

    let expired = ToolApproval::approve().expires_at(Utc::now() - chrono::Duration::seconds(1));
    store.decide(&scope, &fingerprint, expired).await.expect("decide");
    assert_eq!(take(&*store, &scope, &fingerprint).await, None, "an expired decision");

    let live = ToolApproval::deny().expires_in(Duration::from_secs(3_600));
    store.decide(&scope, &fingerprint, live).await.expect("decide");
    assert!(has(&*store, &scope, &fingerprint).await, "a live decision is reported");
    assert_eq!(take(&*store, &scope, &fingerprint).await, Some(ToolConfirmationDecision::Deny));
}

/// A decision recorded for one session is never taken by another session, user, or
/// application.
pub async fn decisions_stay_in_their_scope<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let store = harness.open().await;
    let scope = scope();
    let fingerprint = request(10, "call-1").fingerprint();
    store.decide(&scope, &fingerprint, ToolApproval::approve()).await.expect("decide");

    for other in [
        ApprovalScope::new(&scope.app_name, &scope.user_id, unique("session")),
        ApprovalScope::new(&scope.app_name, unique("user"), &scope.session_id),
        ApprovalScope::new(unique("app"), &scope.user_id, &scope.session_id),
    ] {
        assert_eq!(take(&*store, &other, &fingerprint).await, None, "{other:?}");
    }
    assert_eq!(
        take(&*store, &scope, &fingerprint).await,
        Some(ToolConfirmationDecision::Approve),
        "the decision is still there for its own scope"
    );
}

/// Two calls with the same tool name and arguments, made by different agents or to tools
/// with different origins, are pending separately, and a decision for one is never taken
/// for another.
pub async fn decisions_stay_with_their_agent_and_tool<H: ApprovalStoreHarness + ?Sized>(
    harness: &H,
) {
    let store = harness.open().await;
    let scope = scope();
    let owner = request(10, "call-1");
    let mut other_agent = request(10, "call-2");
    other_agent.acting = Some(Box::new(ActingContext::new(AgentPrincipal::new(
        AgentId::new("spiffe://conformance.test/agent/intern").unwrap(),
    ))));
    let mut other_server = request(10, "call-3");
    other_server.origin = Some(ToolOrigin::new(
        "mcp:conformance_mirror",
        &json!({ "name": "conformance_transfer", "parameters": { "type": "object" } }),
        Some(&json!({ "destructiveHint": true })),
    ));
    let mut redefined = request(10, "call-4");
    redefined.origin = Some(ToolOrigin::new(
        "mcp:conformance",
        &json!({ "name": "conformance_transfer", "parameters": { "type": "object", "required": ["memo"] } }),
        Some(&json!({ "destructiveHint": true })),
    ));
    let calls = [&owner, &other_agent, &other_server, &redefined];
    for call in calls {
        store.record_pending(&scope, call).await.expect("record");
    }
    let mut listed: Vec<String> =
        pending(&*store, &scope).await.into_iter().map(|entry| entry.fingerprint).collect();
    listed.sort();
    let mut expected: Vec<String> = calls.iter().map(|call| call.fingerprint()).collect();
    expected.sort();
    expected.dedup();
    assert_eq!(expected.len(), 4, "each agent and tool origin has its own fingerprint");
    assert_eq!(listed, expected, "each call is pending on its own");

    store.decide(&scope, &owner.fingerprint(), ToolApproval::approve()).await.expect("decide");
    for call in [&other_agent, &other_server, &redefined] {
        assert_eq!(
            take(&*store, &scope, &call.fingerprint()).await,
            None,
            "the owner's decision does not authorize {:?}",
            call.function_call_id
        );
    }
    assert_eq!(
        take(&*store, &scope, &owner.fingerprint()).await,
        Some(ToolConfirmationDecision::Approve),
        "the owner's call takes its decision"
    );
}

/// Concurrent takes of one decision, split across two handles, return it to exactly one
/// caller, so one approval authorizes one execution.
pub async fn concurrent_take_has_one_winner<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let first = harness.open().await;
    let second = harness.open().await;
    let scope = scope();
    let fingerprint = request(10, "call-1").fingerprint();
    first.decide(&scope, &fingerprint, ToolApproval::approve()).await.expect("decide");

    let tasks: Vec<_> = (0..16)
        .map(|i| {
            let store = if i % 2 == 0 { first.clone() } else { second.clone() };
            let scope = scope.clone();
            let fingerprint = fingerprint.clone();
            tokio::spawn(async move { store.take_decision(&scope, &fingerprint).await })
        })
        .collect();
    let mut taken = Vec::new();
    for task in tasks {
        if let Some(decision) = task.await.expect("take task completes").expect("take succeeds") {
            taken.push(decision);
        }
    }
    assert_eq!(taken, [ToolConfirmationDecision::Approve], "exactly one take wins");
}

/// Pending requests and decisions read back unchanged through a new handle.
pub async fn records_survive_a_restart<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let scope = scope();
    let waiting = request(10, "call-1");
    let decided = request(20, "call-2");
    let before = {
        let store = harness.open().await;
        store.record_pending(&scope, &waiting).await.expect("record");
        store.record_pending(&scope, &decided).await.expect("record");
        let approval = ToolApproval::approve().expires_in(Duration::from_secs(3_600));
        store.decide(&scope, &decided.fingerprint(), approval).await.expect("decide");
        pending(&*store, &scope).await
    };
    assert_eq!(before.len(), 1, "{before:?}");

    let store = harness.open().await;
    assert_eq!(pending(&*store, &scope).await, before, "pending requests survive");
    assert!(has(&*store, &scope, &decided.fingerprint()).await, "the decision survives");
    assert_eq!(
        take(&*store, &scope, &decided.fingerprint()).await,
        Some(ToolConfirmationDecision::Approve)
    );
}

/// `take_approval` returns the edited arguments and message a decision carries, once;
/// `take_decision` reports a decision without them.
pub async fn decisions_carry_edits_and_messages<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let store = harness.open().await;
    let scope = scope();
    let edited = request(10, "call-1").fingerprint();
    let refused = request(20, "call-2").fingerprint();
    let bare = request(30, "call-3").fingerprint();

    let edit = ToolApproval::approve()
        .with_edited_args(json!({ "amount": 5, "to": "acct:1/main", "memo": "ü-日本" }));
    let denial = ToolApproval::deny().with_message("the approver rejected it: over budget");
    store.decide(&scope, &edited, edit.clone()).await.expect("decide");
    store.decide(&scope, &refused, denial.clone()).await.expect("decide");
    store.decide(&scope, &bare, ToolApproval::approve()).await.expect("decide");

    assert!(has(&*store, &scope, &edited).await, "an edited approval is a live decision");
    let take_full = |fingerprint: String| {
        let store = store.clone();
        let scope = scope.clone();
        async move { store.take_approval(&scope, &fingerprint).await.expect("take_approval") }
    };
    assert_eq!(take_full(edited.clone()).await, Some(edit), "edited arguments round-trip");
    assert_eq!(take_full(edited).await, None, "taken once");
    assert_eq!(take_full(refused).await, Some(denial), "the message round-trips");
    assert_eq!(
        take(&*store, &scope, &bare).await,
        Some(ToolConfirmationDecision::Approve),
        "take_decision reports the bare decision"
    );
}

fn approval_request(app: &str, id: &str, offset_secs: i64) -> ApprovalRequest {
    let mut request = ApprovalRequest::new(
        id,
        ApprovalScope::new(app, unique("user"), unique("session")),
        &request(u64::try_from(offset_secs).unwrap_or(0), "call-1"),
        ApprovalPolicy::new([ApproverSelector::group("conformance:approvers")]).with_quorum(2),
    )
    .with_summary("Transfer to ü-日本")
    .with_requester(SubjectRef::human(unique("requester")));
    request.created_at = base_time() + chrono::Duration::seconds(offset_secs);
    request
}

async fn stored(store: &dyn ApprovalStore, id: &str) -> Option<ApprovalRequest> {
    store.get_request(id).await.expect("get_request reads the store")
}

/// `create_request` stores a request once: creating the same ID again returns the first
/// request unchanged, and `get_request` reads it back exactly.
pub async fn requests_are_created_once<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let store = harness.open().await;
    let app = unique("app");
    let first = approval_request(&app, &unique_unicode("request"), 0);
    assert_eq!(first.origin, request(0, "call-1").origin, "the request names its tool's origin");
    assert_eq!(store.create_request(&first).await.expect("create"), first, "created");
    assert_eq!(stored(&*store, &first.id).await, Some(first.clone()), "reads back exactly");

    let mut second = approval_request(&app, &first.id, 30);
    second.summary = "a different request under the same id".into();
    assert_eq!(
        store.create_request(&second).await.expect("create again"),
        first,
        "creating an existing id returns the stored request"
    );
    assert_eq!(stored(&*store, &first.id).await, Some(first), "the first request is kept");
    assert_eq!(stored(&*store, &unique("missing")).await, None, "an unknown id reads as None");
}

/// Concurrent `replace_request` calls at the same expected version, split across two
/// handles, have exactly one winner, whose write is the one stored.
pub async fn concurrent_replace_has_one_winner<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let first = harness.open().await;
    let second = harness.open().await;
    let original = approval_request(&unique("app"), &unique_unicode("request"), 0);
    first.create_request(&original).await.expect("create");

    let tasks: Vec<_> = (0..16)
        .map(|i| {
            let store = if i % 2 == 0 { first.clone() } else { second.clone() };
            let mut next = original.clone();
            next.version = 2;
            next.decisions
                .push(ApprovalDecision::approve(SubjectRef::human(format!("approver-{i}"))));
            tokio::spawn(async move {
                let won = store.replace_request(&next, 1).await.expect("replace succeeds");
                won.then_some(next)
            })
        })
        .collect();
    let mut winners = Vec::new();
    for task in tasks {
        if let Some(next) = task.await.expect("replace task completes") {
            winners.push(next);
        }
    }
    assert_eq!(winners.len(), 1, "exactly one replace wins");
    assert_eq!(
        stored(&*second, &original.id).await,
        Some(winners.remove(0)),
        "the winner is stored"
    );

    let mut stale = original.clone();
    stale.version = 2;
    assert!(
        !first.replace_request(&stale, 1).await.expect("replace"),
        "a replace at a superseded version is refused"
    );
    let mut missing = original.clone();
    missing.id = unique("missing");
    assert!(!first.replace_request(&missing, 1).await.expect("replace"), "a missing request");
}

/// `list_requests` filters by state, openness, and application, orders by creation time
/// and then ID, and pages from a cursor.
pub async fn requests_list_in_order_with_filters<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let store = harness.open().await;
    let app = unique_unicode("app");
    let prefix = unique("request");
    let id = |suffix: &str| format!("{prefix}:{suffix}");
    // Two requests share a creation time, so the ID breaks the tie.
    let mut pending_late = approval_request(&app, &id("b"), 20);
    let pending_tied = approval_request(&app, &id("a"), 20);
    let pending_early = approval_request(&app, &id("z"), 10);
    let mut approved_unapplied = approval_request(&app, &id("c"), 30);
    approved_unapplied.state = ApprovalState::Approved;
    let mut rejected_applied = approval_request(&app, &id("d"), 40);
    rejected_applied.state = ApprovalState::Rejected;
    rejected_applied.outcome_applied = true;
    pending_late.summary = "late".into();
    let other_app = approval_request(&unique("app"), &unique("other"), 15);
    for request in [
        &pending_late,
        &pending_tied,
        &pending_early,
        &approved_unapplied,
        &rejected_applied,
        &other_app,
    ] {
        store.create_request(request).await.expect("create");
    }
    let ids = |requests: Vec<ApprovalRequest>| -> Vec<String> {
        requests.into_iter().map(|request| request.id).collect()
    };
    let list = |query: ApprovalRequestQuery| {
        let store = store.clone();
        async move { store.list_requests(&query).await.expect("list_requests reads the store") }
    };
    let in_app = ApprovalRequestQuery::default().with_app_name(app.clone());

    assert_eq!(
        ids(list(in_app.clone()).await),
        [id("z"), id("a"), id("b"), id("c"), id("d")],
        "every request of the application, by creation time and then id"
    );
    assert_eq!(
        ids(list(in_app.clone().with_states([ApprovalState::Pending])).await),
        [id("z"), id("a"), id("b")],
        "pending only"
    );
    assert_eq!(
        ids(list(in_app.clone().with_states([ApprovalState::Approved, ApprovalState::Rejected]))
            .await),
        [id("c"), id("d")],
        "either of two states"
    );
    assert_eq!(
        ids(list(in_app.clone().open_only()).await),
        [id("z"), id("a"), id("b"), id("c")],
        "open requests: pending, or resolved and not yet applied"
    );
    let first_page = list(in_app.clone().with_limit(2)).await;
    assert_eq!(ids(first_page.clone()), [id("z"), id("a")], "a page of two");
    let cursor = first_page.last().map(ApprovalRequest::cursor);
    assert_eq!(
        ids(list(in_app.clone().with_after(cursor).with_limit(2)).await),
        [id("b"), id("c")],
        "the next page starts after the cursor, inside a tie on creation time"
    );
    let decoded = ApprovalCursor::decode(&pending_late.cursor().encode()).expect("decode");
    assert_eq!(
        ids(list(in_app.with_after(Some(decoded))).await),
        [id("c"), id("d")],
        "an encoded cursor pages the same way"
    );
    assert_eq!(
        list(ApprovalRequestQuery::default().with_app_name(app.clone()).with_limit(1)).await[0],
        pending_early,
        "listed requests read back exactly"
    );
}

/// `list_requests` filtered by session returns that session's requests alone, ordered by
/// creation time and then ID and paged by cursor, however many requests of other sessions
/// list before them. A session is an application's, user's and session ID together
/// (`with_session`); a session ID alone matches it for every user and application
/// (spec 3.3 §10 C1).
pub async fn requests_list_by_session<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let store = harness.open().await;
    let scope = ApprovalScope::new(
        unique_unicode("app"),
        unique_unicode("user"),
        unique_unicode("session"),
    );
    let prefix = unique("request");
    let id = |n: u32| format!("{prefix}:{n:02}");
    let in_scope = |scope: &ApprovalScope, n: u32, offset_secs: i64| {
        let mut request = approval_request(&scope.app_name, &id(n), offset_secs);
        request.scope = scope.clone();
        request
    };
    // More requests of other sessions than a page of two list before this session's first.
    let mut others: Vec<ApprovalRequest> =
        (0..5).map(|n| approval_request(&scope.app_name, &id(n), i64::from(n))).collect();
    let first = in_scope(&scope, 10, 10);
    others.push(approval_request(&scope.app_name, &id(11), 11));
    // Another user's session, and another application's, with the same session ID.
    let other_user = ApprovalScope::new(
        scope.app_name.clone(),
        unique_unicode("user"),
        scope.session_id.clone(),
    );
    let other_app =
        ApprovalScope::new(unique_unicode("app"), scope.user_id.clone(), scope.session_id.clone());
    let same_id_other_user = in_scope(&other_user, 12, 12);
    let elsewhere = in_scope(&other_app, 15, 15);
    // Two of the session's requests share a creation time, so the ID breaks the tie.
    let mut tied_late = in_scope(&scope, 21, 20);
    let tied_early = in_scope(&scope, 20, 20);
    for request in
        others.iter().chain([&first, &tied_late, &tied_early, &elsewhere, &same_id_other_user])
    {
        store.create_request(request).await.expect("create");
    }
    let ids = |requests: Vec<ApprovalRequest>| -> Vec<String> {
        requests.into_iter().map(|request| request.id).collect()
    };
    let list = |query: ApprovalRequestQuery| {
        let store = store.clone();
        async move { store.list_requests(&query).await.expect("list_requests reads the store") }
    };
    let one_session = ApprovalRequestQuery::default().with_session(&scope);

    assert_eq!(
        ids(list(one_session.clone()).await),
        [id(10), id(20), id(21)],
        "the session's requests alone, by creation time and then id"
    );
    assert_eq!(
        list(one_session.clone().with_limit(1)).await,
        [first],
        "a page of one is the session's first request, read back exactly"
    );
    let page = list(one_session.clone().with_limit(2)).await;
    assert_eq!(ids(page.clone()), [id(10), id(20)], "a page of two");
    let cursor = page.last().map(ApprovalRequest::cursor);
    assert_eq!(
        ids(list(one_session.clone().with_after(cursor)).await),
        [id(21)],
        "the next page starts after the cursor, inside a tie on creation time"
    );
    assert_eq!(
        ids(list(
            ApprovalRequestQuery::default()
                .with_app_name(scope.app_name.clone())
                .with_session_id(scope.session_id.clone())
        )
        .await),
        [id(10), id(12), id(20), id(21)],
        "without a user, the session ID of every user in the application"
    );
    assert_eq!(
        ids(list(
            ApprovalRequestQuery::default()
                .with_user_id(scope.user_id.clone())
                .with_session_id(scope.session_id.clone())
        )
        .await),
        [id(10), id(15), id(20), id(21)],
        "without an application, the user's session ID in every application"
    );
    assert_eq!(
        ids(list(ApprovalRequestQuery::default().with_session(&other_user)).await),
        [id(12)],
        "another user's session with the same ID"
    );

    let mut decided = tied_late.clone();
    decided.version = 2;
    decided.state = ApprovalState::Approved;
    assert!(store.replace_request(&decided, 1).await.expect("replace"), "replaced");
    tied_late = decided;
    assert_eq!(
        ids(list(one_session.clone().with_states([ApprovalState::Pending])).await),
        [id(10), id(20)],
        "with a state"
    );
    assert_eq!(
        list(one_session.with_states([ApprovalState::Approved])).await,
        [tied_late],
        "a replaced request stays in its session"
    );
    let mut empty = scope.clone();
    empty.session_id = unique_unicode("session");
    assert_eq!(
        list(ApprovalRequestQuery::default().with_session(&empty)).await,
        [],
        "a session with no requests"
    );
}

/// Delegations are stored, replaced by ID, listed for their delegate ordered by ID, and
/// deleted once.
pub async fn delegations_round_trip<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let store = harness.open().await;
    let delegate = SubjectRef::human(unique_unicode("delegate"));
    let window = DelegationWindow::new(base_time(), base_time() + chrono::Duration::days(7));
    let delegation = |id: &str, from: &str, to: &SubjectRef| {
        let mut delegation = ApprovalDelegation::new(SubjectRef::human(from), to.clone(), window)
            .with_from_groups(["conformance:finance"]);
        delegation.id = id.to_string();
        delegation.created_at = base_time();
        delegation
    };
    let second = delegation(&format!("{}/b", unique("delegation")), "ana", &delegate);
    let first = delegation(&format!("{}/a", second.id.trim_end_matches("/b")), "bo", &delegate);
    let elsewhere = delegation(&unique("delegation"), "cy", &SubjectRef::human(unique("other")));
    for delegation in [&second, &first, &elsewhere] {
        store.put_delegation(delegation).await.expect("put_delegation");
    }
    let listed = store.delegations_to(&delegate).await.expect("delegations_to");
    assert_eq!(listed, [first.clone(), second.clone()], "the delegate's delegations, by id");

    let mut narrowed = second.clone();
    narrowed.scope = DelegationScope { app_name: Some("payments".into()), tool_names: vec![] };
    store.put_delegation(&narrowed).await.expect("replace");
    assert_eq!(
        store.delegations_to(&delegate).await.expect("delegations_to"),
        [first.clone(), narrowed.clone()],
        "putting an existing id replaces it"
    );

    assert!(store.delete_delegation(&first.id).await.expect("delete"), "deleted");
    assert!(!store.delete_delegation(&first.id).await.expect("delete"), "deleted once");
    assert_eq!(store.delegations_to(&delegate).await.expect("delegations_to"), [narrowed]);
    assert_eq!(
        store
            .delegations_to(&SubjectRef::service(delegate.id.clone()))
            .await
            .expect("delegations_to"),
        [],
        "a subject of another kind with the same id has none"
    );
}

/// Requests and delegations read back unchanged through a new handle.
pub async fn approval_requests_survive_a_restart<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let app = unique("app");
    let mut request = approval_request(&app, &unique_unicode("request"), 0);
    let delegate = SubjectRef::human(unique("delegate"));
    let mut delegation = ApprovalDelegation::new(
        SubjectRef::human("ana"),
        delegate.clone(),
        DelegationWindow::new(base_time(), base_time() + chrono::Duration::hours(1)),
    );
    delegation.created_at = base_time();
    {
        let store = harness.open().await;
        store.create_request(&request).await.expect("create");
        let mut next = request.clone();
        next.version = 2;
        next.decisions.push(ApprovalDecision::approve(SubjectRef::human("ana")));
        assert!(store.replace_request(&next, 1).await.expect("replace"));
        request = next;
        store.put_delegation(&delegation).await.expect("put_delegation");
    }
    let store = harness.open().await;
    assert_eq!(stored(&*store, &request.id).await, Some(request.clone()), "the request survives");
    assert_eq!(
        store
            .list_requests(&ApprovalRequestQuery::default().with_app_name(app).open_only())
            .await
            .expect("list"),
        [request],
        "and lists"
    );
    assert_eq!(store.delegations_to(&delegate).await.expect("list"), [delegation]);
}

/// An image held as evidence, with regions and a caption, so a backend proves it keeps every
/// field.
fn image_evidence(scope: &ApprovalScope, digest: &str) -> Evidence {
    ImageEvidence::new(
        digest,
        ArtifactLocator::new(
            &scope.app_name,
            &scope.user_id,
            &scope.session_id,
            unique_unicode("egress/crop"),
            3,
        ),
        "image/png",
        640,
        180,
    )
    .with_regions(json!({
        "image": digest,
        "width": 640,
        "height": 180,
        "regions": [{ "label": "total", "shape": { "box": { "x0": 12.5, "y0": 8.5, "x1": 300.25, "y1": 60.75 } } }]
    }))
    .with_caption("Invoice total — ü-日本, after redaction")
    .into()
}

/// A held call's evidence and an approval request's evidence read back unchanged, also after
/// a restart, and a decision recorded for one image's call never authorizes the same call
/// with another image.
pub async fn evidence_round_trips<H: ApprovalStoreHarness + ?Sized>(harness: &H) {
    let scope = scope();
    let digest = "sha256:9f2c0a7e5b1d4c8a6f3e2d1c0b9a8f7e6d5c4b3a2f1e0d9c8b7a6f5e4d3c2b1a";
    let swapped_digest = "sha256:0e5751c026e543b2e8ab2eb06099daa1d1e5df47778f7787faab45cdf12fe3a8";
    let held = request(10, "call-1").with_evidence([image_evidence(&scope, digest)]);
    let swapped = request(10, "call-2").with_evidence([image_evidence(&scope, swapped_digest)]);
    assert_ne!(held.fingerprint(), swapped.fingerprint(), "the digest is part of the fingerprint");

    let mut approval = ApprovalRequest::new(
        unique_unicode("request"),
        scope.clone(),
        &held,
        ApprovalPolicy::new([ApproverSelector::human("ana")]),
    )
    .with_evidence([image_evidence(&scope, swapped_digest)]);
    approval.created_at = base_time();
    {
        let store = harness.open().await;
        store.record_pending(&scope, &held).await.expect("record");
        let listed = pending(&*store, &scope).await;
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].request, held, "the held call keeps its evidence");
        assert_eq!(listed[0].fingerprint, held.fingerprint());
        assert_eq!(store.create_request(&approval).await.expect("create"), approval);
        store.decide(&scope, &held.fingerprint(), ToolApproval::approve()).await.expect("decide");
    }

    let store = harness.open().await;
    assert_eq!(stored(&*store, &approval.id).await, Some(approval.clone()), "evidence survives");
    assert_eq!(approval.evidence.len(), 2);
    assert_eq!(
        take(&*store, &scope, &swapped.fingerprint()).await,
        None,
        "the decision does not authorize the call with another image"
    );
    assert_eq!(
        take(&*store, &scope, &held.fingerprint()).await,
        Some(ToolConfirmationDecision::Approve),
        "the call with the approved image takes its decision"
    );
}