Skip to main content

adk_surface/
answers.rs

1//! How each answer was given (spec 3.3 §8.1 "Decided", §11).
2//!
3//! `adk_core::ApprovalDecision` records who decided and when, not the surface or the way the
4//! answer was given. The engine writes both to the audit record of every answer
5//! ([`SURFACE_AUDIT_DECIDE`]) and keeps them in an [`AnswerLog`], so a decision answered
6//! elsewhere reads "You said yes in Telegram at 07:31" on every other surface.
7//!
8//! | Log | Survives a restart | Reads |
9//! |---|---|---|
10//! | [`InMemoryAnswerLog`] | No | What this process recorded |
11//! | [`AuditAnswerLog`] | Yes | The `surface.decide` records of an `AuditLogStore` (the signed audit log), newest first |
12//! | [`RecordAnswerLog`] | Yes | A kernel's record over its control plane (`GET /api/kernel/record`), for a surface attached to the kernel, such as a terminal |
13
14use std::collections::{HashMap, HashSet};
15use std::sync::{Arc, Mutex};
16
17use adk_core::ApprovalRequest;
18use adk_core::audit_log::{AuditLogStore, AuditRecord};
19use adk_core::principal::SubjectRef;
20use adk_kernel::control::{ControlClient, RecordLine};
21use async_trait::async_trait;
22use chrono::{DateTime, Utc};
23
24use crate::error::Result;
25use crate::origin::{Origin, SurfaceKind, Via};
26use crate::rules::Answer;
27
28/// The audit action of an answer to a decision given through a surface (spec 3.3 §11).
29pub const SURFACE_AUDIT_DECIDE: &str = "surface.decide";
30
31/// One answer given through a surface.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct AnswerRecord {
34    /// The decision.
35    pub approval_id: String,
36    /// Who answered.
37    pub by: SubjectRef,
38    /// Where and how.
39    pub via: Via,
40    /// The answer.
41    pub answer: Answer,
42    /// When.
43    pub at: DateTime<Utc>,
44}
45
46/// Where the engine keeps how each answer was given (spec 3.3 §11).
47#[async_trait]
48pub trait AnswerLog: Send + Sync {
49    /// Records the answer that decided `record.approval_id`.
50    async fn record(&self, record: &AnswerRecord) -> Result<()>;
51
52    /// The answer that decided `approval_id`, when it was given through a surface.
53    async fn find(&self, approval_id: &str) -> Result<Option<AnswerRecord>>;
54
55    /// The answers given through a surface since `at`, oldest first: what "How you answered"
56    /// counts (spec 3.3 §5.1). The default lists none.
57    async fn since(&self, at: DateTime<Utc>) -> Result<Vec<AnswerRecord>> {
58        let _ = at;
59        Ok(Vec::new())
60    }
61
62    /// The answer that decided `request`, when it was given through a surface: what the
63    /// engine reads for a decided card. A log may use the request's times to read less; the
64    /// default calls [`find`](Self::find).
65    async fn find_for(&self, request: &ApprovalRequest) -> Result<Option<AnswerRecord>> {
66        self.find(&request.id).await
67    }
68}
69
70/// An [`AnswerLog`] in memory, for one process.
71///
72/// # Example
73///
74/// ```rust
75/// use adk_surface::{AnswerLog, InMemoryAnswerLog};
76///
77/// # futures::executor::block_on(async {
78/// let log = InMemoryAnswerLog::new();
79/// assert!(log.find("apr_1").await.unwrap().is_none());
80/// # });
81/// ```
82#[derive(Debug, Clone, Default)]
83pub struct InMemoryAnswerLog {
84    records: Arc<Mutex<HashMap<String, AnswerRecord>>>,
85}
86
87impl InMemoryAnswerLog {
88    /// An empty log.
89    pub fn new() -> Self {
90        Self::default()
91    }
92}
93
94#[async_trait]
95impl AnswerLog for InMemoryAnswerLog {
96    async fn record(&self, record: &AnswerRecord) -> Result<()> {
97        self.records
98            .lock()
99            .unwrap_or_else(|e| e.into_inner())
100            .insert(record.approval_id.clone(), record.clone());
101        Ok(())
102    }
103
104    async fn find(&self, approval_id: &str) -> Result<Option<AnswerRecord>> {
105        Ok(self.records.lock().unwrap_or_else(|e| e.into_inner()).get(approval_id).cloned())
106    }
107
108    async fn since(&self, at: DateTime<Utc>) -> Result<Vec<AnswerRecord>> {
109        let mut found: Vec<AnswerRecord> = self
110            .records
111            .lock()
112            .unwrap_or_else(|e| e.into_inner())
113            .values()
114            .filter(|record| record.at >= at)
115            .cloned()
116            .collect();
117        found.sort_by_key(|record| record.at);
118        Ok(found)
119    }
120}
121
122/// An [`AnswerLog`] over the audit log the engine's records go to: `record` writes nothing
123/// (the engine's [`AuditTrail`](adk_core::audit_log::AuditTrail) already wrote the
124/// `surface.decide` record), and `find` reads it back from the store, newest first, so every
125/// process over the same store, and a restarted one, sees how a decision was answered.
126///
127/// [`find_for`](AnswerLog::find_for), which the engine reads, stops at records older than the
128/// request, and remembers what it found: an answer, and the absence of one for a request
129/// decided long enough ago that its record would have been written. So a decision answered
130/// outside the surfaces, expired or cancelled reads the log once, back to its creation.
131#[derive(Clone)]
132pub struct AuditAnswerLog {
133    store: Arc<dyn AuditLogStore>,
134    found: Arc<Mutex<HashMap<String, AnswerRecord>>>,
135    absent: Arc<Mutex<HashSet<String>>>,
136}
137
138impl std::fmt::Debug for AuditAnswerLog {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        f.debug_struct("AuditAnswerLog").finish_non_exhaustive()
141    }
142}
143
144impl AuditAnswerLog {
145    /// Reads the `surface.decide` records of `store`.
146    pub fn new(store: Arc<dyn AuditLogStore>) -> Self {
147        Self { store, found: Arc::default(), absent: Arc::default() }
148    }
149
150    /// The `surface.decide` record of `approval_id`, read newest first, back to `since` when
151    /// set.
152    async fn scan(
153        &self,
154        approval_id: &str,
155        since: Option<DateTime<Utc>>,
156    ) -> Result<Option<AnswerRecord>> {
157        for log in self.store.logs().await? {
158            let mut end = self.store.size(&log).await?;
159            'log: while end > 0 {
160                let start = end.saturating_sub(AUDIT_PAGE);
161                let entries = self.store.read(&log, start..end).await?;
162                for entry in entries.iter().rev() {
163                    let Some(text) = &entry.record else { continue };
164                    let Ok(record) = serde_json::from_str::<AuditRecord>(text) else { continue };
165                    if let Some(answer) = answer_of(&record, approval_id) {
166                        return Ok(Some(answer));
167                    }
168                    if since.is_some_and(|since| record.ts < since) {
169                        break 'log;
170                    }
171                }
172                end = start;
173            }
174        }
175        Ok(None)
176    }
177
178    /// Every `surface.decide` record that decided something since `at`, oldest first.
179    async fn scan_since(&self, at: DateTime<Utc>) -> Result<Vec<AnswerRecord>> {
180        let mut found = Vec::new();
181        for log in self.store.logs().await? {
182            let mut end = self.store.size(&log).await?;
183            'log: while end > 0 {
184                let start = end.saturating_sub(AUDIT_PAGE);
185                let entries = self.store.read(&log, start..end).await?;
186                for entry in entries.iter().rev() {
187                    let Some(text) = &entry.record else { continue };
188                    let Ok(record) = serde_json::from_str::<AuditRecord>(text) else { continue };
189                    if record.ts < at - CLOCK_SLACK {
190                        break 'log;
191                    }
192                    if record.ts < at {
193                        continue;
194                    }
195                    let id =
196                        record.ext.get("approvalId").and_then(|v| v.as_str()).map(str::to_string);
197                    if let Some(answer) = id.and_then(|id| answer_of(&record, &id)) {
198                        found.push(answer);
199                    }
200                }
201                end = start;
202            }
203        }
204        found.sort_by_key(|record| record.at);
205        Ok(found)
206    }
207}
208
209/// How many entries one read of the audit log takes.
210const AUDIT_PAGE: u64 = 256;
211
212/// How much earlier than its request an answer's record is still looked for, for clocks
213/// that disagree.
214const CLOCK_SLACK: chrono::Duration = chrono::Duration::minutes(5);
215
216/// How long after a decision its `surface.decide` record may still be on its way, so a
217/// missing one is not yet remembered as missing.
218const RECORD_DELAY: chrono::Duration = chrono::Duration::minutes(5);
219
220/// How many requests [`AuditAnswerLog`] remembers before it starts again.
221const REMEMBERED: usize = 10_000;
222
223#[async_trait]
224impl AnswerLog for AuditAnswerLog {
225    async fn record(&self, _record: &AnswerRecord) -> Result<()> {
226        Ok(())
227    }
228
229    async fn find(&self, approval_id: &str) -> Result<Option<AnswerRecord>> {
230        self.scan(approval_id, None).await
231    }
232
233    async fn since(&self, at: DateTime<Utc>) -> Result<Vec<AnswerRecord>> {
234        self.scan_since(at).await
235    }
236
237    async fn find_for(&self, request: &ApprovalRequest) -> Result<Option<AnswerRecord>> {
238        if let Some(found) =
239            self.found.lock().unwrap_or_else(|e| e.into_inner()).get(&request.id).cloned()
240        {
241            return Ok(Some(found));
242        }
243        if self.absent.lock().unwrap_or_else(|e| e.into_inner()).contains(&request.id) {
244            return Ok(None);
245        }
246        let found = self.scan(&request.id, Some(request.created_at - CLOCK_SLACK)).await?;
247        match &found {
248            Some(answer) => {
249                let mut remembered = self.found.lock().unwrap_or_else(|e| e.into_inner());
250                if remembered.len() >= REMEMBERED {
251                    remembered.clear();
252                }
253                remembered.insert(request.id.clone(), answer.clone());
254            }
255            None => {
256                let decided = request
257                    .resolved_at
258                    .or_else(|| request.decisions.last().map(|decision| decision.decided_at));
259                if request.state.is_terminal()
260                    && decided.is_some_and(|at| at + RECORD_DELAY < Utc::now())
261                {
262                    let mut remembered = self.absent.lock().unwrap_or_else(|e| e.into_inner());
263                    if remembered.len() >= REMEMBERED {
264                        remembered.clear();
265                    }
266                    remembered.insert(request.id.clone());
267                }
268            }
269        }
270        Ok(found)
271    }
272}
273
274/// The answer a `surface.decide` record holds for `approval_id`, when it decided it.
275pub(crate) fn answer_of(record: &AuditRecord, approval_id: &str) -> Option<AnswerRecord> {
276    if record.action != SURFACE_AUDIT_DECIDE {
277        return None;
278    }
279    let ext = &record.ext;
280    if ext.get("approvalId").and_then(|v| v.as_str()) != Some(approval_id)
281        || ext.get("outcome").and_then(|v| v.as_str()) != Some("decided")
282    {
283        return None;
284    }
285    let surface: SurfaceKind = serde_json::from_value(ext.get("surface")?.clone()).ok()?;
286    let origin: Origin = serde_json::from_value(ext.get("origin")?.clone()).ok()?;
287    let answer: Answer = serde_json::from_value(ext.get("answer")?.clone()).ok()?;
288    let by = record.actor.on_behalf_of.clone()?;
289    Some(AnswerRecord {
290        approval_id: approval_id.to_string(),
291        by,
292        via: Via { surface, origin },
293        answer,
294        at: record.ts,
295    })
296}
297
298/// How many of the record's latest actions [`RecordAnswerLog`] reads: the most one
299/// `GET /api/kernel/record` answers.
300pub const RECORD_LINES: usize = 500;
301
302/// An [`AnswerLog`] over a kernel's record, for a surface attached to the kernel over its
303/// control plane (spec 3.3 §5.2, §10 K5, §11): a decision answered in Telegram reads "You said
304/// yes in Telegram at 07:31" in the terminal too.
305///
306/// `find` reads the answers this surface gave first, then the `surface.decide` lines among the
307/// record's latest [`RECORD_LINES`] actions (`GET /api/kernel/record`, the operator's or a
308/// paired device's with `read`). A record line says how an answer was given, not on which
309/// surface: `chat` names its channel, `touch` reads as the phone, `pointer` as the home,
310/// `keyboard` as the terminal. An answer older than those lines, or a kernel that shows no
311/// record, reads without where it was given.
312///
313/// # Example
314///
315/// ```rust,no_run
316/// use std::sync::Arc;
317/// use adk_kernel::control::ControlClient;
318/// use adk_surface::{ControlSource, RecordAnswerLog, SurfaceEngine};
319///
320/// # async fn example(home: &std::path::Path) -> adk_surface::Result<()> {
321/// let client = ControlClient::connect_local(home).await?.expect("a kernel is running");
322/// let answers = Arc::new(RecordAnswerLog::new(client.clone()));
323/// let source = ControlSource::new(client, "adk-rust", "adk-rust");
324/// let engine = SurfaceEngine::builder(Arc::new(source)).answers(answers).build();
325/// # let _ = engine;
326/// # Ok(())
327/// # }
328/// ```
329#[derive(Clone)]
330pub struct RecordAnswerLog {
331    client: ControlClient,
332    given_here: InMemoryAnswerLog,
333}
334
335impl std::fmt::Debug for RecordAnswerLog {
336    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
337        f.debug_struct("RecordAnswerLog")
338            .field("endpoint", &self.client.endpoint())
339            .finish_non_exhaustive()
340    }
341}
342
343impl RecordAnswerLog {
344    /// Reads the record of the kernel `client` reaches.
345    pub fn new(client: ControlClient) -> Self {
346        Self { client, given_here: InMemoryAnswerLog::new() }
347    }
348}
349
350#[async_trait]
351impl AnswerLog for RecordAnswerLog {
352    async fn record(&self, record: &AnswerRecord) -> Result<()> {
353        self.given_here.record(record).await
354    }
355
356    async fn find(&self, approval_id: &str) -> Result<Option<AnswerRecord>> {
357        if let Some(found) = self.given_here.find(approval_id).await? {
358            return Ok(Some(found));
359        }
360        match self.client.record(Some(RECORD_LINES)).await {
361            Ok(lines) => Ok(lines.iter().find_map(|line| answer_of_line(line, approval_id))),
362            Err(error) => {
363                tracing::debug!(error = %error, "the kernel's record could not be read");
364                Ok(None)
365            }
366        }
367    }
368
369    async fn since(&self, at: DateTime<Utc>) -> Result<Vec<AnswerRecord>> {
370        let mut found: HashMap<String, AnswerRecord> = HashMap::new();
371        if let Ok(lines) = self.client.record(Some(RECORD_LINES)).await {
372            for line in lines.iter().filter(|line| line.at >= at) {
373                if let Some(answer) = line.target.as_deref().and_then(|id| answer_of_line(line, id))
374                {
375                    found.insert(answer.approval_id.clone(), answer);
376                }
377            }
378        }
379        for answer in self.given_here.since(at).await? {
380            found.insert(answer.approval_id.clone(), answer);
381        }
382        let mut found: Vec<AnswerRecord> = found.into_values().collect();
383        found.sort_by_key(|record| record.at);
384        Ok(found)
385    }
386}
387
388/// How a person answered since a time (spec 3.3 §5.1 "How you answered"): how many of each
389/// answer, and on which surfaces. `GET /surface/answers`.
390#[derive(
391    Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
392)]
393#[serde(rename_all = "camelCase")]
394pub struct AnswerSummary {
395    /// Counted from.
396    pub since: DateTime<Utc>,
397    /// Every answer.
398    pub total: u32,
399    /// "Allow once".
400    pub allowed_once: u32,
401    /// "Always allow".
402    pub always_allowed: u32,
403    /// Edited, then allowed.
404    pub edited: u32,
405    /// "Deny".
406    pub denied: u32,
407    /// How many were given on each surface, most first.
408    pub surfaces: Vec<SurfaceCount>,
409    /// "12 answers: 9 allowed once, 2 always allowed, 1 denied".
410    pub text: String,
411}
412
413/// How many answers were given on one surface.
414#[derive(
415    Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
416)]
417#[serde(rename_all = "camelCase")]
418pub struct SurfaceCount {
419    /// The surface.
420    pub surface: SurfaceKind,
421    /// How many.
422    pub count: u32,
423}
424
425impl AnswerSummary {
426    /// The summary of `records`, the answers since `since`.
427    pub fn of(since: DateTime<Utc>, records: &[AnswerRecord]) -> Self {
428        let count = |answer: Answer| {
429            u32::try_from(records.iter().filter(|record| record.answer == answer).count())
430                .unwrap_or(u32::MAX)
431        };
432        let mut surfaces: Vec<SurfaceCount> = Vec::new();
433        for record in records {
434            match surfaces.iter_mut().find(|entry| entry.surface == record.via.surface) {
435                Some(entry) => entry.count += 1,
436                None => surfaces.push(SurfaceCount { surface: record.via.surface, count: 1 }),
437            }
438        }
439        surfaces.sort_by_key(|entry| std::cmp::Reverse(entry.count));
440        let (allowed_once, always_allowed, edited, denied) = (
441            count(Answer::AllowOnce),
442            count(Answer::AlwaysAllow),
443            count(Answer::Edit),
444            count(Answer::Deny),
445        );
446        let total = u32::try_from(records.len()).unwrap_or(u32::MAX);
447        Self {
448            since,
449            total,
450            allowed_once,
451            always_allowed,
452            edited,
453            denied,
454            surfaces,
455            text: crate::words::answers_line(total, allowed_once, always_allowed, edited, denied),
456        }
457    }
458}
459
460/// The answer a record line of `surface.decide` holds for `approval_id`, when it decided it.
461pub(crate) fn answer_of_line(line: &RecordLine, approval_id: &str) -> Option<AnswerRecord> {
462    if line.action != SURFACE_AUDIT_DECIDE
463        || line.target.as_deref() != Some(approval_id)
464        || line.outcome.as_deref() != Some("decided")
465    {
466        return None;
467    }
468    let (surface, origin) = match line.how.as_deref()? {
469        "chat" => (
470            SurfaceKind::Chat,
471            Origin::Chat { channel: line.channel.clone().unwrap_or_else(|| "chat".into()) },
472        ),
473        "touch" => (SurfaceKind::Phone, Origin::Touch),
474        "pointer" => (SurfaceKind::Web, Origin::Pointer),
475        "keyboard" => (SurfaceKind::Terminal, Origin::Keyboard),
476        "voice" => (SurfaceKind::Voice, Origin::Voice),
477        _ => return None,
478    };
479    let answer = match line.decision.as_deref()? {
480        "approved" => Answer::AllowOnce,
481        "rejected" => Answer::Deny,
482        _ => return None,
483    };
484    Some(AnswerRecord {
485        approval_id: approval_id.to_string(),
486        by: SubjectRef::human(line.subject.clone()?),
487        via: Via { surface, origin },
488        answer,
489        at: line.at,
490    })
491}
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496    use adk_core::audit_log::{
497        AuditActor, AuditAppend, AuditHash, AuditLogEntry, AuditRecordDraft, AuditRecordKind,
498        InMemoryAuditLogStore,
499    };
500    use serde_json::json;
501
502    fn entry(
503        seq: u64,
504        approval_id: &str,
505        outcome: &str,
506        origin: serde_json::Value,
507    ) -> AuditLogEntry {
508        let record = AuditRecordDraft::new(AuditRecordKind::Approval, SURFACE_AUDIT_DECIDE)
509            .actor(AuditActor::subject(SubjectRef::human("ana")))
510            .ext("approvalId", json!(approval_id))
511            .ext("outcome", json!(outcome))
512            .ext("answer", json!("allowOnce"))
513            .ext("surface", json!("chat"))
514            .ext("origin", origin)
515            .into_record("replica-1", seq, Utc::now(), None);
516        AuditLogEntry {
517            seq,
518            leaf_hash: AuditHash([seq as u8; 32]),
519            record: Some(serde_json::to_string(&record).unwrap()),
520        }
521    }
522
523    #[tokio::test]
524    async fn the_audit_log_says_how_a_decision_was_answered() {
525        let store = Arc::new(InMemoryAuditLogStore::new());
526        let telegram = json!({ "kind": "chat", "channel": "Telegram" });
527        store
528            .append(AuditAppend {
529                log_id: "replica-1".into(),
530                entries: vec![
531                    entry(0, "apr_1", "decided", telegram.clone()),
532                    entry(1, "apr_1", "already_decided", json!({ "kind": "pointer" })),
533                    entry(2, "apr_2", "refused", telegram),
534                ],
535                nodes: vec![],
536            })
537            .await
538            .unwrap();
539        let log = AuditAnswerLog::new(store);
540        let found = log.find("apr_1").await.unwrap().unwrap();
541        assert_eq!(found.via.origin, Origin::Chat { channel: "Telegram".into() });
542        assert_eq!(found.by, SubjectRef::human("ana"));
543        assert_eq!(found.answer, Answer::AllowOnce);
544        assert!(log.find("apr_2").await.unwrap().is_none(), "a refused answer decided nothing");
545    }
546
547    /// "How you answered" reads every answer the audit log holds since a time: a refused or
548    /// repeated answer is none, and nothing before the time is counted (spec 3.3 §5.1).
549    #[tokio::test]
550    async fn the_audit_log_lists_the_answers_since_a_time() {
551        let store = Arc::new(InMemoryAuditLogStore::new());
552        let pointer = json!({ "kind": "pointer" });
553        store
554            .append(AuditAppend {
555                log_id: "replica-1".into(),
556                entries: vec![
557                    entry(0, "apr_1", "decided", pointer.clone()),
558                    entry(1, "apr_1", "already_decided", pointer.clone()),
559                    entry(2, "apr_2", "refused", pointer.clone()),
560                    entry(3, "apr_3", "decided", pointer),
561                ],
562                nodes: vec![],
563            })
564            .await
565            .unwrap();
566        let log = AuditAnswerLog::new(store);
567        let since = log.since(Utc::now() - chrono::Duration::hours(1)).await.unwrap();
568        assert_eq!(
569            since.iter().map(|answer| answer.approval_id.as_str()).collect::<Vec<_>>(),
570            ["apr_1", "apr_3"]
571        );
572        assert!(log.since(Utc::now() + chrono::Duration::hours(1)).await.unwrap().is_empty());
573        let memory = InMemoryAnswerLog::new();
574        for answer in &since {
575            memory.record(answer).await.unwrap();
576        }
577        assert_eq!(memory.since(Utc::now() - chrono::Duration::hours(1)).await.unwrap().len(), 2);
578    }
579
580    /// A kernel's record line of an answer given in Telegram says where it was given; a line
581    /// of another decision, a refused answer or another action says nothing (spec 3.3 §12
582    /// phase 1: the terminal shows "You said yes in Telegram").
583    #[test]
584    fn a_record_line_says_how_a_decision_was_answered() {
585        let at = Utc::now();
586        let line = |id: &str, outcome: &str| {
587            RecordLine::new(7, at, SURFACE_AUDIT_DECIDE)
588                .with_subject("ana")
589                .with_decision("approved")
590                .with_outcome(outcome)
591                .with_how("chat", Some("Telegram"))
592                .with_target(id)
593        };
594        let found = answer_of_line(&line("apr_1", "decided"), "apr_1").unwrap();
595        assert_eq!(
596            found,
597            AnswerRecord {
598                approval_id: "apr_1".into(),
599                by: SubjectRef::human("ana"),
600                via: Via {
601                    surface: SurfaceKind::Chat,
602                    origin: Origin::Chat { channel: "Telegram".into() },
603                },
604                answer: Answer::AllowOnce,
605                at,
606            }
607        );
608        assert_eq!(found.via.phrase(), "in Telegram");
609        assert!(answer_of_line(&line("apr_1", "decided"), "apr_2").is_none());
610        assert!(answer_of_line(&line("apr_1", "refused"), "apr_1").is_none());
611        let control =
612            RecordLine::new(8, at, "kernel.control").with_subject("ana").with_target("apr_1");
613        assert!(answer_of_line(&control, "apr_1").is_none());
614        let touch = RecordLine::new(9, at, SURFACE_AUDIT_DECIDE)
615            .with_subject("ana")
616            .with_decision("rejected")
617            .with_outcome("decided")
618            .with_how("touch", None)
619            .with_target("apr_3");
620        let found = answer_of_line(&touch, "apr_3").unwrap();
621        assert_eq!((found.via.phrase(), found.answer), ("on your phone".to_string(), Answer::Deny));
622    }
623}