Skip to main content

adk_kernel/control/
away.rs

1//! "While you were away" over the `/proc` ledger, with a cursor per device (spec 3.3 §10
2//! K4, §5.1 Today, §8.1; feature `proc`).
3//!
4//! | Route (under `/api`) | Caller | Does |
5//! |---|---|---|
6//! | `GET /kernel/away` | operator, or a device with `read` | The rows after the viewer's cursor: counts, spend, whether quiet time was respected, one line per event ([`AwayResponse`], [`AwayQuery`]) |
7//! | `POST /kernel/away/seen` | operator, or a device with `read` | Moves the viewer's cursor to a row it was shown ([`SeenRequest`]) |
8//! | `GET /kernel/away/lines/{seq}` | operator, or a device with `read` | One line with its ledger row: the line's record ([`AwayLineResponse`]); a row that makes no line is `404` |
9//!
10//! The viewer is the paired device a token admitted (`device:<id>`), else the name the
11//! surface gives (`viewer`, default `home`). Its cursor is a ledger sequence number kept in
12//! the [`ControlStore`](super::ControlStore), so the digest is exact across a restart: a
13//! page covers the rows after the cursor in sequence order, and only a row the viewer was
14//! shown is ever marked seen, so marking `through` and reading again skips no row and repeats
15//! none. A page stops before a missing sequence number younger than a few seconds, which a
16//! store that numbers rows before it commits them (PostgreSQL) may still fill. A viewer
17//! with no cursor reads the last day.
18//!
19//! | Line | Ledger row |
20//! |---|---|
21//! | `done`, `failed`, `stopped` | `process` of an agent, ending `completed`, `failed` or `cancelled` |
22//! | `suggestion` | `proposal` with effect `proposed` |
23//! | `question` | `observation` |
24//! | `decided` | `approval` or `rejection`: a person's answer to a held call, from its audit record; `decided` |
25//! | `failed` | `loop_guard` |
26//! | `stoppedAll`, `resumedAll` | `governance`, `frozen` or `unfrozen` |
27//!
28//! `spentMicroUsd` sums the `spend` rows of the page. Quiet time was respected when no
29//! suggestion's work started (`proposal` with effect `running`) inside a quiet window of its
30//! area, as admission keeps it (spec 3.2 §7.9), with the windows in force when it started: a
31//! quiet time changed since judges only what came after it.
32//!
33//! A line names its agent as the agent calls itself: `finance`, not
34//! `urn:adk:agent:adk-rust/finance`; the kernel's own rows say `kernel`.
35//!
36//! These routes serve the lines of the `/proc` ledger and the row of each line; the full
37//! ledger leaves the host only through the operator's recorded `GET /kernel/proc/ledger`.
38
39use std::collections::BTreeMap;
40use std::sync::Arc;
41
42use adk_core::{ApprovalService, InboxQuery};
43use axum::Json;
44use axum::Router;
45use axum::extract::{Path as UrlPath, Query, State};
46use axum::routing::{get, post};
47use chrono::{DateTime, FixedOffset, Utc};
48use serde::{Deserialize, Serialize};
49
50use super::paths;
51use super::routes::{Caller, ControlBackend};
52use super::store::AwayCursor;
53use crate::error::{KernelError, NOT_FOUND_CODE, Result};
54use crate::kernel::Kernel;
55use crate::partition::PartitionId;
56use crate::proc::{KERNEL_AGENT, Ledger, LedgerEntry, LedgerQuery};
57
58/// The most rows one page covers.
59pub const MAX_PAGE_ROWS: usize = 2_000;
60/// How far back a viewer with no cursor reads.
61const NEW_VIEWER_WINDOW: chrono::Duration = chrono::Duration::hours(24);
62/// How long a missing sequence number may still be filled by a commit in flight.
63const SETTLE: chrono::Duration = chrono::Duration::seconds(5);
64/// The viewer a surface that names none reads as.
65pub const DEFAULT_VIEWER: &str = "home";
66
67/// What a line of "While you were away" says happened (spec 3.3 §8.1).
68///
69/// # Example
70///
71/// ```rust
72/// use adk_kernel::control::api::AwayKind;
73///
74/// assert_eq!(serde_json::to_value(AwayKind::StoppedAll).unwrap(), "stoppedAll");
75/// ```
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78#[non_exhaustive]
79pub enum AwayKind {
80    /// An agent finished its work.
81    Done,
82    /// An agent's work failed, or the loop guard ended a turn.
83    Failed,
84    /// An agent's work was stopped.
85    Stopped,
86    /// An agent suggested something to do.
87    Suggestion,
88    /// The kernel asks whether something it noticed is right.
89    Question,
90    /// A decision was answered.
91    Decided,
92    /// Everything was stopped.
93    StoppedAll,
94    /// Everything was resumed.
95    ResumedAll,
96}
97
98impl AwayKind {
99    /// The line a ledger row makes, or `None` for a row that is no event of its own.
100    pub fn of(entry: &LedgerEntry) -> Option<Self> {
101        let agent = entry.agent != KERNEL_AGENT;
102        match (entry.kind.as_str(), entry.effect.as_deref()) {
103            ("process", Some("completed")) if agent => Some(Self::Done),
104            ("process", Some("failed")) if agent => Some(Self::Failed),
105            ("process", Some("cancelled")) if agent => Some(Self::Stopped),
106            ("proposal", Some("proposed")) => Some(Self::Suggestion),
107            ("observation", _) => Some(Self::Question),
108            // The answer's audit record is the ledger's row of a decision (spec 3.3 §12
109            // phase 2): the kernel publishes no `decided` event of its own.
110            ("approval" | "rejection" | "decided", _) => Some(Self::Decided),
111            ("loop_guard", _) => Some(Self::Failed),
112            ("governance", Some("frozen")) => Some(Self::StoppedAll),
113            ("governance", Some("unfrozen")) => Some(Self::ResumedAll),
114            _ => None,
115        }
116    }
117}
118
119/// One line of "While you were away", from one ledger row (spec 3.3 §5.1).
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121#[serde(rename_all = "camelCase")]
122#[non_exhaustive]
123pub struct AwayLine {
124    /// The ledger row's sequence number.
125    pub seq: u64,
126    /// When, in the person's local offset.
127    pub at: DateTime<FixedOffset>,
128    /// The area.
129    pub partition: PartitionId,
130    /// The agent.
131    pub agent: String,
132    /// What happened.
133    pub kind: AwayKind,
134    /// The row's effect, such as `failed` or `approve`.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub effect: Option<String>,
137    /// The line's record: `GET` it for the ledger row.
138    pub record: String,
139}
140
141impl AwayLine {
142    /// The line `entry` makes, or `None`.
143    pub fn of(entry: &LedgerEntry) -> Option<Self> {
144        let kind = AwayKind::of(entry)?;
145        // An answer says which it was, as a `decided` row's effect does.
146        let effect = entry.effect.clone().or_else(|| match entry.kind.as_str() {
147            "approval" => Some("approve".to_string()),
148            "rejection" => Some("deny".to_string()),
149            _ => None,
150        });
151        Some(Self {
152            seq: entry.seq,
153            at: entry.ts,
154            partition: entry.partition.clone(),
155            agent: agent_name(&entry.agent).to_string(),
156            kind,
157            effect,
158            record: format!(
159                "{}{}",
160                paths::API_PREFIX,
161                paths::AWAY_LINE.replace("{seq}", &entry.seq.to_string())
162            ),
163        })
164    }
165}
166
167/// The name an agent goes by: the last part of its `urn:adk:agent:<app>/<agent>` id, or the
168/// label the ledger keeps when it is no id (spec 3.3 §8 "No internal identifiers").
169fn agent_name(agent: &str) -> &str {
170    match agent.strip_prefix("urn:adk:agent:") {
171        Some(id) => id.rsplit('/').next().filter(|name| !name.is_empty()).unwrap_or(id),
172        None => agent,
173    }
174}
175
176/// How many lines of each kind a page holds.
177#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
178#[serde(rename_all = "camelCase")]
179#[non_exhaustive]
180pub struct AwayCounts {
181    /// Work finished.
182    pub done: usize,
183    /// Work failed.
184    pub failed: usize,
185    /// Work stopped.
186    pub stopped: usize,
187    /// Suggestions made.
188    pub suggestions: usize,
189    /// Questions asked.
190    pub questions: usize,
191    /// Decisions answered.
192    pub decided: usize,
193}
194
195impl AwayCounts {
196    fn add(&mut self, kind: AwayKind) {
197        match kind {
198            AwayKind::Done => self.done += 1,
199            AwayKind::Failed => self.failed += 1,
200            AwayKind::Stopped => self.stopped += 1,
201            AwayKind::Suggestion => self.suggestions += 1,
202            AwayKind::Question => self.questions += 1,
203            AwayKind::Decided => self.decided += 1,
204            AwayKind::StoppedAll | AwayKind::ResumedAll => {}
205        }
206    }
207}
208
209/// Whether quiet time was respected over a page (spec 3.3 §5.1).
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
211#[serde(rename_all = "camelCase")]
212#[non_exhaustive]
213pub struct QuietTimeReport {
214    /// No suggestion's work started inside quiet time.
215    pub respected: bool,
216    /// The ledger rows of work that started inside it.
217    #[serde(default, skip_serializing_if = "Vec::is_empty")]
218    pub breaches: Vec<u64>,
219}
220
221/// `GET /kernel/away` query (spec 3.3 §10 K4).
222///
223/// # Example
224///
225/// ```rust
226/// use adk_kernel::control::api::AwayQuery;
227///
228/// let query: AwayQuery = serde_json::from_value(serde_json::json!({ "viewer": "terminal" })).unwrap();
229/// assert_eq!(query.viewer.as_deref(), Some("terminal"));
230/// ```
231#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
232#[serde(rename_all = "camelCase")]
233pub struct AwayQuery {
234    /// The surface reading, when no device token names it: letters, digits, `.`, `_`
235    /// and `-`, at most 64. Defaults to `home`.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub viewer: Option<String>,
238    /// Read after this row instead of the viewer's cursor, to page on without marking seen.
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub after: Option<u64>,
241    /// At most this many rows; at most [`MAX_PAGE_ROWS`], the default.
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub limit: Option<usize>,
244}
245
246/// `GET /kernel/away` answer (spec 3.3 §10 K4, §5.1).
247#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
248#[serde(rename_all = "camelCase")]
249#[non_exhaustive]
250pub struct AwayResponse {
251    /// The viewer the page was read for.
252    pub viewer: String,
253    /// When the viewer last marked the digest seen; for a viewer with no cursor, the start
254    /// of the day it reads.
255    pub since: DateTime<Utc>,
256    /// The row the page starts after, when it starts after one.
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub after: Option<u64>,
259    /// The last row the page covers: mark it seen to move on.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub through: Option<u64>,
262    /// Rows after `through` are left for the next page.
263    pub more: bool,
264    /// How many lines of each kind.
265    pub counts: AwayCounts,
266    /// What the page's rows spent, in micro-USD.
267    pub spent_micro_usd: u64,
268    /// Whether quiet time was respected.
269    pub quiet_time: QuietTimeReport,
270    /// Decisions waiting for the caller now.
271    pub waiting: usize,
272    /// One line per event, oldest first.
273    pub lines: Vec<AwayLine>,
274}
275
276/// `POST /kernel/away/seen` body (spec 3.3 §10 K4).
277///
278/// # Example
279///
280/// ```rust
281/// use adk_kernel::control::api::SeenRequest;
282///
283/// let body = SeenRequest { viewer: None, through: 120 };
284/// assert_eq!(serde_json::to_value(&body).unwrap(), serde_json::json!({ "through": 120 }));
285/// ```
286#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
287#[serde(rename_all = "camelCase")]
288pub struct SeenRequest {
289    /// The surface marking, when no device token names it. Defaults to `home`.
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub viewer: Option<String>,
292    /// The last row the viewer was shown: a page's `through`.
293    pub through: u64,
294}
295
296/// `POST /kernel/away/seen` answer.
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(rename_all = "camelCase")]
299pub struct SeenResponse {
300    /// The cursor after the call; never behind where it was.
301    pub cursor: AwayCursor,
302}
303
304/// `GET /kernel/away/lines/{seq}` answer: a line's record.
305#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
306#[serde(rename_all = "camelCase")]
307pub struct AwayLineResponse {
308    /// The line the row makes.
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub line: Option<AwayLine>,
311    /// The ledger row: content-free, as `/proc` keeps it.
312    pub entry: LedgerEntry,
313}
314
315type Backend = State<Arc<dyn ControlBackend>>;
316
317/// The routes, relative to `/api`, over the backend in their state.
318pub(super) fn routes() -> Router<Arc<dyn ControlBackend>> {
319    Router::new()
320        .route(paths::AWAY, get(away))
321        .route(paths::AWAY_SEEN, post(seen))
322        .route(paths::AWAY_LINE, get(line))
323}
324
325/// The kernel and its ledger behind `backend`, or a `Config` error naming why there is
326/// none.
327fn ledger_of(backend: &dyn ControlBackend) -> Result<(&Kernel, Ledger)> {
328    let kernel = backend.kernel().ok_or_else(|| KernelError::Config {
329        reason: "\"While you were away\" reads a kernel's ledger; serve it from a Kernel".into(),
330    })?;
331    let ledger = kernel.ledger().cloned().ok_or_else(|| KernelError::Config {
332        reason: "this kernel keeps no activity ledger: build it with KernelBuilder::ledger, as \
333                 `adk-rust up` does"
334            .into(),
335    })?;
336    Ok((kernel, ledger))
337}
338
339/// The viewer of `caller`: its paired device, else `named`, else `home`.
340fn viewer_of(caller: &Caller, named: Option<&str>) -> Result<String> {
341    if let Some(device) = caller.context.metadata.get(crate::pairing::DEVICE_ID_METADATA) {
342        return Ok(format!("device:{device}"));
343    }
344    let viewer = named.unwrap_or(DEFAULT_VIEWER);
345    let valid = (1..=64).contains(&viewer.len())
346        && viewer.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
347    if !valid {
348        return Err(KernelError::Config {
349            reason: format!(
350                "`{viewer}` is not a viewer name: use up to 64 letters, digits, `.`, `_` or `-`"
351            ),
352        });
353    }
354    Ok(viewer.to_string())
355}
356
357/// The longest prefix of `rows` with no missing sequence number younger than [`SETTLE`]
358/// after `after`, and whether rows were held back.
359fn settled(
360    mut rows: Vec<LedgerEntry>,
361    after: Option<u64>,
362    now: DateTime<Utc>,
363) -> (Vec<LedgerEntry>, bool) {
364    let mut expected = after.and_then(|after| after.checked_add(1));
365    for (index, row) in rows.iter().enumerate() {
366        if let Some(expected) = expected
367            && row.seq != expected
368            && now - row.utc() < SETTLE
369        {
370            rows.truncate(index);
371            return (rows, true);
372        }
373        expected = row.seq.checked_add(1);
374    }
375    (rows, false)
376}
377
378/// The decisions waiting for `caller` now; zero on a kernel without an inbox.
379async fn waiting(
380    approvals: Option<&Arc<dyn ApprovalService>>,
381    caller: &Caller,
382    app: &str,
383) -> Result<usize> {
384    let Some(approvals) = approvals else { return Ok(0) };
385    let query = InboxQuery::for_approver(caller.subject(), caller.context.scopes.clone())
386        .with_app_name(app)
387        .with_limit(500);
388    Ok(approvals.inbox(query).await?.items.len())
389}
390
391async fn away(
392    State(backend): Backend,
393    caller: Caller,
394    Query(query): Query<AwayQuery>,
395) -> Result<Json<AwayResponse>> {
396    caller.require_operator("read what happened while you were away")?;
397    let (kernel, ledger) = ledger_of(backend.as_ref())?;
398    let viewer = viewer_of(&caller, query.viewer.as_deref())?;
399    let store = kernel.config().control.control_store.clone();
400    let cursor = store.cursor(&caller.context.user_id, &viewer).await?;
401    let now = ledger.clock().now();
402    let limit = query.limit.unwrap_or(MAX_PAGE_ROWS).clamp(1, MAX_PAGE_ROWS);
403    let after = query.after.or(cursor.as_ref().map(|cursor| cursor.seq));
404    let since = cursor.as_ref().map_or(now - NEW_VIEWER_WINDOW, |cursor| cursor.seen_at);
405    let rows_query = match after {
406        Some(after) => LedgerQuery::default().after(after),
407        None => LedgerQuery::default().from(since),
408    };
409    let mut rows = ledger.store().list(&rows_query.limit(limit + 1)).await?;
410    let full = rows.len() > limit;
411    rows.truncate(limit);
412    let (rows, held_back) = settled(rows, after, now);
413
414    let mut counts = AwayCounts::default();
415    let mut spent: u64 = 0;
416    let mut breaches = Vec::new();
417    let mut areas: BTreeMap<PartitionId, (super::settings::Start, Option<super::AreaSettings>)> =
418        BTreeMap::new();
419    let mut lines = Vec::new();
420    for row in &rows {
421        if row.kind == "spend" {
422            let micro = row.meta.get("micro_usd").and_then(serde_json::Value::as_u64);
423            spent = spent.saturating_add(micro.unwrap_or_default());
424        }
425        if row.kind == "proposal" && row.effect.as_deref() == Some("running") {
426            if !areas.contains_key(&row.partition) {
427                let start = super::settings::start_of(kernel, &row.partition).await?;
428                let changed = store.area_settings(&row.partition).await?;
429                areas.insert(row.partition.clone(), (start, changed));
430            }
431            let at = row.utc();
432            let (start, changed) = &areas[&row.partition];
433            let windows = super::settings::quiet_windows_at(start, changed.as_ref(), at);
434            if windows.iter().any(|window| window.contains(at)) {
435                breaches.push(row.seq);
436            }
437        }
438        if let Some(line) = AwayLine::of(row) {
439            counts.add(line.kind);
440            lines.push(line);
441        }
442    }
443    let waiting = waiting(backend.approvals(), &caller, backend.app_name()).await?;
444    Ok(Json(AwayResponse {
445        viewer,
446        since,
447        after,
448        through: rows.last().map(|row| row.seq).or(after),
449        more: full || held_back,
450        counts,
451        spent_micro_usd: spent,
452        quiet_time: QuietTimeReport { respected: breaches.is_empty(), breaches },
453        waiting,
454        lines,
455    }))
456}
457
458async fn seen(
459    State(backend): Backend,
460    caller: Caller,
461    Json(request): Json<SeenRequest>,
462) -> Result<Json<SeenResponse>> {
463    caller.require_operator("mark what happened while you were away seen")?;
464    let (kernel, ledger) = ledger_of(backend.as_ref())?;
465    let viewer = viewer_of(&caller, request.viewer.as_deref())?;
466    // A cursor never passes the last row: rows written after it would be skipped.
467    let query = LedgerQuery::default().after(request.through.saturating_sub(1)).limit(1);
468    if ledger.store().list(&query).await?.is_empty() {
469        return Err(KernelError::Config {
470            reason: format!(
471                "the ledger has no row {} yet: mark seen a page's `through`",
472                request.through
473            ),
474        });
475    }
476    let cursor = AwayCursor::new(
477        caller.context.user_id.clone(),
478        viewer,
479        request.through,
480        ledger.clock().now(),
481    );
482    let cursor = kernel.config().control.control_store.advance_cursor(cursor).await?;
483    Ok(Json(SeenResponse { cursor }))
484}
485
486async fn line(
487    State(backend): Backend,
488    caller: Caller,
489    UrlPath(seq): UrlPath<u64>,
490) -> Result<Json<AwayLineResponse>> {
491    caller.require_operator("read what happened while you were away")?;
492    let (_, ledger) = ledger_of(backend.as_ref())?;
493    let query = LedgerQuery::default().after(seq.saturating_sub(1)).limit(1);
494    let entry = ledger.store().list(&query).await?.into_iter().find(|entry| entry.seq == seq);
495    // Only a line's own row: the ledger itself leaves the host through the recorded export.
496    let Some((line, entry)) = entry.and_then(|entry| Some((AwayLine::of(&entry)?, entry))) else {
497        return Err(KernelError::Core(adk_core::AdkError::new(
498            adk_core::ErrorComponent::Server,
499            adk_core::ErrorCategory::NotFound,
500            NOT_FOUND_CODE,
501            format!("no line of \"While you were away\" is row {seq} of the ledger"),
502        )));
503    };
504    Ok(Json(AwayLineResponse { line: Some(line), entry }))
505}
506
507#[cfg(test)]
508mod tests {
509    use chrono::TimeZone;
510
511    use super::*;
512
513    fn row(seq: u64, at: DateTime<Utc>) -> LedgerEntry {
514        let mut entry: LedgerEntry = serde_json::from_value(serde_json::json!({
515            "ts": at.fixed_offset(), "partition": "default", "agent": "kernel", "kind": "wake",
516        }))
517        .unwrap();
518        entry.seq = seq;
519        entry
520    }
521
522    #[test]
523    fn a_young_gap_holds_the_page_back_and_an_old_one_does_not() {
524        let now = Utc.with_ymd_and_hms(2026, 10, 24, 7, 0, 0).unwrap();
525        let old = now - chrono::Duration::minutes(5);
526        let young = now - chrono::Duration::seconds(1);
527        let rows = vec![row(11, old), row(12, old), row(14, young), row(15, young)];
528        let (kept, held) = settled(rows.clone(), Some(10), now);
529        assert_eq!((kept.iter().map(|r| r.seq).collect::<Vec<_>>(), held), (vec![11, 12], true));
530        let rows = vec![row(11, old), row(13, old)];
531        let (kept, held) = settled(rows, Some(10), now);
532        assert_eq!((kept.len(), held), (2, false), "a gap older than the settle time stays a gap");
533        let (kept, held) = settled(vec![row(12, young)], Some(10), now);
534        assert!(kept.is_empty() && held, "the first row counts too");
535        let (kept, held) = settled(vec![row(40, young), row(41, young)], None, now);
536        assert_eq!((kept.len(), held), (2, false), "a viewer with no cursor starts anywhere");
537    }
538
539    #[test]
540    fn rows_make_the_lines_the_home_shows() {
541        let mut entry = row(3, Utc::now());
542        assert_eq!(AwayKind::of(&entry), None, "a wake is no event of its own");
543        entry.kind = "process".into();
544        entry.effect = Some("failed".into());
545        assert_eq!(AwayKind::of(&entry), None, "the kernel's own processes are not lines");
546        entry.agent = "urn:adk:agent:adk-rust/finance".into();
547        assert_eq!(AwayKind::of(&entry), Some(AwayKind::Failed));
548        let line = AwayLine::of(&entry).unwrap();
549        assert_eq!(line.record, "/api/kernel/away/lines/3");
550        entry.kind = "governance".into();
551        entry.effect = Some("frozen".into());
552        assert_eq!(AwayKind::of(&entry), Some(AwayKind::StoppedAll));
553    }
554
555    /// A person's answer reaches the ledger as the `approval` or `rejection` row of its audit
556    /// record, and is a decided line saying which it was (spec 3.3 §12 phase 2).
557    #[test]
558    fn an_answer_is_a_decided_line() {
559        let mut entry = row(7, Utc::now());
560        entry.agent = "urn:adk:agent:adk-rust/adk-rust".into();
561        for (kind, effect) in [("approval", "approve"), ("rejection", "deny")] {
562            entry.kind = kind.into();
563            entry.effect = None;
564            let line = AwayLine::of(&entry).expect("an answer is a line");
565            assert_eq!((line.kind, line.effect.as_deref()), (AwayKind::Decided, Some(effect)));
566        }
567        entry.kind = "held".into();
568        assert_eq!(AwayKind::of(&entry), None, "a held call is no answer");
569    }
570}