Skip to main content

adk_kernel/conformance/
channel_contract.rs

1//! The contract every chat channel adapter passes (spec 3.3 §5.3, §7.2, §10 K1, §11 S-I2,
2//! S-I5, S-I6, S-I10; feature `channels`).
3//!
4//! Each case runs the adapter under a [`ChannelGateway`] over a [`ContractHost`], an
5//! in-memory kernel double, and checks what the adapter put on the wire and what it made of
6//! the person's input:
7//!
8//! | Case | Contract |
9//! |------|----------|
10//! | [`an_unpaired_account_gets_a_code_and_starts_nothing`] | An unpaired account's message gets a pairing code in its thread and starts no turn (S-I6) |
11//! | [`a_paired_message_starts_a_turn_and_the_reply_returns_to_its_thread`] | After its code is accepted the account's message starts a turn as its person, authenticated, and the reply comes back to the same thread |
12//! | [`a_redelivered_message_starts_one_turn`] | The same platform message delivered twice starts one turn (K-I3) |
13//! | [`decision_cards_carry_no_arguments`] | A card reaches the person's thread with its agent, summary and risk; no argument value ever leaves the machine (S-I5) |
14//! | [`allow_once_decides_once_and_a_second_answer_is_already_decided`] | "Allow once" approves at the card's version; a second press is answered "decided already" and decides nothing (S-I2) |
15//! | [`deny_rejects`] | "Deny" rejects |
16//! | [`high_risk_offers_no_answer_and_a_forged_one_is_refused`] | A high-risk card offers no button, and an answer forged for it decides nothing (§7.2) |
17//! | [`stop_all_stops_and_resume_is_refused`] | "stop all" stops everything; "resume" is refused and everything stays stopped (S-I10) |
18//! | [`a_stopped_kernel_starts_no_turn`] | While everything is stopped a message starts nothing and says so |
19//! | [`an_unpaired_account_cannot_answer`] | An answer from an unpaired account decides nothing and gets a pairing code |
20//! | [`a_restart_rings_what_still_waits`] | After a restart, every decision that still waits is rung again, and only those |
21//! | [`quiet_time_holds_cards`] | A card for a decision asked in quiet time arrives when quiet time ends |
22//!
23//! Generate the tests with [`channel_contract_tests!`](crate::channel_contract_tests) and a
24//! [`ChannelAdapterHarness`] that makes a fresh adapter per case.
25
26use std::collections::BTreeMap;
27use std::sync::{Arc, Mutex, PoisonError};
28use std::time::Duration;
29
30use adk_core::audit_log::{AuditActor, AuditTrail, InMemoryAuditRecorder};
31use adk_core::{
32    ActingContext, AgentPrincipal, ApprovalPolicy, ApprovalRequest, ApprovalRisk, ApprovalScope,
33    ApprovalService, ApprovalState, ApproverSelector, GovernanceControl, InMemoryApprovalStore,
34    NewRun, RunRecord, RunState, StoreApprovalService, ToolConfirmationRequest,
35};
36use async_trait::async_trait;
37use chrono::{DateTime, Utc};
38use futures::stream::{BoxStream, StreamExt};
39use serde_json::json;
40use tokio::sync::broadcast;
41
42use crate::channels::{
43    ChannelAnswer, ChannelBindingStore, ChannelGateway, ChannelHost, ChannelInbound, ChannelSink,
44    InMemoryChannel, InMemoryChannelBindingStore, InboundOutcome, accept_pairing,
45};
46use crate::error::{KernelError, Result};
47
48/// The person every paired account in the suite acts for.
49const PERSON: &str = "ana";
50/// The approval group decisions route to, as `adk-rust up` routes them.
51const GROUP: &str = "operator";
52
53/// A chat adapter as the suite drives it (spec 3.3 §10 K1): its [`ChannelSink`], what it
54/// put on the wire, and the [`ChannelInbound`] values it makes of the person's input.
55#[async_trait]
56pub trait ChannelAdapter: ChannelSink {
57    /// Everything the adapter put on the wire to `thread`, in order, as text: what left the
58    /// machine.
59    async fn wire(&self, thread: &str) -> Vec<String>;
60
61    /// What the adapter makes of `account` typing `text` in `thread`, as a new message.
62    async fn typed(&self, account: &str, thread: &str, text: &str) -> ChannelInbound;
63
64    /// What the adapter makes of `account` pressing `answer` on the last card it sent to
65    /// `thread`, or `None` when that card offers no such button.
66    async fn pressed(
67        &self,
68        account: &str,
69        thread: &str,
70        answer: ChannelAnswer,
71    ) -> Option<ChannelInbound>;
72
73    /// The pairing code the adapter delivered to `thread`, as the person reads it.
74    async fn pairing_code(&self, thread: &str) -> Option<String>;
75}
76
77/// Makes a fresh adapter for each case.
78///
79/// # Example
80///
81/// ```rust
82/// use std::sync::Arc;
83/// use adk_kernel::channels::InMemoryChannel;
84/// use adk_kernel::conformance::{ChannelAdapter, ChannelAdapterHarness};
85///
86/// struct InMemory;
87///
88/// #[async_trait::async_trait]
89/// impl ChannelAdapterHarness for InMemory {
90///     async fn adapter(&self) -> Arc<dyn ChannelAdapter> {
91///         Arc::new(InMemoryChannel::new("chat"))
92///     }
93/// }
94/// ```
95#[async_trait]
96pub trait ChannelAdapterHarness: Send + Sync {
97    /// A fresh adapter, with nothing sent.
98    async fn adapter(&self) -> Arc<dyn ChannelAdapter>;
99}
100
101#[async_trait]
102impl ChannelAdapter for InMemoryChannel {
103    async fn wire(&self, thread: &str) -> Vec<String> {
104        self.wire(thread).lines().map(str::to_string).collect()
105    }
106
107    async fn typed(&self, account: &str, thread: &str, text: &str) -> ChannelInbound {
108        self.text(account, thread, text)
109    }
110
111    async fn pressed(
112        &self,
113        account: &str,
114        thread: &str,
115        answer: ChannelAnswer,
116    ) -> Option<ChannelInbound> {
117        let card = self.last_card(thread)?;
118        self.press(account, thread, &card, answer)
119    }
120
121    async fn pairing_code(&self, thread: &str) -> Option<String> {
122        InMemoryChannel::pairing_code(self, thread)
123    }
124}
125
126/// A kernel double the suite runs the gateway on (spec 3.3 §10 K1): a real approval service
127/// and kill switch, turns kept in memory and finished on demand, and quiet time set by the
128/// test.
129pub struct ContractHost {
130    approvals: Arc<dyn ApprovalService>,
131    governance: GovernanceControl,
132    recorder: InMemoryAuditRecorder,
133    turns: Mutex<BTreeMap<String, NewRun>>,
134    finished: broadcast::Sender<RunRecord>,
135    quiet_until: Mutex<Option<DateTime<Utc>>>,
136}
137
138impl std::fmt::Debug for ContractHost {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        f.debug_struct("ContractHost").finish_non_exhaustive()
141    }
142}
143
144impl Default for ContractHost {
145    fn default() -> Self {
146        Self::new()
147    }
148}
149
150impl ContractHost {
151    /// A host with nothing started and nothing stopped.
152    pub fn new() -> Self {
153        Self {
154            approvals: Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))),
155            governance: GovernanceControl::new(),
156            recorder: InMemoryAuditRecorder::new(),
157            turns: Mutex::default(),
158            finished: broadcast::channel(64).0,
159            quiet_until: Mutex::default(),
160        }
161    }
162
163    /// The turns started so far: process id and run.
164    pub fn turns(&self) -> Vec<(String, NewRun)> {
165        let turns = self.turns.lock().unwrap_or_else(PoisonError::into_inner);
166        turns.iter().map(|(pid, run)| (pid.clone(), run.clone())).collect()
167    }
168
169    /// Finishes turn `pid` with the agent's reply `text`.
170    ///
171    /// # Panics
172    ///
173    /// When no turn has that id.
174    pub fn finish(&self, pid: &str, text: &str) {
175        let run = self.turns.lock().unwrap_or_else(PoisonError::into_inner)[pid].clone();
176        let mut record = RunRecord::queued(pid, run, Utc::now());
177        record.state = RunState::Completed;
178        record.result = Some(json!({ "text": text }));
179        let _ = self.finished.send(record);
180    }
181
182    /// Holds cards until `until`, or lifts quiet time with `None`.
183    pub fn set_quiet_until(&self, until: Option<DateTime<Utc>>) {
184        *self.quiet_until.lock().unwrap_or_else(PoisonError::into_inner) = until;
185    }
186
187    /// Whether everything is stopped.
188    pub fn is_stopped(&self) -> bool {
189        self.governance.is_frozen()
190    }
191
192    /// The `origin` of every `kernel.channel` record written so far.
193    pub fn channel_origins(&self) -> Vec<serde_json::Value> {
194        self.recorder
195            .records()
196            .into_iter()
197            .filter(|record| record.action == crate::audit::CHANNEL)
198            .filter_map(|record| record.ext.get("origin").cloned())
199            .collect()
200    }
201
202    /// The `kernel.channel` records written so far, as their actions.
203    pub fn channel_actions(&self) -> Vec<String> {
204        self.recorder
205            .records()
206            .into_iter()
207            .filter(|record| record.action == crate::audit::CHANNEL)
208            .filter_map(|record| {
209                record.ext.get("action").and_then(|v| v.as_str()).map(str::to_string)
210            })
211            .collect()
212    }
213
214    /// Submits a decision for `PERSON` calling `tool` with `args` at `risk`, as a held call
215    /// would, and returns it.
216    ///
217    /// # Panics
218    ///
219    /// When the approval service refuses it.
220    pub async fn ask(
221        &self,
222        summary: &str,
223        args: serde_json::Value,
224        risk: ApprovalRisk,
225    ) -> ApprovalRequest {
226        let call = ToolConfirmationRequest::new("send_email", args);
227        let id = format!("decision-{}", uuid::Uuid::new_v4().simple());
228        let request = ApprovalRequest::new(
229            id,
230            ApprovalScope::new("adk-rust", PERSON, "session-1"),
231            &call,
232            ApprovalPolicy::new([ApproverSelector::group(GROUP)]).allow_self_approval(),
233        )
234        .with_summary(summary)
235        .with_risk(risk)
236        .with_acting(ActingContext::new(AgentPrincipal::derived("adk-rust", "Finance")));
237        self.approvals.submit(request).await.expect("the approval service takes the decision")
238    }
239
240    /// The decision `id` now.
241    ///
242    /// # Panics
243    ///
244    /// When the approval service fails.
245    pub async fn decision(&self, id: &str) -> ApprovalRequest {
246        self.approvals.get(id).await.expect("read").expect("the decision exists")
247    }
248}
249
250#[async_trait]
251impl ChannelHost for ContractHost {
252    fn app_name(&self) -> &str {
253        "adk-rust"
254    }
255
256    fn now(&self) -> DateTime<Utc> {
257        Utc::now()
258    }
259
260    fn quiet_until(&self, at: DateTime<Utc>) -> Option<DateTime<Utc>> {
261        let until = *self.quiet_until.lock().unwrap_or_else(PoisonError::into_inner);
262        until.filter(|until| *until > at)
263    }
264
265    fn approvals(&self) -> Option<Arc<dyn ApprovalService>> {
266        Some(self.approvals.clone())
267    }
268
269    fn audit_trail(&self) -> Option<AuditTrail> {
270        Some(AuditTrail::new(Arc::new(self.recorder.clone())))
271    }
272
273    async fn start_turn(&self, run: NewRun) -> Result<String> {
274        if self.governance.is_frozen() {
275            return Err(KernelError::Frozen {
276                reason: self.governance.reason().unwrap_or_default(),
277            });
278        }
279        let mut turns = self.turns.lock().unwrap_or_else(PoisonError::into_inner);
280        if let Some((pid, _)) =
281            turns.iter().find(|(_, started)| started.idempotency_key == run.idempotency_key)
282        {
283            return Ok(pid.clone());
284        }
285        let pid = format!("turn-{}", turns.len() + 1);
286        turns.insert(pid.clone(), run);
287        Ok(pid)
288    }
289
290    async fn finished_turns(&self) -> Result<BoxStream<'static, RunRecord>> {
291        let receiver = self.finished.subscribe();
292        Ok(futures::stream::unfold(receiver, |mut receiver| async move {
293            loop {
294                match receiver.recv().await {
295                    Ok(record) => return Some((record, receiver)),
296                    Err(broadcast::error::RecvError::Lagged(_)) => {}
297                    Err(broadcast::error::RecvError::Closed) => return None,
298                }
299            }
300        })
301        .boxed())
302    }
303
304    async fn stop_all(&self, reason: &str, by: AuditActor) -> Result<()> {
305        self.governance.freeze_recorded(reason, by).await.map_err(KernelError::from)
306    }
307}
308
309/// One case's world: the adapter, the host, the binding store and the gateway over them.
310struct World {
311    adapter: Arc<dyn ChannelAdapter>,
312    host: Arc<ContractHost>,
313    bindings: Arc<dyn ChannelBindingStore>,
314    gateway: ChannelGateway,
315}
316
317impl World {
318    async fn new(harness: &dyn ChannelAdapterHarness) -> Self {
319        let adapter = harness.adapter().await;
320        let host = Arc::new(ContractHost::new());
321        let bindings: Arc<dyn ChannelBindingStore> = Arc::new(InMemoryChannelBindingStore::new());
322        let sink: Arc<dyn ChannelSink> = adapter.clone();
323        let gateway = ChannelGateway::builder(host.clone(), bindings.clone())
324            .sink(sink)
325            .home_url("https://home.example")
326            .build();
327        gateway.start().await.expect("the gateway starts");
328        Self { adapter, host, bindings, gateway }
329    }
330
331    async fn receive(&self, inbound: ChannelInbound) -> InboundOutcome {
332        self.gateway.receive(inbound).await.expect("the gateway takes the message")
333    }
334
335    /// Pairs `account` in `thread` to the person, as the person accepting its code does.
336    async fn pair(&self, account: &str, thread: &str) {
337        let hello = self.adapter.typed(account, thread, "hello").await;
338        assert_eq!(self.receive(hello).await, InboundOutcome::PairingRequested);
339        let code = self.adapter.pairing_code(thread).await.expect("the adapter delivered a code");
340        accept_pairing(self.bindings.as_ref(), &code, PERSON, &[GROUP.to_string()], Utc::now())
341            .await
342            .expect("the code pairs the account");
343    }
344
345    async fn wire(&self, thread: &str) -> String {
346        self.adapter.wire(thread).await.join("\n")
347    }
348}
349
350/// Polls `probe` every 10 ms for at most five seconds.
351async fn eventually<F, Fut>(what: &str, mut probe: F)
352where
353    F: FnMut() -> Fut,
354    Fut: std::future::Future<Output = bool>,
355{
356    let started = tokio::time::Instant::now();
357    while started.elapsed() < Duration::from_secs(5) {
358        if probe().await {
359            return;
360        }
361        tokio::time::sleep(Duration::from_millis(10)).await;
362    }
363    panic!("timed out waiting for {what}");
364}
365
366/// An unpaired account's message gets a pairing code in its thread and starts no turn.
367pub async fn an_unpaired_account_gets_a_code_and_starts_nothing(
368    harness: &dyn ChannelAdapterHarness,
369) {
370    let world = World::new(harness).await;
371    let inbound = world.adapter.typed("stranger", "t-stranger", "run rm -rf /").await;
372    assert_eq!(world.receive(inbound).await, InboundOutcome::PairingRequested);
373    assert!(
374        world.adapter.pairing_code("t-stranger").await.is_some(),
375        "the adapter showed the code"
376    );
377    assert!(world.host.turns().is_empty(), "nothing started");
378    let again = world.adapter.typed("stranger", "t-stranger", "hello?").await;
379    assert_eq!(world.receive(again).await, InboundOutcome::PairingWaiting);
380    assert!(world.host.turns().is_empty(), "still nothing started");
381    assert!(world.host.channel_actions().contains(&"pairing.requested".to_string()));
382}
383
384/// After its code is accepted the account's message starts a turn as its person and the
385/// reply comes back to the same thread.
386pub async fn a_paired_message_starts_a_turn_and_the_reply_returns_to_its_thread(
387    harness: &dyn ChannelAdapterHarness,
388) {
389    let world = World::new(harness).await;
390    world.pair("ana-chat", "t-ana").await;
391    let message = world.adapter.typed("ana-chat", "t-ana", "what's on today?").await;
392    let InboundOutcome::TurnStarted { pid } = world.receive(message).await else {
393        panic!("a paired message starts a turn");
394    };
395    let (_, run) = world.host.turns().into_iter().find(|(id, _)| *id == pid).expect("the turn");
396    assert_eq!(run.user_id, PERSON);
397    assert!(run.authenticated, "the pairing authenticates the person");
398    assert_eq!(run.principal, None, "a person's turn, not a service's");
399    assert_eq!(run.input["text"], "what's on today?");
400    world.host.finish(&pid, "Two meetings and the invoice.");
401    let adapter = world.adapter.clone();
402    eventually("the reply in the thread", || {
403        let adapter = adapter.clone();
404        async move { adapter.wire("t-ana").await.join("\n").contains("Two meetings and the invoice.") }
405    })
406    .await;
407    assert!(world.adapter.wire("t-other").await.is_empty(), "no other thread hears it");
408}
409
410/// The same platform message delivered twice starts one turn.
411pub async fn a_redelivered_message_starts_one_turn(harness: &dyn ChannelAdapterHarness) {
412    let world = World::new(harness).await;
413    world.pair("ana-chat", "t-ana").await;
414    let message = world.adapter.typed("ana-chat", "t-ana", "draft the reply").await;
415    let first = world.receive(message.clone()).await;
416    let second = world.receive(message).await;
417    assert_eq!(first, second);
418    assert_eq!(world.host.turns().len(), 1);
419}
420
421/// A card reaches the person's thread with its agent, summary and risk; no argument value
422/// leaves the machine.
423pub async fn decision_cards_carry_no_arguments(harness: &dyn ChannelAdapterHarness) {
424    let world = World::new(harness).await;
425    world.pair("ana-chat", "t-ana").await;
426    let canary = "canary-7f3a@client.example";
427    let request = world
428        .host
429        .ask(
430            &format!("Send the October invoice to {canary}"),
431            json!({"to": canary, "body": "secret-body-91c2", "amount": 4200}),
432            ApprovalRisk::Medium,
433        )
434        .await;
435    assert_eq!(world.gateway.ring(&request).await.expect("ring"), 1);
436    let wire = world.wire("t-ana").await;
437    assert!(wire.contains("Finance"), "the agent is named: {wire}");
438    assert!(wire.contains("Send the October invoice to"), "the summary is shown: {wire}");
439    for argument in [canary, "secret-body-91c2"] {
440        assert!(!wire.contains(argument), "an argument left the machine: {argument} in {wire}");
441    }
442    assert!(world.adapter.pressed("ana-chat", "t-ana", ChannelAnswer::AllowOnce).await.is_some());
443    assert!(world.adapter.pressed("ana-chat", "t-ana", ChannelAnswer::Deny).await.is_some());
444    assert!(world.host.channel_actions().contains(&"notify".to_string()));
445}
446
447/// "Allow once" approves at the card's version; a second press is answered "decided
448/// already" and decides nothing.
449pub async fn allow_once_decides_once_and_a_second_answer_is_already_decided(
450    harness: &dyn ChannelAdapterHarness,
451) {
452    let world = World::new(harness).await;
453    world.pair("ana-chat", "t-ana").await;
454    let request = world.host.ask("Send the invoice", json!({}), ApprovalRisk::Low).await;
455    world.gateway.ring(&request).await.expect("ring");
456    let press = world
457        .adapter
458        .pressed("ana-chat", "t-ana", ChannelAnswer::AllowOnce)
459        .await
460        .expect("a button");
461    assert!(matches!(world.receive(press.clone()).await, InboundOutcome::Decided { .. }));
462    let decided = world.host.decision(&request.id).await;
463    assert_eq!(decided.state, ApprovalState::Approved);
464    assert_eq!(decided.decisions.len(), 1);
465    assert_eq!(decided.decisions[0].approver.id, PERSON);
466    let mut again = press;
467    again.message_id.push_str("-again");
468    assert!(matches!(world.receive(again).await, InboundOutcome::AlreadyDecided { .. }));
469    assert_eq!(world.host.decision(&request.id).await.decisions.len(), 1, "decided once");
470    assert!(world.wire("t-ana").await.to_lowercase().contains("already"));
471}
472
473/// "Deny" rejects.
474pub async fn deny_rejects(harness: &dyn ChannelAdapterHarness) {
475    let world = World::new(harness).await;
476    world.pair("ana-chat", "t-ana").await;
477    let request = world.host.ask("Post the update", json!({}), ApprovalRisk::Medium).await;
478    world.gateway.ring(&request).await.expect("ring");
479    let press =
480        world.adapter.pressed("ana-chat", "t-ana", ChannelAnswer::Deny).await.expect("a button");
481    assert!(matches!(world.receive(press).await, InboundOutcome::Decided { .. }));
482    assert_eq!(world.host.decision(&request.id).await.state, ApprovalState::Rejected);
483}
484
485/// A high-risk card offers no button, and an answer forged for it decides nothing.
486pub async fn high_risk_offers_no_answer_and_a_forged_one_is_refused(
487    harness: &dyn ChannelAdapterHarness,
488) {
489    let world = World::new(harness).await;
490    world.pair("ana-chat", "t-ana").await;
491    for risk in [ApprovalRisk::High, ApprovalRisk::Critical] {
492        let request = world.host.ask("Pay the supplier", json!({}), risk).await;
493        world.gateway.ring(&request).await.expect("ring");
494        assert!(
495            world.adapter.pressed("ana-chat", "t-ana", ChannelAnswer::AllowOnce).await.is_none()
496        );
497        assert!(world.wire("t-ana").await.contains("https://home.example"), "it links to the home");
498        let forged = ChannelInbound::answer(
499            world.adapter.channel(),
500            "ana-chat",
501            "t-ana",
502            format!("forged-{risk:?}"),
503            &crate::channels::DecisionCard::from_request(&request, None),
504            ChannelAnswer::AllowOnce,
505        );
506        assert!(matches!(world.receive(forged).await, InboundOutcome::DecisionRefused { .. }));
507        assert_eq!(world.host.decision(&request.id).await.state, ApprovalState::Pending);
508    }
509}
510
511/// "stop all" stops everything; "resume" is refused and everything stays stopped.
512pub async fn stop_all_stops_and_resume_is_refused(harness: &dyn ChannelAdapterHarness) {
513    let world = World::new(harness).await;
514    world.pair("ana-chat", "t-ana").await;
515    let stop = world.adapter.typed("ana-chat", "t-ana", "stop all").await;
516    assert_eq!(world.receive(stop).await, InboundOutcome::Stopped);
517    assert!(world.host.is_stopped());
518    let resume = world.adapter.typed("ana-chat", "t-ana", "resume").await;
519    assert_eq!(world.receive(resume).await, InboundOutcome::ResumeRefused);
520    assert!(world.host.is_stopped(), "a chat thread cannot resume");
521    let actions = world.host.channel_actions();
522    assert!(
523        actions.contains(&"stop".to_string()) && actions.contains(&"resume.refused".to_string())
524    );
525    let origin = json!({ "kind": "chat", "channel": world.adapter.channel() });
526    let origins = world.host.channel_origins();
527    assert!(
528        !origins.is_empty() && origins.iter().all(|recorded| *recorded == origin),
529        "{origins:?}"
530    );
531}
532
533/// While everything is stopped a message starts nothing and says so.
534pub async fn a_stopped_kernel_starts_no_turn(harness: &dyn ChannelAdapterHarness) {
535    let world = World::new(harness).await;
536    world.pair("ana-chat", "t-ana").await;
537    world.host.stop_all("test", AuditActor::default()).await.expect("stop");
538    let message = world.adapter.typed("ana-chat", "t-ana", "are you there?").await;
539    assert_eq!(world.receive(message).await, InboundOutcome::TurnRefused);
540    assert!(world.host.turns().is_empty());
541    assert!(world.wire("t-ana").await.contains("stopped"));
542}
543
544/// An answer from an unpaired account decides nothing and gets a pairing code.
545pub async fn an_unpaired_account_cannot_answer(harness: &dyn ChannelAdapterHarness) {
546    let world = World::new(harness).await;
547    world.pair("ana-chat", "t-ana").await;
548    let request = world.host.ask("Send the invoice", json!({}), ApprovalRisk::Low).await;
549    world.gateway.ring(&request).await.expect("ring");
550    let card = crate::channels::DecisionCard::from_request(&request, None);
551    let forged = ChannelInbound::answer(
552        world.adapter.channel(),
553        "mallory",
554        "t-mallory",
555        "forged-1",
556        &card,
557        ChannelAnswer::AllowOnce,
558    );
559    assert_eq!(world.receive(forged).await, InboundOutcome::PairingRequested);
560    assert_eq!(world.host.decision(&request.id).await.state, ApprovalState::Pending);
561}
562
563/// After a restart, a decision that still waits is rung again on the person's thread.
564pub async fn a_restart_rings_what_still_waits(harness: &dyn ChannelAdapterHarness) {
565    let world = World::new(harness).await;
566    world.pair("ana-chat", "t-ana").await;
567    let waiting = world.host.ask("Send the invoice", json!({}), ApprovalRisk::Low).await;
568    let decided = world.host.ask("Post the update", json!({}), ApprovalRisk::Low).await;
569    world.gateway.ring(&decided).await.expect("ring");
570    let press =
571        world.adapter.pressed("ana-chat", "t-ana", ChannelAnswer::Deny).await.expect("a button");
572    assert!(matches!(world.receive(press).await, InboundOutcome::Decided { .. }));
573    assert_eq!(
574        world.gateway.ring_waiting().await.expect("ring waiting"),
575        1,
576        "only what still waits"
577    );
578    let card = crate::channels::DecisionCard::from_request(&waiting, None);
579    let wire = world.wire("t-ana").await;
580    assert!(wire.contains(&card.decision), "the waiting decision was rung: {wire}");
581}
582
583/// A card for a decision asked in quiet time arrives when quiet time ends.
584pub async fn quiet_time_holds_cards(harness: &dyn ChannelAdapterHarness) {
585    let world = World::new(harness).await;
586    world.pair("ana-chat", "t-ana").await;
587    let before = world.adapter.wire("t-ana").await.len();
588    world.host.set_quiet_until(Some(Utc::now() + chrono::Duration::milliseconds(300)));
589    let request = world.host.ask("Send the invoice", json!({}), ApprovalRisk::Low).await;
590    assert_eq!(world.gateway.ring(&request).await.expect("ring"), 0, "held during quiet time");
591    assert_eq!(world.adapter.wire("t-ana").await.len(), before, "nothing sent during quiet time");
592    let adapter = world.adapter.clone();
593    eventually("the held card", || {
594        let adapter = adapter.clone();
595        async move { adapter.pressed("ana-chat", "t-ana", ChannelAnswer::AllowOnce).await.is_some() }
596    })
597    .await;
598}
599
600/// Generates one test per [`channel_contract`](self) case for a `ChannelAdapterHarness` (spec 3.3 §10 K1; feature `channels`).
601///
602/// Used as [`process_store_conformance_tests!`](crate::process_store_conformance_tests) is;
603/// see the [module documentation](crate::conformance).
604#[cfg(feature = "channels")]
605#[macro_export]
606macro_rules! channel_contract_tests {
607    ($(#[$attr:meta])* harness = $harness:expr $(,)?) => {
608        $(#[$attr])*
609        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
610        async fn channel_contract_an_unpaired_account_gets_a_code_and_starts_nothing() {
611            $crate::conformance::channel_contract::an_unpaired_account_gets_a_code_and_starts_nothing(&$harness).await;
612        }
613        $(#[$attr])*
614        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
615        async fn channel_contract_a_paired_message_starts_a_turn_and_the_reply_returns_to_its_thread() {
616            $crate::conformance::channel_contract::a_paired_message_starts_a_turn_and_the_reply_returns_to_its_thread(&$harness).await;
617        }
618        $(#[$attr])*
619        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
620        async fn channel_contract_a_redelivered_message_starts_one_turn() {
621            $crate::conformance::channel_contract::a_redelivered_message_starts_one_turn(&$harness).await;
622        }
623        $(#[$attr])*
624        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
625        async fn channel_contract_decision_cards_carry_no_arguments() {
626            $crate::conformance::channel_contract::decision_cards_carry_no_arguments(&$harness).await;
627        }
628        $(#[$attr])*
629        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
630        async fn channel_contract_allow_once_decides_once_and_a_second_answer_is_already_decided() {
631            $crate::conformance::channel_contract::allow_once_decides_once_and_a_second_answer_is_already_decided(&$harness).await;
632        }
633        $(#[$attr])*
634        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
635        async fn channel_contract_deny_rejects() {
636            $crate::conformance::channel_contract::deny_rejects(&$harness).await;
637        }
638        $(#[$attr])*
639        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
640        async fn channel_contract_high_risk_offers_no_answer_and_a_forged_one_is_refused() {
641            $crate::conformance::channel_contract::high_risk_offers_no_answer_and_a_forged_one_is_refused(&$harness).await;
642        }
643        $(#[$attr])*
644        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
645        async fn channel_contract_stop_all_stops_and_resume_is_refused() {
646            $crate::conformance::channel_contract::stop_all_stops_and_resume_is_refused(&$harness).await;
647        }
648        $(#[$attr])*
649        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
650        async fn channel_contract_a_stopped_kernel_starts_no_turn() {
651            $crate::conformance::channel_contract::a_stopped_kernel_starts_no_turn(&$harness).await;
652        }
653        $(#[$attr])*
654        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
655        async fn channel_contract_an_unpaired_account_cannot_answer() {
656            $crate::conformance::channel_contract::an_unpaired_account_cannot_answer(&$harness).await;
657        }
658        $(#[$attr])*
659        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
660        async fn channel_contract_a_restart_rings_what_still_waits() {
661            $crate::conformance::channel_contract::a_restart_rings_what_still_waits(&$harness).await;
662        }
663        $(#[$attr])*
664        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
665        async fn channel_contract_quiet_time_holds_cards() {
666            $crate::conformance::channel_contract::quiet_time_holds_cards(&$harness).await;
667        }
668    };
669}